Roll src/third_party/WebKit 9d2dfea:3aea697 (svn 201972:201973)
[chromium-blink-merge.git] / content / renderer / service_worker / service_worker_context_client.cc
blobd3af28f8d9707af1737e6742a4eb8bb053d03d9f
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"
57 namespace content {
59 namespace {
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())
68 return;
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 {
79 public:
80 DataSourceExtraData() {}
81 virtual ~DataSourceExtraData() {}
84 // Called on the main thread only and blink owns it.
85 class WebServiceWorkerNetworkProviderImpl
86 : public blink::WebServiceWorkerNetworkProvider {
87 public:
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,
104 int routing_id,
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,
115 int message_port_id,
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>(
131 credentials_mode);
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;
166 } // namespace
168 // Holding data that needs to be bound to the worker context on the
169 // worker thread.
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)>,
181 IDMapOwnPointer>;
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()),
230 proxy_(nullptr) {
231 TRACE_EVENT_ASYNC_BEGIN0("ServiceWorker",
232 "ServiceWorkerContextClient::StartingWorkerContext",
233 this);
234 TRACE_EVENT_ASYNC_STEP_INTO0(
235 "ServiceWorker",
236 "ServiceWorkerContextClient::StartingWorkerContext",
237 this,
238 "PrepareWorker");
241 ServiceWorkerContextClient::~ServiceWorkerContextClient() {}
243 void ServiceWorkerContextClient::OnMessageReceived(
244 int thread_id,
245 int embedded_worker_id,
246 const IPC::Message& message) {
247 CHECK_EQ(embedded_worker_id_, embedded_worker_id);
248 bool handled = true;
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,
264 OnOpenWindowError)
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()
277 DCHECK(handled);
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) {
294 DCHECK(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) {
306 DCHECK(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,
313 const char* data,
314 size_t size) {
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());
330 DCHECK(!proxy_);
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);
346 DCHECK(!proxy_);
347 g_worker_client_tls.Pointer()->Set(this);
348 proxy_ = proxy;
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(
369 "ServiceWorker",
370 "ServiceWorkerContextClient::StartingWorkerContext",
371 this,
372 "ExecuteScript");
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,
384 GetWeakPtr()));
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.
393 GetContentClient()
394 ->renderer()
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).
403 proxy_ = NULL;
405 // We have to clear callbacks now, as they need to be freed on the
406 // same thread.
407 context_.reset();
409 // This also lets the message filter stop dispatching messages to
410 // this client.
411 g_worker_client_tls.Pointer()->Set(NULL);
413 GetContentClient()->renderer()->WillDestroyServiceWorkerContextOnWorkerThread(
414 script_url_);
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
421 // main thread.
422 main_thread_task_runner_->PostTask(
423 FROM_HERE,
424 base::Bind(&CallWorkerContextDestroyedOnMainThread,
425 embedded_worker_id_));
428 void ServiceWorkerContextClient::reportException(
429 const blink::WebString& error_message,
430 int line_number,
431 int column_number,
432 const blink::WebString& source_url) {
433 Send(new EmbeddedWorkerHostMsg_ReportException(
434 embedded_worker_id_,
435 error_message,
436 line_number,
437 column_number, GURL(source_url)));
440 void ServiceWorkerContextClient::reportConsoleMessage(
441 int source,
442 int level,
443 const blink::WebString& message,
444 int line_number,
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(
458 int call_id,
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(
467 int request_id,
468 blink::WebServiceWorkerEventResult result) {
469 Send(new ServiceWorkerHostMsg_ActivateEventFinished(
470 GetRoutingID(), request_id, result));
473 void ServiceWorkerContextClient::didHandleInstallEvent(
474 int request_id,
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(
488 int request_id,
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,
500 response));
503 void ServiceWorkerContextClient::didHandleNotificationClickEvent(
504 int request_id,
505 blink::WebServiceWorkerEventResult result) {
506 Send(new ServiceWorkerHostMsg_NotificationClickEventFinished(
507 GetRoutingID(), request_id));
510 void ServiceWorkerContextClient::didHandlePushEvent(
511 int request_id,
512 blink::WebServiceWorkerEventResult result) {
513 Send(new ServiceWorkerHostMsg_PushEventFinished(
514 GetRoutingID(), request_id, result));
517 void ServiceWorkerContextClient::didHandleSyncEvent(
518 int request_id,
519 blink::WebServiceWorkerEventResult result) {
520 const SyncCallback* callback =
521 context_->sync_event_callbacks.Lookup(request_id);
522 if (!callback)
523 return;
524 if (result == blink::WebServiceWorkerEventResultCompleted) {
525 callback->Run(SERVICE_WORKER_EVENT_STATUS_COMPLETED);
526 } else {
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(
578 FROM_HERE,
579 base::Bind(&SendPostMessageToClientOnMainThread,
580 sender_,
581 GetRoutingID(),
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(
597 FROM_HERE,
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) {
607 DCHECK(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) {
618 DCHECK(callback);
619 int request_id = context_->client_callbacks.Add(callback);
620 Send(new ServiceWorkerHostMsg_NavigateClient(
621 GetRoutingID(), request_id, base::UTF16ToUTF8(base::StringPiece16(uuid)),
622 url));
625 void ServiceWorkerContextClient::skipWaiting(
626 blink::WebServiceWorkerSkipWaitingCallbacks* callbacks) {
627 DCHECK(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) {
634 DCHECK(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");
644 int request_id =
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",
657 this);
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;
667 bool found =
668 provider_context_->GetRegistrationInfoAndVersionAttributes(&info, &attrs);
669 if (!found)
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(
696 int request_id,
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();
705 ++it) {
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),
711 request.blob_size);
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(
728 int request_id,
729 int64_t persistent_notification_id,
730 const PlatformNotificationData& notification_data,
731 int action_index) {
732 TRACE_EVENT0("ServiceWorker",
733 "ServiceWorkerContextClient::OnNotificationClickEvent");
734 proxy_->dispatchNotificationClickEvent(
735 request_id,
736 persistent_notification_id,
737 ToWebNotificationData(notification_data),
738 action_index);
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(
749 int request_id,
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(),
758 request_id));
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
773 // synchronously.
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);
806 if (!callbacks) {
807 NOTREACHED() << "Got stray response: " << request_id;
808 return;
810 blink::WebServiceWorkerClientsInfo info;
811 blink::WebVector<blink::WebServiceWorkerClientInfo> convertedClients(
812 clients.size());
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(
821 int request_id,
822 const ServiceWorkerClientInfo& client) {
823 TRACE_EVENT0("ServiceWorker",
824 "ServiceWorkerContextClient::OnOpenWindowResponse");
825 blink::WebServiceWorkerClientCallbacks* callbacks =
826 context_->client_callbacks.Lookup(request_id);
827 if (!callbacks) {
828 NOTREACHED() << "Got stray response: " << request_id;
829 return;
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(
842 int request_id,
843 const std::string& message) {
844 TRACE_EVENT0("ServiceWorker",
845 "ServiceWorkerContextClient::OnOpenWindowError");
846 blink::WebServiceWorkerClientCallbacks* callbacks =
847 context_->client_callbacks.Lookup(request_id);
848 if (!callbacks) {
849 NOTREACHED() << "Got stray response: " << request_id;
850 return;
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);
864 if (!callback) {
865 NOTREACHED() << "Got stray response: " << request_id;
866 return;
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()));
874 } else {
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(
884 int request_id,
885 const ServiceWorkerClientInfo& client) {
886 TRACE_EVENT0("ServiceWorker",
887 "ServiceWorkerContextClient::OnNavigateClientResponse");
888 blink::WebServiceWorkerClientCallbacks* callbacks =
889 context_->client_callbacks.Lookup(request_id);
890 if (!callbacks) {
891 NOTREACHED() << "Got stray response: " << request_id;
892 return;
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,
905 const GURL& url) {
906 TRACE_EVENT0("ServiceWorker",
907 "ServiceWorkerContextClient::OnNavigateClientError");
908 blink::WebServiceWorkerClientCallbacks* callbacks =
909 context_->client_callbacks.Lookup(request_id);
910 if (!callbacks) {
911 NOTREACHED() << "Got stray response: " << request_id;
912 return;
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);
926 if (!callbacks) {
927 NOTREACHED() << "Got stray response: " << request_id;
928 return;
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);
939 if (!callbacks) {
940 NOTREACHED() << "Got stray response: " << request_id;
941 return;
943 callbacks->onSuccess();
944 context_->claim_clients_callbacks.Remove(request_id);
947 void ServiceWorkerContextClient::OnClaimClientsError(
948 int request_id,
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);
955 if (!callbacks) {
956 NOTREACHED() << "Got stray response: " << request_id;
957 return;
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());
970 DCHECK(context_);
971 return context_->weak_factory.GetWeakPtr();
974 } // namespace content