Android: Store language .pak files in res/raw rather than assets
[chromium-blink-merge.git] / content / browser / service_worker / service_worker_version.h
blob0d97f9455cc7baa774ed07eb3ddd173f10e61c21
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;
74 typedef base::Callback<void(ServiceWorkerStatusCode, const std::vector<int>&)>
75 SendStashedPortsCallback;
77 enum RunningStatus {
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.
86 enum 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.
96 class Listener {
97 public:
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,
104 int line_number,
105 int column_number,
106 const GURL& source_url) {}
107 virtual void OnReportConsoleMessage(ServiceWorkerVersion* version,
108 int source_identifier,
109 int message_level,
110 const base::string16& message,
111 int line_number,
112 const GURL& source_url) {}
113 virtual void OnControlleeAdded(ServiceWorkerVersion* version,
114 ServiceWorkerProviderHost* provider_host) {}
115 virtual void OnControlleeRemoved(ServiceWorkerVersion* version,
116 ServiceWorkerProviderHost* provider_host) {
118 // Fires when a version transitions from having a controllee to not.
119 virtual void OnNoControllees(ServiceWorkerVersion* version) {}
120 virtual void OnCachedMetadataUpdated(ServiceWorkerVersion* version) {}
122 protected:
123 virtual ~Listener() {}
126 ServiceWorkerVersion(
127 ServiceWorkerRegistration* registration,
128 const GURL& script_url,
129 int64 version_id,
130 base::WeakPtr<ServiceWorkerContextCore> context);
132 int64 version_id() const { return version_id_; }
133 int64 registration_id() const { return registration_id_; }
134 const GURL& script_url() const { return script_url_; }
135 const GURL& scope() const { return scope_; }
136 RunningStatus running_status() const {
137 return static_cast<RunningStatus>(embedded_worker_->status());
139 ServiceWorkerVersionInfo GetInfo();
140 Status status() const { return status_; }
142 // This sets the new status and also run status change callbacks
143 // if there're any (see RegisterStatusChangeCallback).
144 void SetStatus(Status status);
146 // Registers status change callback. (This is for one-off observation,
147 // the consumer needs to re-register if it wants to continue observing
148 // status changes)
149 void RegisterStatusChangeCallback(const base::Closure& callback);
151 // Starts an embedded worker for this version.
152 // This returns OK (success) if the worker is already running.
153 void StartWorker(const StatusCallback& callback);
155 // Starts an embedded worker for this version.
156 // |pause_after_download| notifies worker to pause after download finished
157 // which could be resumed by EmbeddedWorkerInstance::ResumeAfterDownload.
158 // This returns OK (success) if the worker is already running.
159 void StartWorker(bool pause_after_download,
160 const StatusCallback& callback);
162 // Stops an embedded worker for this version.
163 // This returns OK (success) if the worker is already stopped.
164 void StopWorker(const StatusCallback& callback);
166 // Schedules an update to be run 'soon'.
167 void ScheduleUpdate();
169 // If an update is scheduled but not yet started, this resets the timer
170 // delaying the start time by a 'small' amount.
171 void DeferScheduledUpdate();
173 // Starts an update now.
174 void StartUpdate();
176 // Sends a message event to the associated embedded worker.
177 void DispatchMessageEvent(
178 const base::string16& message,
179 const std::vector<TransferredMessagePort>& sent_message_ports,
180 const StatusCallback& callback);
182 // Sends install event to the associated embedded worker and asynchronously
183 // calls |callback| when it errors out or it gets a response from the worker
184 // to notify install completion.
186 // This must be called when the status() is NEW. Calling this changes
187 // the version's status to INSTALLING.
188 // Upon completion, the version's status will be changed to INSTALLED
189 // on success, or back to NEW on failure.
190 void DispatchInstallEvent(const StatusCallback& callback);
192 // Sends activate event to the associated embedded worker and asynchronously
193 // calls |callback| when it errors out or it gets a response from the worker
194 // to notify activation completion.
196 // This must be called when the status() is INSTALLED. Calling this changes
197 // the version's status to ACTIVATING.
198 // Upon completion, the version's status will be changed to ACTIVATED
199 // on success, or back to INSTALLED on failure.
200 void DispatchActivateEvent(const StatusCallback& callback);
202 // Sends fetch event to the associated embedded worker and calls
203 // |callback| with the response from the worker.
205 // This must be called when the status() is ACTIVATED. Calling this in other
206 // statuses will result in an error SERVICE_WORKER_ERROR_FAILED.
207 void DispatchFetchEvent(const ServiceWorkerFetchRequest& request,
208 const base::Closure& prepare_callback,
209 const FetchCallback& fetch_callback);
211 // Sends sync event to the associated embedded worker and asynchronously calls
212 // |callback| when it errors out or it gets a response from the worker to
213 // notify completion.
215 // This must be called when the status() is ACTIVATED.
216 void DispatchSyncEvent(const StatusCallback& callback);
218 // Sends notificationclick event to the associated embedded worker and
219 // asynchronously calls |callback| when it errors out or it gets a response
220 // from the worker to notify completion.
222 // This must be called when the status() is ACTIVATED.
223 void DispatchNotificationClickEvent(
224 const StatusCallback& callback,
225 int64_t persistent_notification_id,
226 const PlatformNotificationData& notification_data);
228 // Sends push event to the associated embedded worker and asynchronously calls
229 // |callback| when it errors out or it gets a response from the worker to
230 // notify completion.
232 // This must be called when the status() is ACTIVATED.
233 void DispatchPushEvent(const StatusCallback& callback,
234 const std::string& data);
236 // Sends geofencing event to the associated embedded worker and asynchronously
237 // calls |callback| when it errors out or it gets a response from the worker
238 // to notify completion.
240 // This must be called when the status() is ACTIVATED.
241 void DispatchGeofencingEvent(
242 const StatusCallback& callback,
243 blink::WebGeofencingEventType event_type,
244 const std::string& region_id,
245 const blink::WebCircularGeofencingRegion& region);
247 // Sends a cross origin connect event to the associated embedded worker and
248 // asynchronously calls |callback| with the response from the worker.
250 // This must be called when the status() is ACTIVATED.
251 void DispatchCrossOriginConnectEvent(
252 const CrossOriginConnectCallback& callback,
253 const NavigatorConnectClient& client);
255 // Sends a cross origin message event to the associated embedded worker and
256 // asynchronously calls |callback| when the message was sent (or failed to
257 // sent).
258 // It is the responsibility of the code calling this method to make sure that
259 // any transferred message ports are put on hold while potentially a process
260 // for the service worker is spun up.
262 // This must be called when the status() is ACTIVATED.
263 void DispatchCrossOriginMessageEvent(
264 const NavigatorConnectClient& client,
265 const base::string16& message,
266 const std::vector<TransferredMessagePort>& sent_message_ports,
267 const StatusCallback& callback);
269 // Transfers one or more stashed message ports to the associated embedded
270 // worker, and asynchronously calls |callback| with the new route ids for the
271 // transferred ports as soon as the ports are sent to the renderer.
272 // Once the ports are received by the renderer, the ports themselves will
273 // inform MessagePortService, which will enable actual messages to be sent.
274 void SendStashedMessagePorts(
275 const std::vector<TransferredMessagePort>& stashed_message_ports,
276 const std::vector<base::string16>& port_names,
277 const SendStashedPortsCallback& callback);
279 // Adds and removes |provider_host| as a controllee of this ServiceWorker.
280 // A potential controllee is a host having the version as its .installing
281 // or .waiting version.
282 void AddControllee(ServiceWorkerProviderHost* provider_host);
283 void RemoveControllee(ServiceWorkerProviderHost* provider_host);
285 // Returns if it has controllee.
286 bool HasControllee() const { return !controllee_map_.empty(); }
288 // Adds and removes |request_job| as a dependent job not to stop the
289 // ServiceWorker while |request_job| is reading the stream of the fetch event
290 // response from the ServiceWorker.
291 void AddStreamingURLRequestJob(const ServiceWorkerURLRequestJob* request_job);
292 void RemoveStreamingURLRequestJob(
293 const ServiceWorkerURLRequestJob* request_job);
295 // Adds and removes Listeners.
296 void AddListener(Listener* listener);
297 void RemoveListener(Listener* listener);
299 ServiceWorkerScriptCacheMap* script_cache_map() { return &script_cache_map_; }
300 EmbeddedWorkerInstance* embedded_worker() { return embedded_worker_.get(); }
302 // Reports the error message to |listeners_|.
303 void ReportError(ServiceWorkerStatusCode status,
304 const std::string& status_message);
306 // Sets the status code to pass to StartWorker callbacks if start fails.
307 void SetStartWorkerStatusCode(ServiceWorkerStatusCode status);
309 // Sets this version's status to REDUNDANT and deletes its resources.
310 // The version must not have controllees.
311 void Doom();
312 bool is_redundant() const { return status_ == REDUNDANT; }
314 bool skip_waiting() const { return skip_waiting_; }
315 void set_skip_waiting(bool skip_waiting) { skip_waiting_ = skip_waiting; }
317 bool force_bypass_cache_for_scripts() {
318 return force_bypass_cache_for_scripts_;
320 void set_force_bypass_cache_for_scripts(bool force_bypass_cache_for_scripts) {
321 force_bypass_cache_for_scripts_ = force_bypass_cache_for_scripts;
324 void SetDevToolsAttached(bool attached);
326 // Sets the HttpResponseInfo used to load the main script.
327 // This HttpResponseInfo will be used for all responses sent back from the
328 // service worker, as the effective security of these responses is equivalent
329 // to that of the ServiceWorker.
330 void SetMainScriptHttpResponseInfo(const net::HttpResponseInfo& http_info);
331 const net::HttpResponseInfo* GetMainScriptHttpResponseInfo();
333 // Simulate ping timeout. Should be used for tests-only.
334 void SimulatePingTimeoutForTesting();
336 private:
337 friend class base::RefCounted<ServiceWorkerVersion>;
338 friend class ServiceWorkerURLRequestJobTest;
339 friend class ServiceWorkerVersionBrowserTest;
341 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest,
342 ActivateWaitingVersion);
343 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, IdleTimeout);
344 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, SetDevToolsAttached);
345 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerWaitForeverInFetchTest, RequestTimeout);
346 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerFailToStartTest, Timeout);
347 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest,
348 TimeoutStartingWorker);
349 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest,
350 TimeoutWorkerInEvent);
352 class Metrics;
353 class PingController;
355 typedef ServiceWorkerVersion self;
356 using ServiceWorkerClients = std::vector<ServiceWorkerClientInfo>;
358 enum RequestType {
359 REQUEST_ACTIVATE,
360 REQUEST_INSTALL,
361 REQUEST_FETCH,
362 REQUEST_SYNC,
363 REQUEST_NOTIFICATION_CLICK,
364 REQUEST_PUSH,
365 REQUEST_GEOFENCING,
366 REQUEST_CROSS_ORIGIN_CONNECT
369 struct RequestInfo {
370 RequestInfo(int id, RequestType type);
371 ~RequestInfo();
372 int id;
373 RequestType type;
374 base::TimeTicks time;
377 // Timeout for the worker to start.
378 static const int kStartWorkerTimeoutMinutes;
379 // Timeout for a request to be handled.
380 static const int kRequestTimeoutMinutes;
382 ~ServiceWorkerVersion() override;
384 // EmbeddedWorkerInstance::Listener overrides:
385 void OnScriptLoaded() override;
386 void OnStarting() override;
387 void OnStarted() override;
388 void OnStopping() override;
389 void OnStopped(EmbeddedWorkerInstance::Status old_status) override;
390 void OnReportException(const base::string16& error_message,
391 int line_number,
392 int column_number,
393 const GURL& source_url) override;
394 void OnReportConsoleMessage(int source_identifier,
395 int message_level,
396 const base::string16& message,
397 int line_number,
398 const GURL& source_url) override;
399 bool OnMessageReceived(const IPC::Message& message) override;
401 void OnStartSentAndScriptEvaluated(ServiceWorkerStatusCode status);
403 void DispatchInstallEventAfterStartWorker(const StatusCallback& callback);
404 void DispatchActivateEventAfterStartWorker(const StatusCallback& callback);
406 void DispatchMessageEventInternal(
407 const base::string16& message,
408 const std::vector<TransferredMessagePort>& sent_message_ports,
409 const StatusCallback& callback);
411 // Message handlers.
413 // This corresponds to the spec's matchAll(options) steps.
414 void OnGetClients(int request_id,
415 const ServiceWorkerClientQueryOptions& options);
417 void OnActivateEventFinished(int request_id,
418 blink::WebServiceWorkerEventResult result);
419 void OnInstallEventFinished(int request_id,
420 blink::WebServiceWorkerEventResult result);
421 void OnFetchEventFinished(int request_id,
422 ServiceWorkerFetchEventResult result,
423 const ServiceWorkerResponse& response);
424 void OnSyncEventFinished(int request_id,
425 blink::WebServiceWorkerEventResult result);
426 void OnNotificationClickEventFinished(int request_id);
427 void OnPushEventFinished(int request_id,
428 blink::WebServiceWorkerEventResult result);
429 void OnGeofencingEventFinished(int request_id);
430 void OnCrossOriginConnectEventFinished(int request_id,
431 bool accept_connection);
432 void OnOpenWindow(int request_id, GURL url);
433 void DidOpenWindow(int request_id,
434 int render_process_id,
435 int render_frame_id);
436 void OnOpenWindowFinished(int request_id,
437 const std::string& client_uuid,
438 const ServiceWorkerClientInfo& client_info);
440 void OnSetCachedMetadata(const GURL& url, const std::vector<char>& data);
441 void OnSetCachedMetadataFinished(int64 callback_id, int result);
442 void OnClearCachedMetadata(const GURL& url);
443 void OnClearCachedMetadataFinished(int64 callback_id, int result);
445 void OnPostMessageToClient(
446 const std::string& client_uuid,
447 const base::string16& message,
448 const std::vector<TransferredMessagePort>& sent_message_ports);
449 void OnFocusClient(int request_id, const std::string& client_uuid);
450 void OnSkipWaiting(int request_id);
451 void OnClaimClients(int request_id);
452 void OnPongFromWorker();
453 void OnStashMessagePort(int message_port_id, const base::string16& name);
455 void OnFocusClientFinished(int request_id,
456 const std::string& client_uuid,
457 const ServiceWorkerClientInfo& client);
459 void DidEnsureLiveRegistrationForStartWorker(
460 bool pause_after_download,
461 const StatusCallback& callback,
462 ServiceWorkerStatusCode status,
463 const scoped_refptr<ServiceWorkerRegistration>& protect);
464 void StartWorkerInternal(bool pause_after_download);
466 void DidSkipWaiting(int request_id);
468 void GetWindowClients(int request_id,
469 const ServiceWorkerClientQueryOptions& options);
470 void DidGetWindowClients(int request_id,
471 const ServiceWorkerClientQueryOptions& options,
472 scoped_ptr<ServiceWorkerClients> clients);
473 void GetNonWindowClients(int request_id,
474 const ServiceWorkerClientQueryOptions& options,
475 ServiceWorkerClients* clients);
476 void OnGetClientsFinished(int request_id,
477 const ServiceWorkerClients& clients);
479 // The timeout timer periodically calls OnTimeoutTimer, which stops the worker
480 // if it is excessively idle or unresponsive to ping.
481 void StartTimeoutTimer();
482 void StopTimeoutTimer();
483 void OnTimeoutTimer();
485 // Called by PingController for ping protocol.
486 ServiceWorkerStatusCode PingWorker();
487 void OnPingTimeout();
489 // Stops the worker if it is idle (has no in-flight requests) or timed out
490 // ping.
491 void StopWorkerIfIdle();
492 bool HasInflightRequests() const;
494 // RecordStartWorkerResult is added as a start callback by StartTimeoutTimer
495 // and records metrics about startup.
496 void RecordStartWorkerResult(ServiceWorkerStatusCode status);
498 template <typename IDMAP>
499 void RemoveCallbackAndStopIfRedundant(IDMAP* callbacks, int request_id);
501 template <typename CallbackType>
502 int AddRequest(const CallbackType& callback,
503 IDMap<CallbackType, IDMapOwnPointer>* callback_map,
504 RequestType request_type);
506 bool OnRequestTimeout(const RequestInfo& info);
507 void SetAllRequestTimes(const base::TimeTicks& ticks);
509 // Returns the reason the embedded worker failed to start, using information
510 // inaccessible to EmbeddedWorkerInstance. Returns |default_code| if it can't
511 // deduce a reason.
512 ServiceWorkerStatusCode DeduceStartWorkerFailureReason(
513 ServiceWorkerStatusCode default_code);
515 const int64 version_id_;
516 const int64 registration_id_;
517 const GURL script_url_;
518 const GURL scope_;
520 Status status_ = NEW;
521 scoped_ptr<EmbeddedWorkerInstance> embedded_worker_;
522 std::vector<StatusCallback> start_callbacks_;
523 std::vector<StatusCallback> stop_callbacks_;
524 std::vector<base::Closure> status_change_callbacks_;
526 // Message callbacks. (Update HasInflightRequests() too when you update this
527 // list.)
528 IDMap<StatusCallback, IDMapOwnPointer> activate_callbacks_;
529 IDMap<StatusCallback, IDMapOwnPointer> install_callbacks_;
530 IDMap<FetchCallback, IDMapOwnPointer> fetch_callbacks_;
531 IDMap<StatusCallback, IDMapOwnPointer> sync_callbacks_;
532 IDMap<StatusCallback, IDMapOwnPointer> notification_click_callbacks_;
533 IDMap<StatusCallback, IDMapOwnPointer> push_callbacks_;
534 IDMap<StatusCallback, IDMapOwnPointer> geofencing_callbacks_;
535 IDMap<CrossOriginConnectCallback, IDMapOwnPointer>
536 cross_origin_connect_callbacks_;
538 std::set<const ServiceWorkerURLRequestJob*> streaming_url_request_jobs_;
540 std::map<std::string, ServiceWorkerProviderHost*> controllee_map_;
541 // Will be null while shutting down.
542 base::WeakPtr<ServiceWorkerContextCore> context_;
543 base::ObserverList<Listener> listeners_;
544 ServiceWorkerScriptCacheMap script_cache_map_;
545 base::OneShotTimer<ServiceWorkerVersion> update_timer_;
547 // Starts running in StartWorker and continues until the worker is stopped.
548 base::RepeatingTimer<ServiceWorkerVersion> timeout_timer_;
549 // Holds the time the worker last started being considered idle.
550 base::TimeTicks idle_time_;
551 // Holds the time that the outstanding StartWorker() request started.
552 base::TimeTicks start_time_;
554 // New requests are added to |requests_| along with their entry in a callback
555 // map. The timeout timer periodically checks |requests_| for entries that
556 // should time out or have already been fulfilled (i.e., removed from the
557 // callback map).
558 std::queue<RequestInfo> requests_;
560 bool skip_waiting_ = false;
561 bool skip_recording_startup_time_ = false;
562 bool force_bypass_cache_for_scripts_ = false;
564 std::vector<int> pending_skip_waiting_requests_;
565 scoped_ptr<net::HttpResponseInfo> main_script_http_info_;
567 // The status when StartWorker was invoked. Used for UMA.
568 Status prestart_status_ = NEW;
569 // If not OK, the reason that StartWorker failed. Used for
570 // running |start_callbacks_|.
571 ServiceWorkerStatusCode start_worker_status_ = SERVICE_WORKER_OK;
573 scoped_ptr<PingController> ping_controller_;
574 scoped_ptr<Metrics> metrics_;
576 base::WeakPtrFactory<ServiceWorkerVersion> weak_factory_;
578 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion);
581 } // namespace content
583 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_