1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_
6 #define CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_
13 #include "base/basictypes.h"
14 #include "base/callback.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/id_map.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/observer_list.h"
20 #include "base/timer/timer.h"
21 #include "content/browser/service_worker/embedded_worker_instance.h"
22 #include "content/browser/service_worker/service_worker_cache_listener.h"
23 #include "content/browser/service_worker/service_worker_script_cache_map.h"
24 #include "content/common/content_export.h"
25 #include "content/common/service_worker/service_worker_status_code.h"
26 #include "content/common/service_worker/service_worker_types.h"
27 #include "third_party/WebKit/public/platform/WebGeofencingEventType.h"
28 #include "third_party/WebKit/public/platform/WebServiceWorkerEventResult.h"
30 // Windows headers will redefine SendMessage.
38 struct WebCircularGeofencingRegion
;
42 class HttpResponseInfo
;
47 class EmbeddedWorkerRegistry
;
48 class ServiceWorkerContextCore
;
49 class ServiceWorkerProviderHost
;
50 class ServiceWorkerRegistration
;
51 class ServiceWorkerURLRequestJob
;
52 class ServiceWorkerVersionInfo
;
53 struct NavigatorConnectClient
;
54 struct PlatformNotificationData
;
55 struct ServiceWorkerClientInfo
;
56 struct TransferredMessagePort
;
58 // This class corresponds to a specific version of a ServiceWorker
59 // script for a given pattern. When a script is upgraded, there may be
60 // more than one ServiceWorkerVersion "running" at a time, but only
61 // one of them is activated. This class connects the actual script with a
63 class CONTENT_EXPORT ServiceWorkerVersion
64 : NON_EXPORTED_BASE(public base::RefCounted
<ServiceWorkerVersion
>),
65 public EmbeddedWorkerInstance::Listener
{
67 typedef base::Callback
<void(ServiceWorkerStatusCode
)> StatusCallback
;
68 typedef base::Callback
<void(ServiceWorkerStatusCode
,
69 ServiceWorkerFetchEventResult
,
70 const ServiceWorkerResponse
&)> FetchCallback
;
71 typedef base::Callback
<void(ServiceWorkerStatusCode
, bool)>
72 CrossOriginConnectCallback
;
75 STOPPED
= EmbeddedWorkerInstance::STOPPED
,
76 STARTING
= EmbeddedWorkerInstance::STARTING
,
77 RUNNING
= EmbeddedWorkerInstance::RUNNING
,
78 STOPPING
= EmbeddedWorkerInstance::STOPPING
,
81 // Current version status; some of the status (e.g. INSTALLED and ACTIVATED)
82 // should be persisted unlike running status.
84 NEW
, // The version is just created.
85 INSTALLING
, // Install event is dispatched and being handled.
86 INSTALLED
, // Install event is finished and is ready to be activated.
87 ACTIVATING
, // Activate event is dispatched and being handled.
88 ACTIVATED
, // Activation is finished and can run as activated.
89 REDUNDANT
, // The version is no longer running as activated, due to
90 // unregistration or replace.
95 virtual void OnWorkerStarted(ServiceWorkerVersion
* version
) {}
96 virtual void OnWorkerStopped(ServiceWorkerVersion
* version
) {}
97 virtual void OnVersionStateChanged(ServiceWorkerVersion
* version
) {}
98 virtual void OnErrorReported(ServiceWorkerVersion
* version
,
99 const base::string16
& error_message
,
102 const GURL
& source_url
) {}
103 virtual void OnReportConsoleMessage(ServiceWorkerVersion
* version
,
104 int source_identifier
,
106 const base::string16
& message
,
108 const GURL
& source_url
) {}
109 // Fires when a version transitions from having a controllee to not.
110 virtual void OnNoControllees(ServiceWorkerVersion
* version
) {}
111 virtual void OnCachedMetadataUpdated(ServiceWorkerVersion
* version
) {}
114 virtual ~Listener() {}
117 ServiceWorkerVersion(
118 ServiceWorkerRegistration
* registration
,
119 const GURL
& script_url
,
121 base::WeakPtr
<ServiceWorkerContextCore
> context
);
123 int64
version_id() const { return version_id_
; }
124 int64
registration_id() const { return registration_id_
; }
125 const GURL
& script_url() const { return script_url_
; }
126 const GURL
& scope() const { return scope_
; }
127 RunningStatus
running_status() const {
128 return static_cast<RunningStatus
>(embedded_worker_
->status());
130 ServiceWorkerVersionInfo
GetInfo();
131 Status
status() const { return status_
; }
133 // This sets the new status and also run status change callbacks
134 // if there're any (see RegisterStatusChangeCallback).
135 void SetStatus(Status status
);
137 // Registers status change callback. (This is for one-off observation,
138 // the consumer needs to re-register if it wants to continue observing
140 void RegisterStatusChangeCallback(const base::Closure
& callback
);
142 // Starts an embedded worker for this version.
143 // This returns OK (success) if the worker is already running.
144 void StartWorker(const StatusCallback
& callback
);
146 // Starts an embedded worker for this version.
147 // |pause_after_download| notifies worker to pause after download finished
148 // which could be resumed by EmbeddedWorkerInstance::ResumeAfterDownload.
149 // This returns OK (success) if the worker is already running.
150 void StartWorker(bool pause_after_download
,
151 const StatusCallback
& callback
);
153 // Stops an embedded worker for this version.
154 // This returns OK (success) if the worker is already stopped.
155 void StopWorker(const StatusCallback
& callback
);
157 // Schedules an update to be run 'soon'.
158 void ScheduleUpdate();
160 // If an update is scheduled but not yet started, this resets the timer
161 // delaying the start time by a 'small' amount.
162 void DeferScheduledUpdate();
164 // Starts an update now.
167 // Sends a message event to the associated embedded worker.
168 void DispatchMessageEvent(
169 const base::string16
& message
,
170 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
171 const StatusCallback
& callback
);
173 // Sends install event to the associated embedded worker and asynchronously
174 // calls |callback| when it errors out or it gets a response from the worker
175 // to notify install completion.
177 // This must be called when the status() is NEW. Calling this changes
178 // the version's status to INSTALLING.
179 // Upon completion, the version's status will be changed to INSTALLED
180 // on success, or back to NEW on failure.
181 void DispatchInstallEvent(const StatusCallback
& callback
);
183 // Sends activate event to the associated embedded worker and asynchronously
184 // calls |callback| when it errors out or it gets a response from the worker
185 // to notify activation completion.
187 // This must be called when the status() is INSTALLED. Calling this changes
188 // the version's status to ACTIVATING.
189 // Upon completion, the version's status will be changed to ACTIVATED
190 // on success, or back to INSTALLED on failure.
191 void DispatchActivateEvent(const StatusCallback
& callback
);
193 // Sends fetch event to the associated embedded worker and calls
194 // |callback| with the response from the worker.
196 // This must be called when the status() is ACTIVATED. Calling this in other
197 // statuses will result in an error SERVICE_WORKER_ERROR_FAILED.
198 void DispatchFetchEvent(const ServiceWorkerFetchRequest
& request
,
199 const base::Closure
& prepare_callback
,
200 const FetchCallback
& fetch_callback
);
202 // Sends sync event to the associated embedded worker and asynchronously calls
203 // |callback| when it errors out or it gets a response from the worker to
204 // notify completion.
206 // This must be called when the status() is ACTIVATED.
207 void DispatchSyncEvent(const StatusCallback
& callback
);
209 // Sends notificationclick event to the associated embedded worker and
210 // asynchronously calls |callback| when it errors out or it gets a response
211 // from the worker to notify completion.
213 // This must be called when the status() is ACTIVATED.
214 void DispatchNotificationClickEvent(
215 const StatusCallback
& callback
,
216 const std::string
& notification_id
,
217 const PlatformNotificationData
& notification_data
);
219 // Sends push event to the associated embedded worker and asynchronously calls
220 // |callback| when it errors out or it gets a response from the worker to
221 // notify completion.
223 // This must be called when the status() is ACTIVATED.
224 void DispatchPushEvent(const StatusCallback
& callback
,
225 const std::string
& data
);
227 // Sends geofencing event to the associated embedded worker and asynchronously
228 // calls |callback| when it errors out or it gets a response from the worker
229 // to notify completion.
231 // This must be called when the status() is ACTIVATED.
232 void DispatchGeofencingEvent(
233 const StatusCallback
& callback
,
234 blink::WebGeofencingEventType event_type
,
235 const std::string
& region_id
,
236 const blink::WebCircularGeofencingRegion
& region
);
238 // Sends a cross origin connect event to the associated embedded worker and
239 // asynchronously calls |callback| with the response from the worker.
241 // This must be called when the status() is ACTIVATED.
242 void DispatchCrossOriginConnectEvent(
243 const CrossOriginConnectCallback
& callback
,
244 const NavigatorConnectClient
& client
);
246 // Sends a cross origin message event to the associated embedded worker and
247 // asynchronously calls |callback| when the message was sent (or failed to
249 // It is the responsibility of the code calling this method to make sure that
250 // any transferred message ports are put on hold while potentially a process
251 // for the service worker is spun up.
253 // This must be called when the status() is ACTIVATED.
254 void DispatchCrossOriginMessageEvent(
255 const NavigatorConnectClient
& client
,
256 const base::string16
& message
,
257 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
258 const StatusCallback
& callback
);
260 // Adds and removes |provider_host| as a controllee of this ServiceWorker.
261 // A potential controllee is a host having the version as its .installing
262 // or .waiting version.
263 void AddControllee(ServiceWorkerProviderHost
* provider_host
);
264 void RemoveControllee(ServiceWorkerProviderHost
* provider_host
);
266 // Returns if it has controllee.
267 bool HasControllee() const { return !controllee_map_
.empty(); }
269 // Adds and removes |request_job| as a dependent job not to stop the
270 // ServiceWorker while |request_job| is reading the stream of the fetch event
271 // response from the ServiceWorker.
272 void AddStreamingURLRequestJob(const ServiceWorkerURLRequestJob
* request_job
);
273 void RemoveStreamingURLRequestJob(
274 const ServiceWorkerURLRequestJob
* request_job
);
276 // Adds and removes Listeners.
277 void AddListener(Listener
* listener
);
278 void RemoveListener(Listener
* listener
);
280 ServiceWorkerScriptCacheMap
* script_cache_map() { return &script_cache_map_
; }
281 EmbeddedWorkerInstance
* embedded_worker() { return embedded_worker_
.get(); }
283 // Dooms this version to have REDUNDANT status and its resources deleted. If
284 // the version is controlling a page, these changes will happen when the
285 // version no longer controls any pages.
287 bool is_doomed() const { return is_doomed_
; }
289 bool skip_waiting() const { return skip_waiting_
; }
291 void SetDevToolsAttached(bool attached
);
293 // Sets the HttpResponseInfo used to load the main script.
294 // This HttpResponseInfo will be used for all responses sent back from the
295 // service worker, as the effective security of these responses is equivalent
296 // to that of the ServiceWorker.
297 void SetMainScriptHttpResponseInfo(const net::HttpResponseInfo
& http_info
);
298 const net::HttpResponseInfo
* GetMainScriptHttpResponseInfo();
301 class GetClientDocumentsCallback
;
303 friend class base::RefCounted
<ServiceWorkerVersion
>;
304 friend class ServiceWorkerURLRequestJobTest
;
305 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest
,
306 ActivateWaitingVersion
);
307 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, ScheduleStopWorker
);
308 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, KeepAlive
);
309 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, ListenerAvailability
);
310 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerFailToStartTest
, Timeout
);
311 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest
,
312 TimeoutStartingWorker
);
313 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest
,
314 TimeoutWorkerInEvent
);
315 friend class ServiceWorkerVersionBrowserTest
;
317 typedef ServiceWorkerVersion self
;
318 typedef std::map
<ServiceWorkerProviderHost
*, int> ControlleeMap
;
319 typedef IDMap
<ServiceWorkerProviderHost
> ControlleeByIDMap
;
321 ~ServiceWorkerVersion() override
;
323 // EmbeddedWorkerInstance::Listener overrides:
324 void OnScriptLoaded() override
;
325 void OnStarted() override
;
326 void OnStopped(EmbeddedWorkerInstance::Status old_status
) override
;
327 void OnReportException(const base::string16
& error_message
,
330 const GURL
& source_url
) override
;
331 void OnReportConsoleMessage(int source_identifier
,
333 const base::string16
& message
,
335 const GURL
& source_url
) override
;
336 bool OnMessageReceived(const IPC::Message
& message
) override
;
338 void OnStartSentAndScriptEvaluated(ServiceWorkerStatusCode status
);
340 void DispatchInstallEventAfterStartWorker(const StatusCallback
& callback
);
341 void DispatchActivateEventAfterStartWorker(const StatusCallback
& callback
);
343 void DispatchMessageEventInternal(
344 const base::string16
& message
,
345 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
346 const StatusCallback
& callback
);
349 void OnGetClientDocuments(int request_id
);
350 void OnActivateEventFinished(int request_id
,
351 blink::WebServiceWorkerEventResult result
);
352 void OnInstallEventFinished(int request_id
,
353 blink::WebServiceWorkerEventResult result
);
354 void OnFetchEventFinished(int request_id
,
355 ServiceWorkerFetchEventResult result
,
356 const ServiceWorkerResponse
& response
);
357 void OnSyncEventFinished(int request_id
);
358 void OnNotificationClickEventFinished(int request_id
);
359 void OnPushEventFinished(int request_id
,
360 blink::WebServiceWorkerEventResult result
);
361 void OnGeofencingEventFinished(int request_id
);
362 void OnCrossOriginConnectEventFinished(int request_id
,
363 bool accept_connection
);
364 void OnOpenWindow(int request_id
, const GURL
& url
);
365 void DidOpenWindow(int request_id
,
366 int render_process_id
,
367 int render_frame_id
);
368 void OnOpenWindowFinished(int request_id
,
370 const ServiceWorkerClientInfo
& client_info
);
372 void OnSetCachedMetadata(const GURL
& url
, const std::vector
<char>& data
);
373 void OnSetCachedMetadataFinished(int64 callback_id
, int result
);
374 void OnClearCachedMetadata(const GURL
& url
);
375 void OnClearCachedMetadataFinished(int64 callback_id
, int result
);
377 void OnPostMessageToDocument(
379 const base::string16
& message
,
380 const std::vector
<TransferredMessagePort
>& sent_message_ports
);
381 void OnFocusClient(int request_id
, int client_id
);
382 void OnSkipWaiting(int request_id
);
383 void OnClaimClients(int request_id
);
384 void OnPongFromWorker();
386 void OnFocusClientFinished(int request_id
,
388 const ServiceWorkerClientInfo
& client
);
390 void DidSkipWaiting(int request_id
);
391 void DidClaimClients(int request_id
, ServiceWorkerStatusCode status
);
392 void DidGetClientInfo(int client_id
,
393 scoped_refptr
<GetClientDocumentsCallback
> callback
,
394 const ServiceWorkerClientInfo
& info
);
396 // The ping protocol is for terminating workers that are taking excessively
397 // long executing JavaScript (e.g., stuck in while(true) {}). Periodically a
398 // ping IPC is sent to the worker context and if we timeout waiting for a
399 // pong, the worker is terminated.
401 void StartPingWorker();
402 void SchedulePingWorker();
403 void OnPingTimeout();
405 // ScheduleStopWorker is for terminating idle workers. It schedules an attempt
406 // to stop: if the worker has no inflight requests when the attempt runs, the
407 // worker is terminated, otherwise the attempt is rescheduled.
408 void ScheduleStopWorker();
409 void StopWorkerIfIdle();
410 bool HasInflightRequests() const;
412 // ScheduleStartWorkerTimeout is called when attempting to the start the
413 // embedded worker. It sets a timer for calling OnStartWorkerTimeout, which
414 // invokes start callbacks with ERROR_TIMEOUT. It also adds its own start
415 // callback RecordStartWorkerResult which cancels the timer and records
416 // metrics about startup.
417 void ScheduleStartWorkerTimeout();
418 void RecordStartWorkerResult(ServiceWorkerStatusCode status
);
419 void OnStartWorkerTimeout();
423 template <typename IDMAP
>
424 void RemoveCallbackAndStopIfDoomed(IDMAP
* callbacks
, int request_id
);
426 const int64 version_id_
;
427 int64 registration_id_
;
431 scoped_ptr
<EmbeddedWorkerInstance
> embedded_worker_
;
432 scoped_ptr
<ServiceWorkerCacheListener
> cache_listener_
;
433 std::vector
<StatusCallback
> start_callbacks_
;
434 std::vector
<StatusCallback
> stop_callbacks_
;
435 std::vector
<base::Closure
> status_change_callbacks_
;
437 // Message callbacks. (Update HasInflightRequests() too when you update this
439 IDMap
<StatusCallback
, IDMapOwnPointer
> activate_callbacks_
;
440 IDMap
<StatusCallback
, IDMapOwnPointer
> install_callbacks_
;
441 IDMap
<FetchCallback
, IDMapOwnPointer
> fetch_callbacks_
;
442 IDMap
<StatusCallback
, IDMapOwnPointer
> sync_callbacks_
;
443 IDMap
<StatusCallback
, IDMapOwnPointer
> notification_click_callbacks_
;
444 IDMap
<StatusCallback
, IDMapOwnPointer
> push_callbacks_
;
445 IDMap
<StatusCallback
, IDMapOwnPointer
> geofencing_callbacks_
;
446 IDMap
<CrossOriginConnectCallback
, IDMapOwnPointer
>
447 cross_origin_connect_callbacks_
;
449 std::set
<const ServiceWorkerURLRequestJob
*> streaming_url_request_jobs_
;
451 ControlleeMap controllee_map_
;
452 ControlleeByIDMap controllee_by_id_
;
453 // Will be null while shutting down.
454 base::WeakPtr
<ServiceWorkerContextCore
> context_
;
455 ObserverList
<Listener
> listeners_
;
456 ServiceWorkerScriptCacheMap script_cache_map_
;
457 base::OneShotTimer
<ServiceWorkerVersion
> stop_worker_timer_
;
458 base::OneShotTimer
<ServiceWorkerVersion
> update_timer_
;
459 base::OneShotTimer
<ServiceWorkerVersion
> ping_worker_timer_
;
460 base::OneShotTimer
<ServiceWorkerVersion
> start_worker_timeout_timer_
;
461 base::TimeTicks start_timing_
;
462 bool ping_timed_out_
;
464 std::vector
<int> pending_skip_waiting_requests_
;
466 scoped_ptr
<net::HttpResponseInfo
> main_script_http_info_
;
468 base::WeakPtrFactory
<ServiceWorkerVersion
> weak_factory_
;
470 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion
);
473 } // namespace content
475 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_