Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / renderer / service_worker / service_worker_context_client.cc
blob7b43099c3c990b04ae97ce4beaf2cd112f4e2362
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/child/worker_task_runner.h"
28 #include "content/common/devtools_messages.h"
29 #include "content/common/message_port_messages.h"
30 #include "content/common/mojo/service_registry_impl.h"
31 #include "content/common/service_worker/embedded_worker_messages.h"
32 #include "content/common/service_worker/service_worker_messages.h"
33 #include "content/public/common/referrer.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/WebReferrerPolicy.h"
45 #include "third_party/WebKit/public/platform/WebServiceWorkerClientQueryOptions.h"
46 #include "third_party/WebKit/public/platform/WebServiceWorkerRequest.h"
47 #include "third_party/WebKit/public/platform/WebServiceWorkerResponse.h"
48 #include "third_party/WebKit/public/platform/WebString.h"
49 #include "third_party/WebKit/public/platform/modules/background_sync/WebSyncRegistration.h"
50 #include "third_party/WebKit/public/platform/modules/notifications/WebNotificationData.h"
51 #include "third_party/WebKit/public/web/WebDataSource.h"
52 #include "third_party/WebKit/public/web/WebServiceWorkerContextClient.h"
53 #include "third_party/WebKit/public/web/WebServiceWorkerContextProxy.h"
54 #include "third_party/WebKit/public/web/WebServiceWorkerNetworkProvider.h"
56 namespace content {
58 namespace {
60 // For now client must be a per-thread instance.
61 base::LazyInstance<base::ThreadLocalPointer<ServiceWorkerContextClient>>::
62 Leaky g_worker_client_tls = LAZY_INSTANCE_INITIALIZER;
64 void CallWorkerContextDestroyedOnMainThread(int embedded_worker_id) {
65 if (!RenderThreadImpl::current() ||
66 !RenderThreadImpl::current()->embedded_worker_dispatcher())
67 return;
68 RenderThreadImpl::current()->embedded_worker_dispatcher()->
69 WorkerContextDestroyed(embedded_worker_id);
72 // We store an instance of this class in the "extra data" of the WebDataSource
73 // and attach a ServiceWorkerNetworkProvider to it as base::UserData.
74 // (see createServiceWorkerNetworkProvider).
75 class DataSourceExtraData
76 : public blink::WebDataSource::ExtraData,
77 public base::SupportsUserData {
78 public:
79 DataSourceExtraData() {}
80 virtual ~DataSourceExtraData() {}
83 // Called on the main thread only and blink owns it.
84 class WebServiceWorkerNetworkProviderImpl
85 : public blink::WebServiceWorkerNetworkProvider {
86 public:
87 // Blink calls this method for each request starting with the main script,
88 // we tag them with the provider id.
89 virtual void willSendRequest(
90 blink::WebDataSource* data_source,
91 blink::WebURLRequest& request) {
92 ServiceWorkerNetworkProvider* provider =
93 ServiceWorkerNetworkProvider::FromDocumentState(
94 static_cast<DataSourceExtraData*>(data_source->extraData()));
95 scoped_ptr<RequestExtraData> extra_data(new RequestExtraData);
96 extra_data->set_service_worker_provider_id(provider->provider_id());
97 request.setExtraData(extra_data.release());
101 void SendPostMessageToClientOnMainThread(
102 ThreadSafeSender* sender,
103 int routing_id,
104 const std::string& uuid,
105 const base::string16& message,
106 scoped_ptr<blink::WebMessagePortChannelArray> channels) {
107 sender->Send(new ServiceWorkerHostMsg_PostMessageToClient(
108 routing_id, uuid, message,
109 WebMessagePortChannelImpl::ExtractMessagePortIDs(channels.Pass())));
112 void SendCrossOriginMessageToClientOnMainThread(
113 ThreadSafeSender* sender,
114 int message_port_id,
115 const base::string16& message,
116 scoped_ptr<blink::WebMessagePortChannelArray> channels) {
117 sender->Send(new MessagePortHostMsg_PostMessage(
118 message_port_id, MessagePortMessage(message),
119 WebMessagePortChannelImpl::ExtractMessagePortIDs(channels.Pass())));
122 blink::WebURLRequest::FetchRequestMode GetBlinkFetchRequestMode(
123 FetchRequestMode mode) {
124 return static_cast<blink::WebURLRequest::FetchRequestMode>(mode);
127 blink::WebURLRequest::FetchCredentialsMode GetBlinkFetchCredentialsMode(
128 FetchCredentialsMode credentials_mode) {
129 return static_cast<blink::WebURLRequest::FetchCredentialsMode>(
130 credentials_mode);
133 blink::WebURLRequest::RequestContext GetBlinkRequestContext(
134 RequestContextType request_context_type) {
135 return static_cast<blink::WebURLRequest::RequestContext>(
136 request_context_type);
139 blink::WebURLRequest::FrameType GetBlinkFrameType(
140 RequestContextFrameType frame_type) {
141 return static_cast<blink::WebURLRequest::FrameType>(frame_type);
144 blink::WebServiceWorkerClientInfo
145 ToWebServiceWorkerClientInfo(const ServiceWorkerClientInfo& client_info) {
146 DCHECK(client_info.IsValid());
148 blink::WebServiceWorkerClientInfo web_client_info;
150 web_client_info.uuid = base::UTF8ToUTF16(client_info.client_uuid);
151 web_client_info.pageVisibilityState = client_info.page_visibility_state;
152 web_client_info.isFocused = client_info.is_focused;
153 web_client_info.url = client_info.url;
154 web_client_info.frameType = GetBlinkFrameType(client_info.frame_type);
155 web_client_info.clientType = client_info.client_type;
157 return web_client_info;
160 } // namespace
162 // Holding data that needs to be bound to the worker context on the
163 // worker thread.
164 struct ServiceWorkerContextClient::WorkerContextData {
165 using ClientsCallbacksMap =
166 IDMap<blink::WebServiceWorkerClientsCallbacks, IDMapOwnPointer>;
167 using ClaimClientsCallbacksMap =
168 IDMap<blink::WebServiceWorkerClientsClaimCallbacks, IDMapOwnPointer>;
169 using ClientCallbacksMap =
170 IDMap<blink::WebServiceWorkerClientCallbacks, IDMapOwnPointer>;
171 using SkipWaitingCallbacksMap =
172 IDMap<blink::WebServiceWorkerSkipWaitingCallbacks, IDMapOwnPointer>;
173 using SyncEventCallbacksMap =
174 IDMap<const mojo::Callback<void(ServiceWorkerEventStatus)>,
175 IDMapOwnPointer>;
177 explicit WorkerContextData(ServiceWorkerContextClient* owner)
178 : weak_factory(owner), proxy_weak_factory(owner->proxy_) {}
180 ~WorkerContextData() {
181 DCHECK(thread_checker.CalledOnValidThread());
184 // Pending callbacks for GetClientDocuments().
185 ClientsCallbacksMap clients_callbacks;
187 // Pending callbacks for OpenWindow() and FocusClient().
188 ClientCallbacksMap client_callbacks;
190 // Pending callbacks for SkipWaiting().
191 SkipWaitingCallbacksMap skip_waiting_callbacks;
193 // Pending callbacks for ClaimClients().
194 ClaimClientsCallbacksMap claim_clients_callbacks;
196 // Pending callbacks for Background Sync Events
197 SyncEventCallbacksMap sync_event_callbacks;
199 ServiceRegistryImpl service_registry;
201 base::ThreadChecker thread_checker;
202 base::WeakPtrFactory<ServiceWorkerContextClient> weak_factory;
203 base::WeakPtrFactory<blink::WebServiceWorkerContextProxy> proxy_weak_factory;
206 ServiceWorkerContextClient*
207 ServiceWorkerContextClient::ThreadSpecificInstance() {
208 return g_worker_client_tls.Pointer()->Get();
211 ServiceWorkerContextClient::ServiceWorkerContextClient(
212 int embedded_worker_id,
213 int64 service_worker_version_id,
214 const GURL& service_worker_scope,
215 const GURL& script_url,
216 int worker_devtools_agent_route_id)
217 : embedded_worker_id_(embedded_worker_id),
218 service_worker_version_id_(service_worker_version_id),
219 service_worker_scope_(service_worker_scope),
220 script_url_(script_url),
221 worker_devtools_agent_route_id_(worker_devtools_agent_route_id),
222 sender_(ChildThreadImpl::current()->thread_safe_sender()),
223 main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()),
224 proxy_(nullptr) {
225 TRACE_EVENT_ASYNC_BEGIN0("ServiceWorker",
226 "ServiceWorkerContextClient::StartingWorkerContext",
227 this);
228 TRACE_EVENT_ASYNC_STEP_INTO0(
229 "ServiceWorker",
230 "ServiceWorkerContextClient::StartingWorkerContext",
231 this,
232 "PrepareWorker");
235 ServiceWorkerContextClient::~ServiceWorkerContextClient() {}
237 void ServiceWorkerContextClient::OnMessageReceived(
238 int thread_id,
239 int embedded_worker_id,
240 const IPC::Message& message) {
241 CHECK_EQ(embedded_worker_id_, embedded_worker_id);
242 bool handled = true;
243 IPC_BEGIN_MESSAGE_MAP(ServiceWorkerContextClient, message)
244 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_ActivateEvent, OnActivateEvent)
245 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_FetchEvent, OnFetchEvent)
246 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_InstallEvent, OnInstallEvent)
247 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_NotificationClickEvent,
248 OnNotificationClickEvent)
249 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_PushEvent, OnPushEvent)
250 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_GeofencingEvent, OnGeofencingEvent)
251 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_MessageToWorker, OnPostMessage)
252 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_CrossOriginMessageToWorker,
253 OnCrossOriginMessageToWorker)
254 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_DidGetClients, OnDidGetClients)
255 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_OpenWindowResponse,
256 OnOpenWindowResponse)
257 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_OpenWindowError,
258 OnOpenWindowError)
259 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_FocusClientResponse,
260 OnFocusClientResponse)
261 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_DidSkipWaiting, OnDidSkipWaiting)
262 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_DidClaimClients, OnDidClaimClients)
263 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_ClaimClientsError, OnClaimClientsError)
264 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_Ping, OnPing);
265 IPC_MESSAGE_UNHANDLED(handled = false)
266 IPC_END_MESSAGE_MAP()
267 DCHECK(handled);
270 void ServiceWorkerContextClient::BindServiceRegistry(
271 mojo::InterfaceRequest<mojo::ServiceProvider> services,
272 mojo::ServiceProviderPtr exposed_services) {
273 context_->service_registry.Bind(services.Pass());
274 context_->service_registry.BindRemoteServiceProvider(exposed_services.Pass());
277 blink::WebURL ServiceWorkerContextClient::scope() const {
278 return service_worker_scope_;
281 void ServiceWorkerContextClient::getClients(
282 const blink::WebServiceWorkerClientQueryOptions& weboptions,
283 blink::WebServiceWorkerClientsCallbacks* callbacks) {
284 DCHECK(callbacks);
285 int request_id = context_->clients_callbacks.Add(callbacks);
286 ServiceWorkerClientQueryOptions options;
287 options.client_type = weboptions.clientType;
288 options.include_uncontrolled = weboptions.includeUncontrolled;
289 Send(new ServiceWorkerHostMsg_GetClients(
290 GetRoutingID(), request_id, options));
293 void ServiceWorkerContextClient::openWindow(
294 const blink::WebURL& url,
295 blink::WebServiceWorkerClientCallbacks* callbacks) {
296 DCHECK(callbacks);
297 int request_id = context_->client_callbacks.Add(callbacks);
298 Send(new ServiceWorkerHostMsg_OpenWindow(
299 GetRoutingID(), request_id, url));
302 void ServiceWorkerContextClient::setCachedMetadata(const blink::WebURL& url,
303 const char* data,
304 size_t size) {
305 std::vector<char> copy(data, data + size);
306 Send(new ServiceWorkerHostMsg_SetCachedMetadata(GetRoutingID(), url, copy));
309 void ServiceWorkerContextClient::clearCachedMetadata(
310 const blink::WebURL& url) {
311 Send(new ServiceWorkerHostMsg_ClearCachedMetadata(GetRoutingID(), url));
314 void ServiceWorkerContextClient::workerReadyForInspection() {
315 Send(new EmbeddedWorkerHostMsg_WorkerReadyForInspection(embedded_worker_id_));
318 void ServiceWorkerContextClient::workerContextFailedToStart() {
319 DCHECK(main_thread_task_runner_->RunsTasksOnCurrentThread());
320 DCHECK(!proxy_);
322 Send(new EmbeddedWorkerHostMsg_WorkerScriptLoadFailed(embedded_worker_id_));
324 RenderThreadImpl::current()->embedded_worker_dispatcher()->
325 WorkerContextDestroyed(embedded_worker_id_);
328 void ServiceWorkerContextClient::workerContextStarted(
329 blink::WebServiceWorkerContextProxy* proxy) {
330 DCHECK(!worker_task_runner_.get());
331 DCHECK_NE(0, WorkerTaskRunner::Instance()->CurrentWorkerId());
332 worker_task_runner_ = base::ThreadTaskRunnerHandle::Get();
333 // g_worker_client_tls.Pointer()->Get() could return NULL if this context
334 // gets deleted before workerContextStarted() is called.
335 DCHECK(g_worker_client_tls.Pointer()->Get() == NULL);
336 DCHECK(!proxy_);
337 g_worker_client_tls.Pointer()->Set(this);
338 proxy_ = proxy;
340 // Initialize pending callback maps. This needs to be freed on the
341 // same thread before the worker context goes away in
342 // willDestroyWorkerContext.
343 context_.reset(new WorkerContextData(this));
345 // Register Mojo services.
346 context_->service_registry.ServiceRegistry::AddService(
347 base::Bind(&ServicePortDispatcherImpl::Create,
348 context_->proxy_weak_factory.GetWeakPtr()));
349 context_->service_registry.ServiceRegistry::AddService(
350 base::Bind(&BackgroundSyncClientImpl::Create));
352 SetRegistrationInServiceWorkerGlobalScope();
354 Send(new EmbeddedWorkerHostMsg_WorkerScriptLoaded(
355 embedded_worker_id_,
356 WorkerTaskRunner::Instance()->CurrentWorkerId(),
357 provider_context_->provider_id()));
359 TRACE_EVENT_ASYNC_STEP_INTO0(
360 "ServiceWorker",
361 "ServiceWorkerContextClient::StartingWorkerContext",
362 this,
363 "ExecuteScript");
366 void ServiceWorkerContextClient::didEvaluateWorkerScript(bool success) {
367 Send(new EmbeddedWorkerHostMsg_WorkerScriptEvaluated(
368 embedded_worker_id_, success));
370 // Schedule a task to send back WorkerStarted asynchronously,
371 // so that at the time we send it we can be sure that the
372 // worker run loop has been started.
373 worker_task_runner_->PostTask(
374 FROM_HERE, base::Bind(&ServiceWorkerContextClient::SendWorkerStarted,
375 GetWeakPtr()));
378 void ServiceWorkerContextClient::willDestroyWorkerContext() {
379 // At this point OnWorkerRunLoopStopped is already called, so
380 // worker_task_runner_->RunsTasksOnCurrentThread() returns false
381 // (while we're still on the worker thread).
382 proxy_ = NULL;
384 // We have to clear callbacks now, as they need to be freed on the
385 // same thread.
386 context_.reset();
388 // This also lets the message filter stop dispatching messages to
389 // this client.
390 g_worker_client_tls.Pointer()->Set(NULL);
393 void ServiceWorkerContextClient::workerContextDestroyed() {
394 DCHECK(g_worker_client_tls.Pointer()->Get() == NULL);
396 // Now we should be able to free the WebEmbeddedWorker container on the
397 // main thread.
398 main_thread_task_runner_->PostTask(
399 FROM_HERE,
400 base::Bind(&CallWorkerContextDestroyedOnMainThread,
401 embedded_worker_id_));
404 void ServiceWorkerContextClient::reportException(
405 const blink::WebString& error_message,
406 int line_number,
407 int column_number,
408 const blink::WebString& source_url) {
409 Send(new EmbeddedWorkerHostMsg_ReportException(
410 embedded_worker_id_,
411 error_message,
412 line_number,
413 column_number, GURL(source_url)));
416 void ServiceWorkerContextClient::reportConsoleMessage(
417 int source,
418 int level,
419 const blink::WebString& message,
420 int line_number,
421 const blink::WebString& source_url) {
422 EmbeddedWorkerHostMsg_ReportConsoleMessage_Params params;
423 params.source_identifier = source;
424 params.message_level = level;
425 params.message = message;
426 params.line_number = line_number;
427 params.source_url = GURL(source_url);
429 Send(new EmbeddedWorkerHostMsg_ReportConsoleMessage(
430 embedded_worker_id_, params));
433 void ServiceWorkerContextClient::sendDevToolsMessage(
434 int call_id,
435 const blink::WebString& message,
436 const blink::WebString& state_cookie) {
437 DevToolsAgent::SendChunkedProtocolMessage(
438 sender_.get(), worker_devtools_agent_route_id_,
439 call_id, message.utf8(), state_cookie.utf8());
442 void ServiceWorkerContextClient::didHandleActivateEvent(
443 int request_id,
444 blink::WebServiceWorkerEventResult result) {
445 Send(new ServiceWorkerHostMsg_ActivateEventFinished(
446 GetRoutingID(), request_id, result));
449 void ServiceWorkerContextClient::didHandleInstallEvent(
450 int request_id,
451 blink::WebServiceWorkerEventResult result) {
452 Send(new ServiceWorkerHostMsg_InstallEventFinished(
453 GetRoutingID(), request_id, result));
456 void ServiceWorkerContextClient::didHandleFetchEvent(int request_id) {
457 Send(new ServiceWorkerHostMsg_FetchEventFinished(
458 GetRoutingID(), request_id,
459 SERVICE_WORKER_FETCH_EVENT_RESULT_FALLBACK,
460 ServiceWorkerResponse()));
463 void ServiceWorkerContextClient::didHandleFetchEvent(
464 int request_id,
465 const blink::WebServiceWorkerResponse& web_response) {
466 ServiceWorkerHeaderMap headers;
467 GetServiceWorkerHeaderMapFromWebResponse(web_response, &headers);
468 ServiceWorkerResponse response(
469 web_response.url(), web_response.status(),
470 web_response.statusText().utf8(), web_response.responseType(), headers,
471 web_response.blobUUID().utf8(), web_response.blobSize(),
472 web_response.streamURL(), web_response.error());
473 Send(new ServiceWorkerHostMsg_FetchEventFinished(
474 GetRoutingID(), request_id,
475 SERVICE_WORKER_FETCH_EVENT_RESULT_RESPONSE,
476 response));
479 void ServiceWorkerContextClient::didHandleNotificationClickEvent(
480 int request_id,
481 blink::WebServiceWorkerEventResult result) {
482 Send(new ServiceWorkerHostMsg_NotificationClickEventFinished(
483 GetRoutingID(), request_id));
486 void ServiceWorkerContextClient::didHandlePushEvent(
487 int request_id,
488 blink::WebServiceWorkerEventResult result) {
489 Send(new ServiceWorkerHostMsg_PushEventFinished(
490 GetRoutingID(), request_id, result));
493 void ServiceWorkerContextClient::didHandleSyncEvent(
494 int request_id,
495 blink::WebServiceWorkerEventResult result) {
496 const SyncCallback* callback =
497 context_->sync_event_callbacks.Lookup(request_id);
498 if (!callback)
499 return;
500 if (result == blink::WebServiceWorkerEventResultCompleted) {
501 callback->Run(SERVICE_WORKER_EVENT_STATUS_COMPLETED);
502 } else {
503 callback->Run(SERVICE_WORKER_EVENT_STATUS_REJECTED);
505 context_->sync_event_callbacks.Remove(request_id);
508 blink::WebServiceWorkerNetworkProvider*
509 ServiceWorkerContextClient::createServiceWorkerNetworkProvider(
510 blink::WebDataSource* data_source) {
511 DCHECK(main_thread_task_runner_->RunsTasksOnCurrentThread());
513 // Create a content::ServiceWorkerNetworkProvider for this data source so
514 // we can observe its requests.
515 scoped_ptr<ServiceWorkerNetworkProvider> provider(
516 new ServiceWorkerNetworkProvider(
517 MSG_ROUTING_NONE, SERVICE_WORKER_PROVIDER_FOR_CONTROLLER));
518 provider_context_ = provider->context();
520 // Tell the network provider about which version to load.
521 provider->SetServiceWorkerVersionId(service_worker_version_id_);
523 // The provider is kept around for the lifetime of the DataSource
524 // and ownership is transferred to the DataSource.
525 DataSourceExtraData* extra_data = new DataSourceExtraData();
526 data_source->setExtraData(extra_data);
527 ServiceWorkerNetworkProvider::AttachToDocumentState(
528 extra_data, provider.Pass());
530 // Blink is responsible for deleting the returned object.
531 return new WebServiceWorkerNetworkProviderImpl();
534 blink::WebServiceWorkerProvider*
535 ServiceWorkerContextClient::createServiceWorkerProvider() {
536 DCHECK(main_thread_task_runner_->RunsTasksOnCurrentThread());
537 DCHECK(provider_context_);
539 // Blink is responsible for deleting the returned object.
540 return new WebServiceWorkerProviderImpl(
541 sender_.get(), provider_context_.get());
544 void ServiceWorkerContextClient::postMessageToClient(
545 const blink::WebString& uuid,
546 const blink::WebString& message,
547 blink::WebMessagePortChannelArray* channels) {
548 // This may send channels for MessagePorts, and all internal book-keeping
549 // messages for MessagePort (e.g. QueueMessages) are sent from main thread
550 // (with thread hopping), so we need to do the same thread hopping here not
551 // to overtake those messages.
552 scoped_ptr<blink::WebMessagePortChannelArray> channel_array(channels);
553 main_thread_task_runner_->PostTask(
554 FROM_HERE,
555 base::Bind(&SendPostMessageToClientOnMainThread,
556 sender_,
557 GetRoutingID(),
558 base::UTF16ToUTF8(base::StringPiece16(uuid)),
559 static_cast<base::string16>(message),
560 base::Passed(&channel_array)));
563 void ServiceWorkerContextClient::postMessageToCrossOriginClient(
564 const blink::WebCrossOriginServiceWorkerClient& client,
565 const blink::WebString& message,
566 blink::WebMessagePortChannelArray* channels) {
567 // This may send channels for MessagePorts, and all internal book-keeping
568 // messages for MessagePort (e.g. QueueMessages) are sent from main thread
569 // (with thread hopping), so we need to do the same thread hopping here not
570 // to overtake those messages.
571 scoped_ptr<blink::WebMessagePortChannelArray> channel_array(channels);
572 main_thread_task_runner_->PostTask(
573 FROM_HERE,
574 base::Bind(&SendCrossOriginMessageToClientOnMainThread,
575 sender_, client.clientID,
576 static_cast<base::string16>(message),
577 base::Passed(&channel_array)));
580 void ServiceWorkerContextClient::focus(
581 const blink::WebString& uuid,
582 blink::WebServiceWorkerClientCallbacks* callback) {
583 DCHECK(callback);
584 int request_id = context_->client_callbacks.Add(callback);
585 Send(new ServiceWorkerHostMsg_FocusClient(
586 GetRoutingID(), request_id,
587 base::UTF16ToUTF8(base::StringPiece16(uuid))));
590 void ServiceWorkerContextClient::skipWaiting(
591 blink::WebServiceWorkerSkipWaitingCallbacks* callbacks) {
592 DCHECK(callbacks);
593 int request_id = context_->skip_waiting_callbacks.Add(callbacks);
594 Send(new ServiceWorkerHostMsg_SkipWaiting(GetRoutingID(), request_id));
597 void ServiceWorkerContextClient::claim(
598 blink::WebServiceWorkerClientsClaimCallbacks* callbacks) {
599 DCHECK(callbacks);
600 int request_id = context_->claim_clients_callbacks.Add(callbacks);
601 Send(new ServiceWorkerHostMsg_ClaimClients(GetRoutingID(), request_id));
604 void ServiceWorkerContextClient::DispatchSyncEvent(
605 const blink::WebSyncRegistration& registration,
606 const SyncCallback& callback) {
607 TRACE_EVENT0("ServiceWorker",
608 "ServiceWorkerScriptContext::DispatchSyncEvent");
609 int request_id =
610 context_->sync_event_callbacks.Add(new SyncCallback(callback));
611 proxy_->dispatchSyncEvent(request_id, registration);
614 void ServiceWorkerContextClient::Send(IPC::Message* message) {
615 sender_->Send(message);
618 void ServiceWorkerContextClient::SendWorkerStarted() {
619 DCHECK(worker_task_runner_->RunsTasksOnCurrentThread());
620 TRACE_EVENT_ASYNC_END0("ServiceWorker",
621 "ServiceWorkerContextClient::StartingWorkerContext",
622 this);
623 Send(new EmbeddedWorkerHostMsg_WorkerStarted(embedded_worker_id_));
626 void ServiceWorkerContextClient::SetRegistrationInServiceWorkerGlobalScope() {
627 DCHECK(worker_task_runner_->RunsTasksOnCurrentThread());
628 DCHECK(provider_context_);
630 ServiceWorkerRegistrationObjectInfo info;
631 ServiceWorkerVersionAttributes attrs;
632 bool found =
633 provider_context_->GetRegistrationInfoAndVersionAttributes(&info, &attrs);
634 if (!found)
635 return; // Cannot be associated with a registration in some tests.
637 ServiceWorkerDispatcher* dispatcher =
638 ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance(
639 sender_.get(), main_thread_task_runner_.get());
641 // Register a registration and its version attributes with the dispatcher
642 // living on the worker thread.
643 scoped_ptr<WebServiceWorkerRegistrationImpl> registration(
644 dispatcher->CreateServiceWorkerRegistration(info, false));
645 registration->SetInstalling(
646 dispatcher->GetServiceWorker(attrs.installing, false));
647 registration->SetWaiting(
648 dispatcher->GetServiceWorker(attrs.waiting, false));
649 registration->SetActive(
650 dispatcher->GetServiceWorker(attrs.active, false));
652 proxy_->setRegistration(registration.release());
655 void ServiceWorkerContextClient::OnActivateEvent(int request_id) {
656 TRACE_EVENT0("ServiceWorker",
657 "ServiceWorkerContextClient::OnActivateEvent");
658 proxy_->dispatchActivateEvent(request_id);
661 void ServiceWorkerContextClient::OnInstallEvent(int request_id) {
662 TRACE_EVENT0("ServiceWorker",
663 "ServiceWorkerContextClient::OnInstallEvent");
664 proxy_->dispatchInstallEvent(request_id);
667 void ServiceWorkerContextClient::OnFetchEvent(
668 int request_id,
669 const ServiceWorkerFetchRequest& request) {
670 blink::WebServiceWorkerRequest webRequest;
671 TRACE_EVENT0("ServiceWorker",
672 "ServiceWorkerContextClient::OnFetchEvent");
673 webRequest.setURL(blink::WebURL(request.url));
674 webRequest.setMethod(blink::WebString::fromUTF8(request.method));
675 for (ServiceWorkerHeaderMap::const_iterator it = request.headers.begin();
676 it != request.headers.end();
677 ++it) {
678 webRequest.setHeader(blink::WebString::fromUTF8(it->first),
679 blink::WebString::fromUTF8(it->second));
681 if (!request.blob_uuid.empty()) {
682 webRequest.setBlob(blink::WebString::fromUTF8(request.blob_uuid),
683 request.blob_size);
685 webRequest.setReferrer(
686 blink::WebString::fromUTF8(request.referrer.url.spec()),
687 request.referrer.policy);
688 webRequest.setMode(GetBlinkFetchRequestMode(request.mode));
689 webRequest.setCredentialsMode(
690 GetBlinkFetchCredentialsMode(request.credentials_mode));
691 webRequest.setRequestContext(
692 GetBlinkRequestContext(request.request_context_type));
693 webRequest.setFrameType(GetBlinkFrameType(request.frame_type));
694 webRequest.setIsReload(request.is_reload);
695 proxy_->dispatchFetchEvent(request_id, webRequest);
698 void ServiceWorkerContextClient::OnNotificationClickEvent(
699 int request_id,
700 int64_t persistent_notification_id,
701 const PlatformNotificationData& notification_data) {
702 TRACE_EVENT0("ServiceWorker",
703 "ServiceWorkerContextClient::OnNotificationClickEvent");
704 proxy_->dispatchNotificationClickEvent(
705 request_id,
706 persistent_notification_id,
707 ToWebNotificationData(notification_data));
710 void ServiceWorkerContextClient::OnPushEvent(int request_id,
711 const std::string& data) {
712 TRACE_EVENT0("ServiceWorker",
713 "ServiceWorkerContextClient::OnPushEvent");
714 proxy_->dispatchPushEvent(request_id, blink::WebString::fromUTF8(data));
717 void ServiceWorkerContextClient::OnGeofencingEvent(
718 int request_id,
719 blink::WebGeofencingEventType event_type,
720 const std::string& region_id,
721 const blink::WebCircularGeofencingRegion& region) {
722 TRACE_EVENT0("ServiceWorker",
723 "ServiceWorkerContextClient::OnGeofencingEvent");
724 proxy_->dispatchGeofencingEvent(
725 request_id, event_type, blink::WebString::fromUTF8(region_id), region);
726 Send(new ServiceWorkerHostMsg_GeofencingEventFinished(GetRoutingID(),
727 request_id));
730 void ServiceWorkerContextClient::OnPostMessage(
731 const base::string16& message,
732 const std::vector<TransferredMessagePort>& sent_message_ports,
733 const std::vector<int>& new_routing_ids) {
734 TRACE_EVENT0("ServiceWorker",
735 "ServiceWorkerContextClient::OnPostEvent");
736 blink::WebMessagePortChannelArray ports =
737 WebMessagePortChannelImpl::CreatePorts(
738 sent_message_ports, new_routing_ids,
739 main_thread_task_runner_);
741 // dispatchMessageEvent is expected to execute onmessage function
742 // synchronously.
743 base::TimeTicks before = base::TimeTicks::Now();
744 proxy_->dispatchMessageEvent(message, ports);
745 UMA_HISTOGRAM_MEDIUM_TIMES(
746 "ServiceWorker.MessageEvent.Time",
747 base::TimeTicks::Now() - before);
750 void ServiceWorkerContextClient::OnCrossOriginMessageToWorker(
751 const NavigatorConnectClient& client,
752 const base::string16& message,
753 const std::vector<TransferredMessagePort>& sent_message_ports,
754 const std::vector<int>& new_routing_ids) {
755 TRACE_EVENT0("ServiceWorker",
756 "ServiceWorkerContextClient::OnCrossOriginMessageToWorker");
757 blink::WebMessagePortChannelArray ports =
758 WebMessagePortChannelImpl::CreatePorts(
759 sent_message_ports, new_routing_ids,
760 main_thread_task_runner_);
762 blink::WebCrossOriginServiceWorkerClient web_client;
763 web_client.origin = client.origin;
764 web_client.targetURL = client.target_url;
765 web_client.clientID = client.message_port_id;
766 proxy_->dispatchCrossOriginMessageEvent(web_client, message, ports);
769 void ServiceWorkerContextClient::OnDidGetClients(
770 int request_id, const std::vector<ServiceWorkerClientInfo>& clients) {
771 TRACE_EVENT0("ServiceWorker",
772 "ServiceWorkerContextClient::OnDidGetClients");
773 blink::WebServiceWorkerClientsCallbacks* callbacks =
774 context_->clients_callbacks.Lookup(request_id);
775 if (!callbacks) {
776 NOTREACHED() << "Got stray response: " << request_id;
777 return;
779 scoped_ptr<blink::WebServiceWorkerClientsInfo> info(
780 new blink::WebServiceWorkerClientsInfo);
781 blink::WebVector<blink::WebServiceWorkerClientInfo> convertedClients(
782 clients.size());
783 for (size_t i = 0; i < clients.size(); ++i)
784 convertedClients[i] = ToWebServiceWorkerClientInfo(clients[i]);
785 info->clients.swap(convertedClients);
786 callbacks->onSuccess(info.release());
787 context_->clients_callbacks.Remove(request_id);
790 void ServiceWorkerContextClient::OnOpenWindowResponse(
791 int request_id,
792 const ServiceWorkerClientInfo& client) {
793 TRACE_EVENT0("ServiceWorker",
794 "ServiceWorkerContextClient::OnOpenWindowResponse");
795 blink::WebServiceWorkerClientCallbacks* callbacks =
796 context_->client_callbacks.Lookup(request_id);
797 if (!callbacks) {
798 NOTREACHED() << "Got stray response: " << request_id;
799 return;
801 scoped_ptr<blink::WebServiceWorkerClientInfo> web_client;
802 if (!client.IsEmpty()) {
803 DCHECK(client.IsValid());
804 web_client.reset(new blink::WebServiceWorkerClientInfo(
805 ToWebServiceWorkerClientInfo(client)));
807 callbacks->onSuccess(web_client.release());
808 context_->client_callbacks.Remove(request_id);
811 void ServiceWorkerContextClient::OnOpenWindowError(
812 int request_id,
813 const std::string& message) {
814 TRACE_EVENT0("ServiceWorker",
815 "ServiceWorkerContextClient::OnOpenWindowError");
816 blink::WebServiceWorkerClientCallbacks* callbacks =
817 context_->client_callbacks.Lookup(request_id);
818 if (!callbacks) {
819 NOTREACHED() << "Got stray response: " << request_id;
820 return;
822 scoped_ptr<blink::WebServiceWorkerError> error(
823 new blink::WebServiceWorkerError(
824 blink::WebServiceWorkerError::ErrorTypeUnknown,
825 blink::WebString::fromUTF8(message)));
826 callbacks->onError(error.release());
827 context_->client_callbacks.Remove(request_id);
830 void ServiceWorkerContextClient::OnFocusClientResponse(
831 int request_id, const ServiceWorkerClientInfo& client) {
832 TRACE_EVENT0("ServiceWorker",
833 "ServiceWorkerContextClient::OnFocusClientResponse");
834 blink::WebServiceWorkerClientCallbacks* callback =
835 context_->client_callbacks.Lookup(request_id);
836 if (!callback) {
837 NOTREACHED() << "Got stray response: " << request_id;
838 return;
840 if (!client.IsEmpty()) {
841 DCHECK(client.IsValid());
842 scoped_ptr<blink::WebServiceWorkerClientInfo> web_client (
843 new blink::WebServiceWorkerClientInfo(
844 ToWebServiceWorkerClientInfo(client)));
845 callback->onSuccess(web_client.release());
846 } else {
847 scoped_ptr<blink::WebServiceWorkerError> error(
848 new blink::WebServiceWorkerError(
849 blink::WebServiceWorkerError::ErrorTypeNotFound,
850 "The WindowClient was not found."));
851 callback->onError(error.release());
854 context_->client_callbacks.Remove(request_id);
857 void ServiceWorkerContextClient::OnDidSkipWaiting(int request_id) {
858 TRACE_EVENT0("ServiceWorker",
859 "ServiceWorkerContextClient::OnDidSkipWaiting");
860 blink::WebServiceWorkerSkipWaitingCallbacks* callbacks =
861 context_->skip_waiting_callbacks.Lookup(request_id);
862 if (!callbacks) {
863 NOTREACHED() << "Got stray response: " << request_id;
864 return;
866 callbacks->onSuccess();
867 context_->skip_waiting_callbacks.Remove(request_id);
870 void ServiceWorkerContextClient::OnDidClaimClients(int request_id) {
871 TRACE_EVENT0("ServiceWorker",
872 "ServiceWorkerContextClient::OnDidClaimClients");
873 blink::WebServiceWorkerClientsClaimCallbacks* callbacks =
874 context_->claim_clients_callbacks.Lookup(request_id);
875 if (!callbacks) {
876 NOTREACHED() << "Got stray response: " << request_id;
877 return;
879 callbacks->onSuccess();
880 context_->claim_clients_callbacks.Remove(request_id);
883 void ServiceWorkerContextClient::OnClaimClientsError(
884 int request_id,
885 blink::WebServiceWorkerError::ErrorType error_type,
886 const base::string16& message) {
887 TRACE_EVENT0("ServiceWorker",
888 "ServiceWorkerContextClient::OnClaimClientsError");
889 blink::WebServiceWorkerClientsClaimCallbacks* callbacks =
890 context_->claim_clients_callbacks.Lookup(request_id);
891 if (!callbacks) {
892 NOTREACHED() << "Got stray response: " << request_id;
893 return;
895 scoped_ptr<blink::WebServiceWorkerError> error(
896 new blink::WebServiceWorkerError(error_type, message));
897 callbacks->onError(error.release());
898 context_->claim_clients_callbacks.Remove(request_id);
901 void ServiceWorkerContextClient::OnPing() {
902 Send(new ServiceWorkerHostMsg_Pong(GetRoutingID()));
905 base::WeakPtr<ServiceWorkerContextClient>
906 ServiceWorkerContextClient::GetWeakPtr() {
907 DCHECK(worker_task_runner_->RunsTasksOnCurrentThread());
908 DCHECK(context_);
909 return context_->weak_factory.GetWeakPtr();
912 } // namespace content