Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / browser / service_worker / service_worker_version.h
blobc73ef597273c0907ba2eb6d3686f33826849a2df
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_
8 #include <map>
9 #include <queue>
10 #include <set>
11 #include <string>
12 #include <vector>
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.
31 #ifdef SendMessage
32 #undef SendMessage
33 #endif
35 class GURL;
37 namespace blink {
38 struct WebCircularGeofencingRegion;
41 namespace net {
42 class HttpResponseInfo;
45 namespace content {
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
62 // running worker.
63 class CONTENT_EXPORT ServiceWorkerVersion
64 : NON_EXPORTED_BASE(public base::RefCounted<ServiceWorkerVersion>),
65 public EmbeddedWorkerInstance::Listener {
66 public:
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;
75 enum RunningStatus {
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.
84 enum 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.
94 class Listener {
95 public:
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,
102 int line_number,
103 int column_number,
104 const GURL& source_url) {}
105 virtual void OnReportConsoleMessage(ServiceWorkerVersion* version,
106 int source_identifier,
107 int message_level,
108 const base::string16& message,
109 int line_number,
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) {}
115 protected:
116 virtual ~Listener() {}
119 ServiceWorkerVersion(
120 ServiceWorkerRegistration* registration,
121 const GURL& script_url,
122 int64 version_id,
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
141 // status changes)
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.
167 void StartUpdate();
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 const std::string& 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
250 // sent).
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 // Dooms this version to have REDUNDANT status and its resources deleted. If
290 // the version is controlling a page, these changes will happen when the
291 // version no longer controls any pages.
292 void Doom();
293 bool is_doomed() const { return is_doomed_; }
295 bool skip_waiting() const { return skip_waiting_; }
297 void SetDevToolsAttached(bool attached);
299 // Sets the HttpResponseInfo used to load the main script.
300 // This HttpResponseInfo will be used for all responses sent back from the
301 // service worker, as the effective security of these responses is equivalent
302 // to that of the ServiceWorker.
303 void SetMainScriptHttpResponseInfo(const net::HttpResponseInfo& http_info);
304 const net::HttpResponseInfo* GetMainScriptHttpResponseInfo();
306 private:
307 friend class base::RefCounted<ServiceWorkerVersion>;
308 friend class ServiceWorkerURLRequestJobTest;
309 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest,
310 ActivateWaitingVersion);
311 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, IdleTimeout);
312 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, KeepAlive);
313 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, ListenerAvailability);
314 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, SetDevToolsAttached);
315 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerWaitForeverInFetchTest, RequestTimeout);
316 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerFailToStartTest, Timeout);
317 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest,
318 TimeoutStartingWorker);
319 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest,
320 TimeoutWorkerInEvent);
321 friend class ServiceWorkerVersionBrowserTest;
323 typedef ServiceWorkerVersion self;
324 using ServiceWorkerClients = std::vector<ServiceWorkerClientInfo>;
326 enum RequestType {
327 REQUEST_ACTIVATE,
328 REQUEST_INSTALL,
329 REQUEST_FETCH,
330 REQUEST_SYNC,
331 REQUEST_NOTIFICATION_CLICK,
332 REQUEST_PUSH,
333 REQUEST_GEOFENCING,
334 REQUEST_CROSS_ORIGIN_CONNECT
336 enum PingState { NOT_PINGING, PINGING, PING_TIMED_OUT };
338 struct RequestInfo {
339 RequestInfo(int id, RequestType type);
340 ~RequestInfo();
341 int id;
342 RequestType type;
343 base::TimeTicks time;
346 // Timeout for the worker to start.
347 static const int kStartWorkerTimeoutMinutes;
348 // Timeout for a request to be handled.
349 static const int kRequestTimeoutMinutes;
351 ~ServiceWorkerVersion() override;
353 // EmbeddedWorkerInstance::Listener overrides:
354 void OnScriptLoaded() override;
355 void OnStarting() override;
356 void OnStarted() override;
357 void OnStopping() override;
358 void OnStopped(EmbeddedWorkerInstance::Status old_status) override;
359 void OnReportException(const base::string16& error_message,
360 int line_number,
361 int column_number,
362 const GURL& source_url) override;
363 void OnReportConsoleMessage(int source_identifier,
364 int message_level,
365 const base::string16& message,
366 int line_number,
367 const GURL& source_url) override;
368 bool OnMessageReceived(const IPC::Message& message) override;
370 void OnStartSentAndScriptEvaluated(ServiceWorkerStatusCode status);
372 void DispatchInstallEventAfterStartWorker(const StatusCallback& callback);
373 void DispatchActivateEventAfterStartWorker(const StatusCallback& callback);
375 void DispatchMessageEventInternal(
376 const base::string16& message,
377 const std::vector<TransferredMessagePort>& sent_message_ports,
378 const StatusCallback& callback);
380 // Message handlers.
382 // This corresponds to the spec's matchAll(options) steps.
383 void OnGetClients(int request_id,
384 const ServiceWorkerClientQueryOptions& options);
386 void OnActivateEventFinished(int request_id,
387 blink::WebServiceWorkerEventResult result);
388 void OnInstallEventFinished(int request_id,
389 blink::WebServiceWorkerEventResult result);
390 void OnFetchEventFinished(int request_id,
391 ServiceWorkerFetchEventResult result,
392 const ServiceWorkerResponse& response);
393 void OnSyncEventFinished(int request_id);
394 void OnNotificationClickEventFinished(int request_id);
395 void OnPushEventFinished(int request_id,
396 blink::WebServiceWorkerEventResult result);
397 void OnGeofencingEventFinished(int request_id);
398 void OnCrossOriginConnectEventFinished(int request_id,
399 bool accept_connection);
400 void OnOpenWindow(int request_id, GURL url);
401 void DidOpenWindow(int request_id,
402 int render_process_id,
403 int render_frame_id);
404 void OnOpenWindowFinished(int request_id,
405 const std::string& client_uuid,
406 const ServiceWorkerClientInfo& client_info);
408 void OnSetCachedMetadata(const GURL& url, const std::vector<char>& data);
409 void OnSetCachedMetadataFinished(int64 callback_id, int result);
410 void OnClearCachedMetadata(const GURL& url);
411 void OnClearCachedMetadataFinished(int64 callback_id, int result);
413 void OnPostMessageToClient(
414 const std::string& client_uuid,
415 const base::string16& message,
416 const std::vector<TransferredMessagePort>& sent_message_ports);
417 void OnFocusClient(int request_id, const std::string& client_uuid);
418 void OnSkipWaiting(int request_id);
419 void OnClaimClients(int request_id);
420 void OnPongFromWorker();
422 void OnFocusClientFinished(int request_id,
423 const std::string& client_uuid,
424 const ServiceWorkerClientInfo& client);
426 void DidEnsureLiveRegistrationForStartWorker(
427 bool pause_after_download,
428 const StatusCallback& callback,
429 ServiceWorkerStatusCode status,
430 const scoped_refptr<ServiceWorkerRegistration>& protect);
431 void StartWorkerInternal(bool pause_after_download);
433 void DidSkipWaiting(int request_id);
435 void GetWindowClients(int request_id,
436 const ServiceWorkerClientQueryOptions& options);
437 void DidGetWindowClients(int request_id,
438 const ServiceWorkerClientQueryOptions& options,
439 scoped_ptr<ServiceWorkerClients> clients);
440 void GetNonWindowClients(int request_id,
441 const ServiceWorkerClientQueryOptions& options,
442 ServiceWorkerClients* clients);
443 void OnGetClientsFinished(int request_id,
444 const ServiceWorkerClients& clients);
446 // The timeout timer periodically calls OnTimeoutTimer, which stops the worker
447 // if it is excessively idle or unresponsive to ping.
448 void StartTimeoutTimer();
449 void StopTimeoutTimer();
450 void OnTimeoutTimer();
452 // The ping protocol is for terminating workers that are taking excessively
453 // long executing JavaScript (e.g., stuck in while(true) {}). Periodically a
454 // ping IPC is sent to the worker context and if we timeout waiting for a
455 // pong, the worker is terminated. Pinging starts after the script is loaded.
456 void PingWorker();
457 void OnPingTimeout();
459 // Stops the worker if it is idle (has no in-flight requests) or timed out
460 // ping.
461 void StopWorkerIfIdle();
462 bool HasInflightRequests() const;
464 // RecordStartWorkerResult is added as a start callback by StartTimeoutTimer
465 // and records metrics about startup.
466 void RecordStartWorkerResult(ServiceWorkerStatusCode status);
468 void DoomInternal();
470 template <typename IDMAP>
471 void RemoveCallbackAndStopIfDoomed(IDMAP* callbacks, int request_id);
473 template <typename CallbackType>
474 int AddRequest(const CallbackType& callback,
475 IDMap<CallbackType, IDMapOwnPointer>* callback_map,
476 RequestType request_type);
478 bool OnRequestTimeout(const RequestInfo& info);
479 void SetAllRequestTimes(const base::TimeTicks& ticks);
481 const int64 version_id_;
482 int64 registration_id_;
483 GURL script_url_;
484 GURL scope_;
485 Status status_;
486 scoped_ptr<EmbeddedWorkerInstance> embedded_worker_;
487 std::vector<StatusCallback> start_callbacks_;
488 std::vector<StatusCallback> stop_callbacks_;
489 std::vector<base::Closure> status_change_callbacks_;
491 // Message callbacks. (Update HasInflightRequests() too when you update this
492 // list.)
493 IDMap<StatusCallback, IDMapOwnPointer> activate_callbacks_;
494 IDMap<StatusCallback, IDMapOwnPointer> install_callbacks_;
495 IDMap<FetchCallback, IDMapOwnPointer> fetch_callbacks_;
496 IDMap<StatusCallback, IDMapOwnPointer> sync_callbacks_;
497 IDMap<StatusCallback, IDMapOwnPointer> notification_click_callbacks_;
498 IDMap<StatusCallback, IDMapOwnPointer> push_callbacks_;
499 IDMap<StatusCallback, IDMapOwnPointer> geofencing_callbacks_;
500 IDMap<CrossOriginConnectCallback, IDMapOwnPointer>
501 cross_origin_connect_callbacks_;
503 std::set<const ServiceWorkerURLRequestJob*> streaming_url_request_jobs_;
505 std::map<std::string, ServiceWorkerProviderHost*> controllee_map_;
506 // Will be null while shutting down.
507 base::WeakPtr<ServiceWorkerContextCore> context_;
508 ObserverList<Listener> listeners_;
509 ServiceWorkerScriptCacheMap script_cache_map_;
510 base::OneShotTimer<ServiceWorkerVersion> update_timer_;
512 // Starts running in StartWorker and continues until the worker is stopped.
513 base::RepeatingTimer<ServiceWorkerVersion> timeout_timer_;
514 // Holds the time the worker last started being considered idle.
515 base::TimeTicks idle_time_;
516 // Holds the time that an outstanding ping was sent to the worker.
517 base::TimeTicks ping_time_;
518 // The state of the ping protocol.
519 PingState ping_state_;
520 // Holds the time that the outstanding StartWorker() request started.
521 base::TimeTicks start_time_;
523 // New requests are added to |requests_| along with their entry in a callback
524 // map. The timeout timer periodically checks |requests_| for entries that
525 // should time out or have already been fulfilled (i.e., removed from the
526 // callback map).
527 std::queue<RequestInfo> requests_;
529 bool is_doomed_ = false;
530 bool skip_waiting_ = false;
531 bool skip_recording_startup_time_ = false;
533 std::vector<int> pending_skip_waiting_requests_;
534 scoped_ptr<net::HttpResponseInfo> main_script_http_info_;
536 base::WeakPtrFactory<ServiceWorkerVersion> weak_factory_;
538 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion);
541 } // namespace content
543 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_