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_
14 #include "base/basictypes.h"
15 #include "base/callback.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/id_map.h"
18 #include "base/memory/ref_counted.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/observer_list.h"
21 #include "base/timer/timer.h"
22 #include "content/browser/service_worker/embedded_worker_instance.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 struct NavigatorConnectClient
;
53 struct PlatformNotificationData
;
54 struct ServiceWorkerClientInfo
;
55 struct ServiceWorkerVersionInfo
;
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
,
72 bool /* accept_connction */)>
73 CrossOriginConnectCallback
;
74 typedef base::Callback
<void(ServiceWorkerStatusCode
, const std::vector
<int>&)>
75 SendStashedPortsCallback
;
78 STOPPED
= EmbeddedWorkerInstance::STOPPED
,
79 STARTING
= EmbeddedWorkerInstance::STARTING
,
80 RUNNING
= EmbeddedWorkerInstance::RUNNING
,
81 STOPPING
= EmbeddedWorkerInstance::STOPPING
,
84 // Current version status; some of the status (e.g. INSTALLED and ACTIVATED)
85 // should be persisted unlike running status.
87 NEW
, // The version is just created.
88 INSTALLING
, // Install event is dispatched and being handled.
89 INSTALLED
, // Install event is finished and is ready to be activated.
90 ACTIVATING
, // Activate event is dispatched and being handled.
91 ACTIVATED
, // Activation is finished and can run as activated.
92 REDUNDANT
, // The version is no longer running as activated, due to
93 // unregistration or replace.
98 virtual void OnRunningStateChanged(ServiceWorkerVersion
* version
) {}
99 virtual void OnVersionStateChanged(ServiceWorkerVersion
* version
) {}
100 virtual void OnMainScriptHttpResponseInfoSet(
101 ServiceWorkerVersion
* version
) {}
102 virtual void OnErrorReported(ServiceWorkerVersion
* version
,
103 const base::string16
& error_message
,
106 const GURL
& source_url
) {}
107 virtual void OnReportConsoleMessage(ServiceWorkerVersion
* version
,
108 int source_identifier
,
110 const base::string16
& message
,
112 const GURL
& source_url
) {}
113 // Fires when a version transitions from having a controllee to not.
114 virtual void OnNoControllees(ServiceWorkerVersion
* version
) {}
115 virtual void OnCachedMetadataUpdated(ServiceWorkerVersion
* version
) {}
118 virtual ~Listener() {}
121 ServiceWorkerVersion(
122 ServiceWorkerRegistration
* registration
,
123 const GURL
& script_url
,
125 base::WeakPtr
<ServiceWorkerContextCore
> context
);
127 int64
version_id() const { return version_id_
; }
128 int64
registration_id() const { return registration_id_
; }
129 const GURL
& script_url() const { return script_url_
; }
130 const GURL
& scope() const { return scope_
; }
131 RunningStatus
running_status() const {
132 return static_cast<RunningStatus
>(embedded_worker_
->status());
134 ServiceWorkerVersionInfo
GetInfo();
135 Status
status() const { return status_
; }
137 // This sets the new status and also run status change callbacks
138 // if there're any (see RegisterStatusChangeCallback).
139 void SetStatus(Status status
);
141 // Registers status change callback. (This is for one-off observation,
142 // the consumer needs to re-register if it wants to continue observing
144 void RegisterStatusChangeCallback(const base::Closure
& callback
);
146 // Starts an embedded worker for this version.
147 // This returns OK (success) if the worker is already running.
148 void StartWorker(const StatusCallback
& callback
);
150 // Starts an embedded worker for this version.
151 // |pause_after_download| notifies worker to pause after download finished
152 // which could be resumed by EmbeddedWorkerInstance::ResumeAfterDownload.
153 // This returns OK (success) if the worker is already running.
154 void StartWorker(bool pause_after_download
,
155 const StatusCallback
& callback
);
157 // Stops an embedded worker for this version.
158 // This returns OK (success) if the worker is already stopped.
159 void StopWorker(const StatusCallback
& callback
);
161 // Schedules an update to be run 'soon'.
162 void ScheduleUpdate();
164 // If an update is scheduled but not yet started, this resets the timer
165 // delaying the start time by a 'small' amount.
166 void DeferScheduledUpdate();
168 // Starts an update now.
171 // Sends a message event to the associated embedded worker.
172 void DispatchMessageEvent(
173 const base::string16
& message
,
174 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
175 const StatusCallback
& callback
);
177 // Sends install event to the associated embedded worker and asynchronously
178 // calls |callback| when it errors out or it gets a response from the worker
179 // to notify install completion.
181 // This must be called when the status() is NEW. Calling this changes
182 // the version's status to INSTALLING.
183 // Upon completion, the version's status will be changed to INSTALLED
184 // on success, or back to NEW on failure.
185 void DispatchInstallEvent(const StatusCallback
& callback
);
187 // Sends activate event to the associated embedded worker and asynchronously
188 // calls |callback| when it errors out or it gets a response from the worker
189 // to notify activation completion.
191 // This must be called when the status() is INSTALLED. Calling this changes
192 // the version's status to ACTIVATING.
193 // Upon completion, the version's status will be changed to ACTIVATED
194 // on success, or back to INSTALLED on failure.
195 void DispatchActivateEvent(const StatusCallback
& callback
);
197 // Sends fetch event to the associated embedded worker and calls
198 // |callback| with the response from the worker.
200 // This must be called when the status() is ACTIVATED. Calling this in other
201 // statuses will result in an error SERVICE_WORKER_ERROR_FAILED.
202 void DispatchFetchEvent(const ServiceWorkerFetchRequest
& request
,
203 const base::Closure
& prepare_callback
,
204 const FetchCallback
& fetch_callback
);
206 // Sends sync event to the associated embedded worker and asynchronously calls
207 // |callback| when it errors out or it gets a response from the worker to
208 // notify completion.
210 // This must be called when the status() is ACTIVATED.
211 void DispatchSyncEvent(const StatusCallback
& callback
);
213 // Sends notificationclick event to the associated embedded worker and
214 // asynchronously calls |callback| when it errors out or it gets a response
215 // from the worker to notify completion.
217 // This must be called when the status() is ACTIVATED.
218 void DispatchNotificationClickEvent(
219 const StatusCallback
& callback
,
220 int64_t persistent_notification_id
,
221 const PlatformNotificationData
& notification_data
);
223 // Sends push event to the associated embedded worker and asynchronously calls
224 // |callback| when it errors out or it gets a response from the worker to
225 // notify completion.
227 // This must be called when the status() is ACTIVATED.
228 void DispatchPushEvent(const StatusCallback
& callback
,
229 const std::string
& data
);
231 // Sends geofencing event to the associated embedded worker and asynchronously
232 // calls |callback| when it errors out or it gets a response from the worker
233 // to notify completion.
235 // This must be called when the status() is ACTIVATED.
236 void DispatchGeofencingEvent(
237 const StatusCallback
& callback
,
238 blink::WebGeofencingEventType event_type
,
239 const std::string
& region_id
,
240 const blink::WebCircularGeofencingRegion
& region
);
242 // Sends a cross origin connect event to the associated embedded worker and
243 // asynchronously calls |callback| with the response from the worker.
245 // This must be called when the status() is ACTIVATED.
246 void DispatchCrossOriginConnectEvent(
247 const CrossOriginConnectCallback
& callback
,
248 const NavigatorConnectClient
& client
);
250 // Sends a cross origin message event to the associated embedded worker and
251 // asynchronously calls |callback| when the message was sent (or failed to
253 // It is the responsibility of the code calling this method to make sure that
254 // any transferred message ports are put on hold while potentially a process
255 // for the service worker is spun up.
257 // This must be called when the status() is ACTIVATED.
258 void DispatchCrossOriginMessageEvent(
259 const NavigatorConnectClient
& client
,
260 const base::string16
& message
,
261 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
262 const StatusCallback
& callback
);
264 // Transfers one or more stashed message ports to the associated embedded
265 // worker, and asynchronously calls |callback| with the new route ids for the
266 // transferred ports as soon as the ports are sent to the renderer.
267 // Once the ports are received by the renderer, the ports themselves will
268 // inform MessagePortService, which will enable actual messages to be sent.
269 void SendStashedMessagePorts(
270 const std::vector
<TransferredMessagePort
>& stashed_message_ports
,
271 const std::vector
<base::string16
>& port_names
,
272 const SendStashedPortsCallback
& callback
);
274 // Adds and removes |provider_host| as a controllee of this ServiceWorker.
275 // A potential controllee is a host having the version as its .installing
276 // or .waiting version.
277 void AddControllee(ServiceWorkerProviderHost
* provider_host
);
278 void RemoveControllee(ServiceWorkerProviderHost
* provider_host
);
280 // Returns if it has controllee.
281 bool HasControllee() const { return !controllee_map_
.empty(); }
283 // Adds and removes |request_job| as a dependent job not to stop the
284 // ServiceWorker while |request_job| is reading the stream of the fetch event
285 // response from the ServiceWorker.
286 void AddStreamingURLRequestJob(const ServiceWorkerURLRequestJob
* request_job
);
287 void RemoveStreamingURLRequestJob(
288 const ServiceWorkerURLRequestJob
* request_job
);
290 // Adds and removes Listeners.
291 void AddListener(Listener
* listener
);
292 void RemoveListener(Listener
* listener
);
294 ServiceWorkerScriptCacheMap
* script_cache_map() { return &script_cache_map_
; }
295 EmbeddedWorkerInstance
* embedded_worker() { return embedded_worker_
.get(); }
297 // Reports the error message to |listeners_|.
298 void ReportError(ServiceWorkerStatusCode status
,
299 const std::string
& status_message
);
301 // Sets the status code to pass to StartWorker callbacks if start fails.
302 void SetStartWorkerStatusCode(ServiceWorkerStatusCode status
);
304 // Sets this version's status to REDUNDANT and deletes its resources.
305 // The version must not have controllees.
307 bool is_redundant() const { return status_
== REDUNDANT
; }
309 bool skip_waiting() const { return skip_waiting_
; }
310 void set_skip_waiting(bool skip_waiting
) { skip_waiting_
= skip_waiting
; }
312 bool force_bypass_cache_for_scripts() {
313 return force_bypass_cache_for_scripts_
;
315 void set_force_bypass_cache_for_scripts(bool force_bypass_cache_for_scripts
) {
316 force_bypass_cache_for_scripts_
= force_bypass_cache_for_scripts
;
319 void SetDevToolsAttached(bool attached
);
321 // Sets the HttpResponseInfo used to load the main script.
322 // This HttpResponseInfo will be used for all responses sent back from the
323 // service worker, as the effective security of these responses is equivalent
324 // to that of the ServiceWorker.
325 void SetMainScriptHttpResponseInfo(const net::HttpResponseInfo
& http_info
);
326 const net::HttpResponseInfo
* GetMainScriptHttpResponseInfo();
328 // Simulate ping timeout. Should be used for tests-only.
329 void SimulatePingTimeoutForTesting();
332 friend class base::RefCounted
<ServiceWorkerVersion
>;
333 friend class ServiceWorkerURLRequestJobTest
;
334 friend class ServiceWorkerVersionBrowserTest
;
336 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest
,
337 ActivateWaitingVersion
);
338 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, IdleTimeout
);
339 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, SetDevToolsAttached
);
340 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerWaitForeverInFetchTest
, RequestTimeout
);
341 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerFailToStartTest
, Timeout
);
342 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest
,
343 TimeoutStartingWorker
);
344 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest
,
345 TimeoutWorkerInEvent
);
348 class PingController
;
350 typedef ServiceWorkerVersion self
;
351 using ServiceWorkerClients
= std::vector
<ServiceWorkerClientInfo
>;
358 REQUEST_NOTIFICATION_CLICK
,
361 REQUEST_CROSS_ORIGIN_CONNECT
365 RequestInfo(int id
, RequestType type
);
369 base::TimeTicks time
;
372 // Timeout for the worker to start.
373 static const int kStartWorkerTimeoutMinutes
;
374 // Timeout for a request to be handled.
375 static const int kRequestTimeoutMinutes
;
377 ~ServiceWorkerVersion() override
;
379 // EmbeddedWorkerInstance::Listener overrides:
380 void OnScriptLoaded() override
;
381 void OnStarting() override
;
382 void OnStarted() override
;
383 void OnStopping() override
;
384 void OnStopped(EmbeddedWorkerInstance::Status old_status
) override
;
385 void OnReportException(const base::string16
& error_message
,
388 const GURL
& source_url
) override
;
389 void OnReportConsoleMessage(int source_identifier
,
391 const base::string16
& message
,
393 const GURL
& source_url
) override
;
394 bool OnMessageReceived(const IPC::Message
& message
) override
;
396 void OnStartSentAndScriptEvaluated(ServiceWorkerStatusCode status
);
398 void DispatchInstallEventAfterStartWorker(const StatusCallback
& callback
);
399 void DispatchActivateEventAfterStartWorker(const StatusCallback
& callback
);
401 void DispatchMessageEventInternal(
402 const base::string16
& message
,
403 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
404 const StatusCallback
& callback
);
408 // This corresponds to the spec's matchAll(options) steps.
409 void OnGetClients(int request_id
,
410 const ServiceWorkerClientQueryOptions
& options
);
412 void OnActivateEventFinished(int request_id
,
413 blink::WebServiceWorkerEventResult result
);
414 void OnInstallEventFinished(int request_id
,
415 blink::WebServiceWorkerEventResult result
);
416 void OnFetchEventFinished(int request_id
,
417 ServiceWorkerFetchEventResult result
,
418 const ServiceWorkerResponse
& response
);
419 void OnSyncEventFinished(int request_id
,
420 blink::WebServiceWorkerEventResult result
);
421 void OnNotificationClickEventFinished(int request_id
);
422 void OnPushEventFinished(int request_id
,
423 blink::WebServiceWorkerEventResult result
);
424 void OnGeofencingEventFinished(int request_id
);
425 void OnCrossOriginConnectEventFinished(int request_id
,
426 bool accept_connection
);
427 void OnOpenWindow(int request_id
, GURL url
);
428 void DidOpenWindow(int request_id
,
429 int render_process_id
,
430 int render_frame_id
);
431 void OnOpenWindowFinished(int request_id
,
432 const std::string
& client_uuid
,
433 const ServiceWorkerClientInfo
& client_info
);
435 void OnSetCachedMetadata(const GURL
& url
, const std::vector
<char>& data
);
436 void OnSetCachedMetadataFinished(int64 callback_id
, int result
);
437 void OnClearCachedMetadata(const GURL
& url
);
438 void OnClearCachedMetadataFinished(int64 callback_id
, int result
);
440 void OnPostMessageToClient(
441 const std::string
& client_uuid
,
442 const base::string16
& message
,
443 const std::vector
<TransferredMessagePort
>& sent_message_ports
);
444 void OnFocusClient(int request_id
, const std::string
& client_uuid
);
445 void OnSkipWaiting(int request_id
);
446 void OnClaimClients(int request_id
);
447 void OnPongFromWorker();
448 void OnStashMessagePort(int message_port_id
, const base::string16
& name
);
450 void OnFocusClientFinished(int request_id
,
451 const std::string
& client_uuid
,
452 const ServiceWorkerClientInfo
& client
);
454 void DidEnsureLiveRegistrationForStartWorker(
455 bool pause_after_download
,
456 const StatusCallback
& callback
,
457 ServiceWorkerStatusCode status
,
458 const scoped_refptr
<ServiceWorkerRegistration
>& protect
);
459 void StartWorkerInternal(bool pause_after_download
);
461 void DidSkipWaiting(int request_id
);
463 void GetWindowClients(int request_id
,
464 const ServiceWorkerClientQueryOptions
& options
);
465 void DidGetWindowClients(int request_id
,
466 const ServiceWorkerClientQueryOptions
& options
,
467 scoped_ptr
<ServiceWorkerClients
> clients
);
468 void GetNonWindowClients(int request_id
,
469 const ServiceWorkerClientQueryOptions
& options
,
470 ServiceWorkerClients
* clients
);
471 void OnGetClientsFinished(int request_id
,
472 const ServiceWorkerClients
& clients
);
474 // The timeout timer periodically calls OnTimeoutTimer, which stops the worker
475 // if it is excessively idle or unresponsive to ping.
476 void StartTimeoutTimer();
477 void StopTimeoutTimer();
478 void OnTimeoutTimer();
480 // Called by PingController for ping protocol.
481 ServiceWorkerStatusCode
PingWorker();
482 void OnPingTimeout();
484 // Stops the worker if it is idle (has no in-flight requests) or timed out
486 void StopWorkerIfIdle();
487 bool HasInflightRequests() const;
489 // RecordStartWorkerResult is added as a start callback by StartTimeoutTimer
490 // and records metrics about startup.
491 void RecordStartWorkerResult(ServiceWorkerStatusCode status
);
493 template <typename IDMAP
>
494 void RemoveCallbackAndStopIfRedundant(IDMAP
* callbacks
, int request_id
);
496 template <typename CallbackType
>
497 int AddRequest(const CallbackType
& callback
,
498 IDMap
<CallbackType
, IDMapOwnPointer
>* callback_map
,
499 RequestType request_type
);
501 bool OnRequestTimeout(const RequestInfo
& info
);
502 void SetAllRequestTimes(const base::TimeTicks
& ticks
);
504 // Returns the reason the embedded worker failed to start, using information
505 // inaccessible to EmbeddedWorkerInstance. Returns |default_code| if it can't
507 ServiceWorkerStatusCode
DeduceStartWorkerFailureReason(
508 ServiceWorkerStatusCode default_code
);
510 const int64 version_id_
;
511 const int64 registration_id_
;
512 const GURL script_url_
;
515 Status status_
= NEW
;
516 scoped_ptr
<EmbeddedWorkerInstance
> embedded_worker_
;
517 std::vector
<StatusCallback
> start_callbacks_
;
518 std::vector
<StatusCallback
> stop_callbacks_
;
519 std::vector
<base::Closure
> status_change_callbacks_
;
521 // Message callbacks. (Update HasInflightRequests() too when you update this
523 IDMap
<StatusCallback
, IDMapOwnPointer
> activate_callbacks_
;
524 IDMap
<StatusCallback
, IDMapOwnPointer
> install_callbacks_
;
525 IDMap
<FetchCallback
, IDMapOwnPointer
> fetch_callbacks_
;
526 IDMap
<StatusCallback
, IDMapOwnPointer
> sync_callbacks_
;
527 IDMap
<StatusCallback
, IDMapOwnPointer
> notification_click_callbacks_
;
528 IDMap
<StatusCallback
, IDMapOwnPointer
> push_callbacks_
;
529 IDMap
<StatusCallback
, IDMapOwnPointer
> geofencing_callbacks_
;
530 IDMap
<CrossOriginConnectCallback
, IDMapOwnPointer
>
531 cross_origin_connect_callbacks_
;
533 std::set
<const ServiceWorkerURLRequestJob
*> streaming_url_request_jobs_
;
535 std::map
<std::string
, ServiceWorkerProviderHost
*> controllee_map_
;
536 // Will be null while shutting down.
537 base::WeakPtr
<ServiceWorkerContextCore
> context_
;
538 base::ObserverList
<Listener
> listeners_
;
539 ServiceWorkerScriptCacheMap script_cache_map_
;
540 base::OneShotTimer
<ServiceWorkerVersion
> update_timer_
;
542 // Starts running in StartWorker and continues until the worker is stopped.
543 base::RepeatingTimer
<ServiceWorkerVersion
> timeout_timer_
;
544 // Holds the time the worker last started being considered idle.
545 base::TimeTicks idle_time_
;
546 // Holds the time that the outstanding StartWorker() request started.
547 base::TimeTicks start_time_
;
549 // New requests are added to |requests_| along with their entry in a callback
550 // map. The timeout timer periodically checks |requests_| for entries that
551 // should time out or have already been fulfilled (i.e., removed from the
553 std::queue
<RequestInfo
> requests_
;
555 bool skip_waiting_
= false;
556 bool skip_recording_startup_time_
= false;
557 bool force_bypass_cache_for_scripts_
= false;
559 std::vector
<int> pending_skip_waiting_requests_
;
560 scoped_ptr
<net::HttpResponseInfo
> main_script_http_info_
;
562 // The status when StartWorker was invoked. Used for UMA.
563 Status prestart_status_
= NEW
;
564 // If not OK, the reason that StartWorker failed. Used for
565 // running |start_callbacks_|.
566 ServiceWorkerStatusCode start_worker_status_
= SERVICE_WORKER_OK
;
568 scoped_ptr
<PingController
> ping_controller_
;
569 scoped_ptr
<Metrics
> metrics_
;
571 base::WeakPtrFactory
<ServiceWorkerVersion
> weak_factory_
;
573 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion
);
576 } // namespace content
578 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_