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
;
76 STOPPED
= EmbeddedWorkerInstance::STOPPED
,
77 STARTING
= EmbeddedWorkerInstance::STARTING
,
78 RUNNING
= EmbeddedWorkerInstance::RUNNING
,
79 STOPPING
= EmbeddedWorkerInstance::STOPPING
,
82 // Current version status; some of the status (e.g. INSTALLED and ACTIVATED)
83 // should be persisted unlike running status.
85 NEW
, // The version is just created.
86 INSTALLING
, // Install event is dispatched and being handled.
87 INSTALLED
, // Install event is finished and is ready to be activated.
88 ACTIVATING
, // Activate event is dispatched and being handled.
89 ACTIVATED
, // Activation is finished and can run as activated.
90 REDUNDANT
, // The version is no longer running as activated, due to
91 // unregistration or replace.
96 virtual void OnRunningStateChanged(ServiceWorkerVersion
* version
) {}
97 virtual void OnVersionStateChanged(ServiceWorkerVersion
* version
) {}
98 virtual void OnMainScriptHttpResponseInfoSet(
99 ServiceWorkerVersion
* version
) {}
100 virtual void OnErrorReported(ServiceWorkerVersion
* version
,
101 const base::string16
& error_message
,
104 const GURL
& source_url
) {}
105 virtual void OnReportConsoleMessage(ServiceWorkerVersion
* version
,
106 int source_identifier
,
108 const base::string16
& message
,
110 const GURL
& source_url
) {}
111 // Fires when a version transitions from having a controllee to not.
112 virtual void OnNoControllees(ServiceWorkerVersion
* version
) {}
113 virtual void OnCachedMetadataUpdated(ServiceWorkerVersion
* version
) {}
116 virtual ~Listener() {}
119 ServiceWorkerVersion(
120 ServiceWorkerRegistration
* registration
,
121 const GURL
& script_url
,
123 base::WeakPtr
<ServiceWorkerContextCore
> context
);
125 int64
version_id() const { return version_id_
; }
126 int64
registration_id() const { return registration_id_
; }
127 const GURL
& script_url() const { return script_url_
; }
128 const GURL
& scope() const { return scope_
; }
129 RunningStatus
running_status() const {
130 return static_cast<RunningStatus
>(embedded_worker_
->status());
132 ServiceWorkerVersionInfo
GetInfo();
133 Status
status() const { return status_
; }
135 // This sets the new status and also run status change callbacks
136 // if there're any (see RegisterStatusChangeCallback).
137 void SetStatus(Status status
);
139 // Registers status change callback. (This is for one-off observation,
140 // the consumer needs to re-register if it wants to continue observing
142 void RegisterStatusChangeCallback(const base::Closure
& callback
);
144 // Starts an embedded worker for this version.
145 // This returns OK (success) if the worker is already running.
146 void StartWorker(const StatusCallback
& callback
);
148 // Starts an embedded worker for this version.
149 // |pause_after_download| notifies worker to pause after download finished
150 // which could be resumed by EmbeddedWorkerInstance::ResumeAfterDownload.
151 // This returns OK (success) if the worker is already running.
152 void StartWorker(bool pause_after_download
,
153 const StatusCallback
& callback
);
155 // Stops an embedded worker for this version.
156 // This returns OK (success) if the worker is already stopped.
157 void StopWorker(const StatusCallback
& callback
);
159 // Schedules an update to be run 'soon'.
160 void ScheduleUpdate();
162 // If an update is scheduled but not yet started, this resets the timer
163 // delaying the start time by a 'small' amount.
164 void DeferScheduledUpdate();
166 // Starts an update now.
169 // Sends a message event to the associated embedded worker.
170 void DispatchMessageEvent(
171 const base::string16
& message
,
172 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
173 const StatusCallback
& callback
);
175 // Sends install event to the associated embedded worker and asynchronously
176 // calls |callback| when it errors out or it gets a response from the worker
177 // to notify install completion.
179 // This must be called when the status() is NEW. Calling this changes
180 // the version's status to INSTALLING.
181 // Upon completion, the version's status will be changed to INSTALLED
182 // on success, or back to NEW on failure.
183 void DispatchInstallEvent(const StatusCallback
& callback
);
185 // Sends activate event to the associated embedded worker and asynchronously
186 // calls |callback| when it errors out or it gets a response from the worker
187 // to notify activation completion.
189 // This must be called when the status() is INSTALLED. Calling this changes
190 // the version's status to ACTIVATING.
191 // Upon completion, the version's status will be changed to ACTIVATED
192 // on success, or back to INSTALLED on failure.
193 void DispatchActivateEvent(const StatusCallback
& callback
);
195 // Sends fetch event to the associated embedded worker and calls
196 // |callback| with the response from the worker.
198 // This must be called when the status() is ACTIVATED. Calling this in other
199 // statuses will result in an error SERVICE_WORKER_ERROR_FAILED.
200 void DispatchFetchEvent(const ServiceWorkerFetchRequest
& request
,
201 const base::Closure
& prepare_callback
,
202 const FetchCallback
& fetch_callback
);
204 // Sends sync event to the associated embedded worker and asynchronously calls
205 // |callback| when it errors out or it gets a response from the worker to
206 // notify completion.
208 // This must be called when the status() is ACTIVATED.
209 void DispatchSyncEvent(const StatusCallback
& callback
);
211 // Sends notificationclick event to the associated embedded worker and
212 // asynchronously calls |callback| when it errors out or it gets a response
213 // from the worker to notify completion.
215 // This must be called when the status() is ACTIVATED.
216 void DispatchNotificationClickEvent(
217 const StatusCallback
& callback
,
218 int64_t persistent_notification_id
,
219 const PlatformNotificationData
& notification_data
);
221 // Sends push event to the associated embedded worker and asynchronously calls
222 // |callback| when it errors out or it gets a response from the worker to
223 // notify completion.
225 // This must be called when the status() is ACTIVATED.
226 void DispatchPushEvent(const StatusCallback
& callback
,
227 const std::string
& data
);
229 // Sends geofencing event to the associated embedded worker and asynchronously
230 // calls |callback| when it errors out or it gets a response from the worker
231 // to notify completion.
233 // This must be called when the status() is ACTIVATED.
234 void DispatchGeofencingEvent(
235 const StatusCallback
& callback
,
236 blink::WebGeofencingEventType event_type
,
237 const std::string
& region_id
,
238 const blink::WebCircularGeofencingRegion
& region
);
240 // Sends a cross origin connect event to the associated embedded worker and
241 // asynchronously calls |callback| with the response from the worker.
243 // This must be called when the status() is ACTIVATED.
244 void DispatchCrossOriginConnectEvent(
245 const CrossOriginConnectCallback
& callback
,
246 const NavigatorConnectClient
& client
);
248 // Sends a cross origin message event to the associated embedded worker and
249 // asynchronously calls |callback| when the message was sent (or failed to
251 // It is the responsibility of the code calling this method to make sure that
252 // any transferred message ports are put on hold while potentially a process
253 // for the service worker is spun up.
255 // This must be called when the status() is ACTIVATED.
256 void DispatchCrossOriginMessageEvent(
257 const NavigatorConnectClient
& client
,
258 const base::string16
& message
,
259 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
260 const StatusCallback
& callback
);
262 // Adds and removes |provider_host| as a controllee of this ServiceWorker.
263 // A potential controllee is a host having the version as its .installing
264 // or .waiting version.
265 void AddControllee(ServiceWorkerProviderHost
* provider_host
);
266 void RemoveControllee(ServiceWorkerProviderHost
* provider_host
);
268 // Returns if it has controllee.
269 bool HasControllee() const { return !controllee_map_
.empty(); }
271 // Adds and removes |request_job| as a dependent job not to stop the
272 // ServiceWorker while |request_job| is reading the stream of the fetch event
273 // response from the ServiceWorker.
274 void AddStreamingURLRequestJob(const ServiceWorkerURLRequestJob
* request_job
);
275 void RemoveStreamingURLRequestJob(
276 const ServiceWorkerURLRequestJob
* request_job
);
278 // Adds and removes Listeners.
279 void AddListener(Listener
* listener
);
280 void RemoveListener(Listener
* listener
);
282 ServiceWorkerScriptCacheMap
* script_cache_map() { return &script_cache_map_
; }
283 EmbeddedWorkerInstance
* embedded_worker() { return embedded_worker_
.get(); }
285 // Reports the error message to |listeners_|.
286 void ReportError(ServiceWorkerStatusCode status
,
287 const std::string
& status_message
);
289 // Sets this version's status to REDUNDANT and deletes its resources.
290 // The version must not have controllees.
292 bool is_redundant() const { return status_
== REDUNDANT
; }
294 bool skip_waiting() const { return skip_waiting_
; }
296 bool force_bypass_cache_for_scripts() {
297 return force_bypass_cache_for_scripts_
;
299 void set_force_bypass_cache_for_scripts(bool force_bypass_cache_for_scripts
) {
300 force_bypass_cache_for_scripts_
= force_bypass_cache_for_scripts
;
303 void SetDevToolsAttached(bool attached
);
305 // Sets the HttpResponseInfo used to load the main script.
306 // This HttpResponseInfo will be used for all responses sent back from the
307 // service worker, as the effective security of these responses is equivalent
308 // to that of the ServiceWorker.
309 void SetMainScriptHttpResponseInfo(const net::HttpResponseInfo
& http_info
);
310 const net::HttpResponseInfo
* GetMainScriptHttpResponseInfo();
313 friend class base::RefCounted
<ServiceWorkerVersion
>;
314 friend class ServiceWorkerURLRequestJobTest
;
315 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest
,
316 ActivateWaitingVersion
);
317 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, IdleTimeout
);
318 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, KeepAlive
);
319 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, ListenerAvailability
);
320 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, SetDevToolsAttached
);
321 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerWaitForeverInFetchTest
, RequestTimeout
);
322 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerFailToStartTest
, Timeout
);
323 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest
,
324 TimeoutStartingWorker
);
325 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest
,
326 TimeoutWorkerInEvent
);
327 friend class ServiceWorkerVersionBrowserTest
;
329 typedef ServiceWorkerVersion self
;
330 using ServiceWorkerClients
= std::vector
<ServiceWorkerClientInfo
>;
337 REQUEST_NOTIFICATION_CLICK
,
340 REQUEST_CROSS_ORIGIN_CONNECT
342 enum PingState
{ NOT_PINGING
, PINGING
, PING_TIMED_OUT
};
345 RequestInfo(int id
, RequestType type
);
349 base::TimeTicks time
;
352 // Timeout for the worker to start.
353 static const int kStartWorkerTimeoutMinutes
;
354 // Timeout for a request to be handled.
355 static const int kRequestTimeoutMinutes
;
357 ~ServiceWorkerVersion() override
;
359 // EmbeddedWorkerInstance::Listener overrides:
360 void OnScriptLoaded() override
;
361 void OnStarting() override
;
362 void OnStarted() override
;
363 void OnStopping() override
;
364 void OnStopped(EmbeddedWorkerInstance::Status old_status
) override
;
365 void OnReportException(const base::string16
& error_message
,
368 const GURL
& source_url
) override
;
369 void OnReportConsoleMessage(int source_identifier
,
371 const base::string16
& message
,
373 const GURL
& source_url
) override
;
374 bool OnMessageReceived(const IPC::Message
& message
) override
;
376 void OnStartSentAndScriptEvaluated(ServiceWorkerStatusCode status
);
378 void DispatchInstallEventAfterStartWorker(const StatusCallback
& callback
);
379 void DispatchActivateEventAfterStartWorker(const StatusCallback
& callback
);
381 void DispatchMessageEventInternal(
382 const base::string16
& message
,
383 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
384 const StatusCallback
& callback
);
388 // This corresponds to the spec's matchAll(options) steps.
389 void OnGetClients(int request_id
,
390 const ServiceWorkerClientQueryOptions
& options
);
392 void OnActivateEventFinished(int request_id
,
393 blink::WebServiceWorkerEventResult result
);
394 void OnInstallEventFinished(int request_id
,
395 blink::WebServiceWorkerEventResult result
);
396 void OnFetchEventFinished(int request_id
,
397 ServiceWorkerFetchEventResult result
,
398 const ServiceWorkerResponse
& response
);
399 void OnSyncEventFinished(int request_id
);
400 void OnNotificationClickEventFinished(int request_id
);
401 void OnPushEventFinished(int request_id
,
402 blink::WebServiceWorkerEventResult result
);
403 void OnGeofencingEventFinished(int request_id
);
404 void OnCrossOriginConnectEventFinished(int request_id
,
405 bool accept_connection
);
406 void OnOpenWindow(int request_id
, GURL url
);
407 void DidOpenWindow(int request_id
,
408 int render_process_id
,
409 int render_frame_id
);
410 void OnOpenWindowFinished(int request_id
,
411 const std::string
& client_uuid
,
412 const ServiceWorkerClientInfo
& client_info
);
414 void OnSetCachedMetadata(const GURL
& url
, const std::vector
<char>& data
);
415 void OnSetCachedMetadataFinished(int64 callback_id
, int result
);
416 void OnClearCachedMetadata(const GURL
& url
);
417 void OnClearCachedMetadataFinished(int64 callback_id
, int result
);
419 void OnPostMessageToClient(
420 const std::string
& client_uuid
,
421 const base::string16
& message
,
422 const std::vector
<TransferredMessagePort
>& sent_message_ports
);
423 void OnFocusClient(int request_id
, const std::string
& client_uuid
);
424 void OnSkipWaiting(int request_id
);
425 void OnClaimClients(int request_id
);
426 void OnPongFromWorker();
428 void OnFocusClientFinished(int request_id
,
429 const std::string
& client_uuid
,
430 const ServiceWorkerClientInfo
& client
);
432 void DidEnsureLiveRegistrationForStartWorker(
433 bool pause_after_download
,
434 const StatusCallback
& callback
,
435 ServiceWorkerStatusCode status
,
436 const scoped_refptr
<ServiceWorkerRegistration
>& protect
);
437 void StartWorkerInternal(bool pause_after_download
);
439 void DidSkipWaiting(int request_id
);
441 void GetWindowClients(int request_id
,
442 const ServiceWorkerClientQueryOptions
& options
);
443 void DidGetWindowClients(int request_id
,
444 const ServiceWorkerClientQueryOptions
& options
,
445 scoped_ptr
<ServiceWorkerClients
> clients
);
446 void GetNonWindowClients(int request_id
,
447 const ServiceWorkerClientQueryOptions
& options
,
448 ServiceWorkerClients
* clients
);
449 void OnGetClientsFinished(int request_id
,
450 const ServiceWorkerClients
& clients
);
452 // The timeout timer periodically calls OnTimeoutTimer, which stops the worker
453 // if it is excessively idle or unresponsive to ping.
454 void StartTimeoutTimer();
455 void StopTimeoutTimer();
456 void OnTimeoutTimer();
458 // The ping protocol is for terminating workers that are taking excessively
459 // long executing JavaScript (e.g., stuck in while(true) {}). Periodically a
460 // ping IPC is sent to the worker context and if we timeout waiting for a
461 // pong, the worker is terminated. Pinging starts after the script is loaded.
463 void OnPingTimeout();
465 // Stops the worker if it is idle (has no in-flight requests) or timed out
467 void StopWorkerIfIdle();
468 bool HasInflightRequests() const;
470 // RecordStartWorkerResult is added as a start callback by StartTimeoutTimer
471 // and records metrics about startup.
472 void RecordStartWorkerResult(ServiceWorkerStatusCode status
);
474 template <typename IDMAP
>
475 void RemoveCallbackAndStopIfRedundant(IDMAP
* callbacks
, int request_id
);
477 template <typename CallbackType
>
478 int AddRequest(const CallbackType
& callback
,
479 IDMap
<CallbackType
, IDMapOwnPointer
>* callback_map
,
480 RequestType request_type
);
482 bool OnRequestTimeout(const RequestInfo
& info
);
483 void SetAllRequestTimes(const base::TimeTicks
& ticks
);
485 // Returns the reason the embedded worker failed to start, using information
486 // inaccessible to EmbeddedWorkerInstance. Returns |default_code| if it can't
488 ServiceWorkerStatusCode
DeduceStartWorkerFailureReason(
489 ServiceWorkerStatusCode default_code
);
491 const int64 version_id_
;
492 int64 registration_id_
;
496 scoped_ptr
<EmbeddedWorkerInstance
> embedded_worker_
;
497 std::vector
<StatusCallback
> start_callbacks_
;
498 std::vector
<StatusCallback
> stop_callbacks_
;
499 std::vector
<base::Closure
> status_change_callbacks_
;
501 // Message callbacks. (Update HasInflightRequests() too when you update this
503 IDMap
<StatusCallback
, IDMapOwnPointer
> activate_callbacks_
;
504 IDMap
<StatusCallback
, IDMapOwnPointer
> install_callbacks_
;
505 IDMap
<FetchCallback
, IDMapOwnPointer
> fetch_callbacks_
;
506 IDMap
<StatusCallback
, IDMapOwnPointer
> sync_callbacks_
;
507 IDMap
<StatusCallback
, IDMapOwnPointer
> notification_click_callbacks_
;
508 IDMap
<StatusCallback
, IDMapOwnPointer
> push_callbacks_
;
509 IDMap
<StatusCallback
, IDMapOwnPointer
> geofencing_callbacks_
;
510 IDMap
<CrossOriginConnectCallback
, IDMapOwnPointer
>
511 cross_origin_connect_callbacks_
;
513 std::set
<const ServiceWorkerURLRequestJob
*> streaming_url_request_jobs_
;
515 std::map
<std::string
, ServiceWorkerProviderHost
*> controllee_map_
;
516 // Will be null while shutting down.
517 base::WeakPtr
<ServiceWorkerContextCore
> context_
;
518 ObserverList
<Listener
> listeners_
;
519 ServiceWorkerScriptCacheMap script_cache_map_
;
520 base::OneShotTimer
<ServiceWorkerVersion
> update_timer_
;
522 // Starts running in StartWorker and continues until the worker is stopped.
523 base::RepeatingTimer
<ServiceWorkerVersion
> timeout_timer_
;
524 // Holds the time the worker last started being considered idle.
525 base::TimeTicks idle_time_
;
526 // Holds the time that an outstanding ping was sent to the worker.
527 base::TimeTicks ping_time_
;
528 // The state of the ping protocol.
529 PingState ping_state_
;
530 // Holds the time that the outstanding StartWorker() request started.
531 base::TimeTicks start_time_
;
533 // New requests are added to |requests_| along with their entry in a callback
534 // map. The timeout timer periodically checks |requests_| for entries that
535 // should time out or have already been fulfilled (i.e., removed from the
537 std::queue
<RequestInfo
> requests_
;
539 bool skip_waiting_
= false;
540 bool skip_recording_startup_time_
= false;
541 bool force_bypass_cache_for_scripts_
= false;
543 std::vector
<int> pending_skip_waiting_requests_
;
544 scoped_ptr
<net::HttpResponseInfo
> main_script_http_info_
;
546 base::WeakPtrFactory
<ServiceWorkerVersion
> weak_factory_
;
548 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion
);
551 } // namespace content
553 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_