Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / content / browser / service_worker / service_worker_version.h
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.
4
5 #ifndef CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_
6 #define CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_
7
8 #include <map>
9 #include <string>
10 #include <vector>
11
12 #include "base/basictypes.h"
13 #include "base/callback.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/id_map.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/observer_list.h"
19 #include "base/timer/timer.h"
20 #include "content/browser/service_worker/embedded_worker_instance.h"
21 #include "content/browser/service_worker/service_worker_cache_listener.h"
22 #include "content/browser/service_worker/service_worker_script_cache_map.h"
23 #include "content/common/content_export.h"
24 #include "content/common/service_worker/service_worker_status_code.h"
25 #include "content/common/service_worker/service_worker_types.h"
26 #include "third_party/WebKit/public/platform/WebServiceWorkerEventResult.h"
27
28 class GURL;
29
30 namespace content {
31
32 class EmbeddedWorkerRegistry;
33 class ServiceWorkerContextCore;
34 class ServiceWorkerProviderHost;
35 class ServiceWorkerRegistration;
36 class ServiceWorkerVersionInfo;
37
38 // This class corresponds to a specific version of a ServiceWorker
39 // script for a given pattern. When a script is upgraded, there may be
40 // more than one ServiceWorkerVersion "running" at a time, but only
41 // one of them is activated. This class connects the actual script with a
42 // running worker.
43 class CONTENT_EXPORT ServiceWorkerVersion
44     : NON_EXPORTED_BASE(public base::RefCounted<ServiceWorkerVersion>),
45       public EmbeddedWorkerInstance::Listener {
46  public:
47   typedef base::Callback<void(ServiceWorkerStatusCode)> StatusCallback;
48   typedef base::Callback<void(ServiceWorkerStatusCode,
49                               const IPC::Message& message)> MessageCallback;
50   typedef base::Callback<void(ServiceWorkerStatusCode,
51                               ServiceWorkerFetchEventResult,
52                               const ServiceWorkerResponse&)> FetchCallback;
53
54   enum RunningStatus {
55     STOPPED = EmbeddedWorkerInstance::STOPPED,
56     STARTING = EmbeddedWorkerInstance::STARTING,
57     RUNNING = EmbeddedWorkerInstance::RUNNING,
58     STOPPING = EmbeddedWorkerInstance::STOPPING,
59   };
60
61   // Current version status; some of the status (e.g. INSTALLED and ACTIVATED)
62   // should be persisted unlike running status.
63   enum Status {
64     NEW,         // The version is just created.
65     INSTALLING,  // Install event is dispatched and being handled.
66     INSTALLED,   // Install event is finished and is ready to be activated.
67     ACTIVATING,  // Activate event is dispatched and being handled.
68     ACTIVATED,   // Activation is finished and can run as activated.
69     REDUNDANT,   // The version is no longer running as activated, due to
70                  // unregistration or replace.
71   };
72
73   class Listener {
74    public:
75     virtual void OnWorkerStarted(ServiceWorkerVersion* version) {}
76     virtual void OnWorkerStopped(ServiceWorkerVersion* version) {}
77     virtual void OnVersionStateChanged(ServiceWorkerVersion* version) {}
78     virtual void OnErrorReported(ServiceWorkerVersion* version,
79                                  const base::string16& error_message,
80                                  int line_number,
81                                  int column_number,
82                                  const GURL& source_url) {}
83     virtual void OnReportConsoleMessage(ServiceWorkerVersion* version,
84                                         int source_identifier,
85                                         int message_level,
86                                         const base::string16& message,
87                                         int line_number,
88                                         const GURL& source_url) {}
89     // Fires when a version transitions from having a controllee to not.
90     virtual void OnNoControllees(ServiceWorkerVersion* version) {}
91
92    protected:
93     virtual ~Listener() {}
94   };
95
96   ServiceWorkerVersion(
97       ServiceWorkerRegistration* registration,
98       int64 version_id,
99       base::WeakPtr<ServiceWorkerContextCore> context);
100
101   int64 version_id() const { return version_id_; }
102   int64 registration_id() const { return registration_id_; }
103   const GURL& script_url() const { return script_url_; }
104   const GURL& scope() const { return scope_; }
105   RunningStatus running_status() const {
106     return static_cast<RunningStatus>(embedded_worker_->status());
107   }
108   ServiceWorkerVersionInfo GetInfo();
109   Status status() const { return status_; }
110
111   // This sets the new status and also run status change callbacks
112   // if there're any (see RegisterStatusChangeCallback).
113   void SetStatus(Status status);
114
115   // Registers status change callback. (This is for one-off observation,
116   // the consumer needs to re-register if it wants to continue observing
117   // status changes)
118   void RegisterStatusChangeCallback(const base::Closure& callback);
119
120   // Starts an embedded worker for this version.
121   // This returns OK (success) if the worker is already running.
122   void StartWorker(const StatusCallback& callback);
123
124   // Starts an embedded worker for this version.
125   // |potential_process_ids| is a list of processes in which to start the
126   // worker.
127   // This returns OK (success) if the worker is already running.
128   void StartWorkerWithCandidateProcesses(
129       const std::vector<int>& potential_process_ids,
130       bool pause_after_download,
131       const StatusCallback& callback);
132
133   // Stops an embedded worker for this version.
134   // This returns OK (success) if the worker is already stopped.
135   void StopWorker(const StatusCallback& callback);
136
137   // Schedules an update to be run 'soon'.
138   void ScheduleUpdate();
139
140   // If an update is scheduled but not yet started, this resets the timer
141   // delaying the start time by a 'small' amount.
142   void DeferScheduledUpdate();
143
144   // Starts an update now.
145   void StartUpdate();
146
147   // Sends an IPC message to the worker.
148   // If the worker is not running this first tries to start it by
149   // calling StartWorker internally.
150   // |callback| can be null if the sender does not need to know if the
151   // message is successfully sent or not.
152   void SendMessage(const IPC::Message& message, const StatusCallback& callback);
153
154   // Sends install event to the associated embedded worker and asynchronously
155   // calls |callback| when it errors out or it gets response from the worker
156   // to notify install completion.
157   // |active_version_id| must be a valid positive ID
158   // if there's an activated (previous) version running.
159   //
160   // This must be called when the status() is NEW. Calling this changes
161   // the version's status to INSTALLING.
162   // Upon completion, the version's status will be changed to INSTALLED
163   // on success, or back to NEW on failure.
164   void DispatchInstallEvent(int active_version_id,
165                             const StatusCallback& callback);
166
167   // Sends activate event to the associated embedded worker and asynchronously
168   // calls |callback| when it errors out or it gets response from the worker
169   // to notify activation completion.
170   //
171   // This must be called when the status() is INSTALLED. Calling this changes
172   // the version's status to ACTIVATING.
173   // Upon completion, the version's status will be changed to ACTIVATED
174   // on success, or back to INSTALLED on failure.
175   void DispatchActivateEvent(const StatusCallback& callback);
176
177   // Sends fetch event to the associated embedded worker and calls
178   // |callback| with the response from the worker.
179   //
180   // This must be called when the status() is ACTIVATED. Calling this in other
181   // statuses will result in an error SERVICE_WORKER_ERROR_FAILED.
182   void DispatchFetchEvent(const ServiceWorkerFetchRequest& request,
183                           const FetchCallback& callback);
184
185   // Sends sync event to the associated embedded worker and asynchronously calls
186   // |callback| when it errors out or it gets response from the worker to notify
187   // completion.
188   //
189   // This must be called when the status() is ACTIVATED.
190   void DispatchSyncEvent(const StatusCallback& callback);
191
192   // Sends push event to the associated embedded worker and asynchronously calls
193   // |callback| when it errors out or it gets response from the worker to notify
194   // completion.
195   //
196   // This must be called when the status() is ACTIVATED.
197   void DispatchPushEvent(const StatusCallback& callback,
198                          const std::string& data);
199
200   // These are expected to be called when a renderer process host for the
201   // same-origin as for this ServiceWorkerVersion is created.  The added
202   // processes are used to run an in-renderer embedded worker.
203   void AddProcessToWorker(int process_id);
204   void RemoveProcessFromWorker(int process_id);
205
206   // Returns true if this has at least one process to run.
207   bool HasProcessToRun() const;
208
209   // Adds and removes |provider_host| as a controllee of this ServiceWorker.
210   // A potential controllee is a host having the version as its .installing
211   // or .waiting version.
212   void AddControllee(ServiceWorkerProviderHost* provider_host);
213   void RemoveControllee(ServiceWorkerProviderHost* provider_host);
214   void AddPotentialControllee(ServiceWorkerProviderHost* provider_host);
215   void RemovePotentialControllee(ServiceWorkerProviderHost* provider_host);
216
217   // Returns if it has controllee.
218   bool HasControllee() const { return !controllee_map_.empty(); }
219
220   // Adds and removes Listeners.
221   void AddListener(Listener* listener);
222   void RemoveListener(Listener* listener);
223
224   ServiceWorkerScriptCacheMap* script_cache_map() { return &script_cache_map_; }
225   EmbeddedWorkerInstance* embedded_worker() { return embedded_worker_.get(); }
226
227   // Dooms this version to have REDUNDANT status and its resources deleted.  If
228   // the version is controlling a page, these changes will happen when the
229   // version no longer controls any pages.
230   void Doom();
231   bool is_doomed() const { return is_doomed_; }
232
233  private:
234   friend class base::RefCounted<ServiceWorkerVersion>;
235   FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest,
236                            ActivateWaitingVersion);
237   typedef ServiceWorkerVersion self;
238   typedef std::map<ServiceWorkerProviderHost*, int> ControlleeMap;
239   typedef IDMap<ServiceWorkerProviderHost> ControlleeByIDMap;
240   FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, ScheduleStopWorker);
241
242   virtual ~ServiceWorkerVersion();
243
244   // EmbeddedWorkerInstance::Listener overrides:
245   virtual void OnStarted() OVERRIDE;
246   virtual void OnStopped() OVERRIDE;
247   virtual void OnReportException(const base::string16& error_message,
248                                  int line_number,
249                                  int column_number,
250                                  const GURL& source_url) OVERRIDE;
251   virtual void OnReportConsoleMessage(int source_identifier,
252                                       int message_level,
253                                       const base::string16& message,
254                                       int line_number,
255                                       const GURL& source_url) OVERRIDE;
256   virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
257
258   void RunStartWorkerCallbacksOnError(ServiceWorkerStatusCode status);
259
260   void DispatchInstallEventAfterStartWorker(int active_version_id,
261                                             const StatusCallback& callback);
262   void DispatchActivateEventAfterStartWorker(const StatusCallback& callback);
263
264   // Message handlers.
265   void OnGetClientDocuments(int request_id);
266   void OnActivateEventFinished(int request_id,
267                                blink::WebServiceWorkerEventResult result);
268   void OnInstallEventFinished(int request_id,
269                               blink::WebServiceWorkerEventResult result);
270   void OnFetchEventFinished(int request_id,
271                             ServiceWorkerFetchEventResult result,
272                             const ServiceWorkerResponse& response);
273   void OnSyncEventFinished(int request_id);
274   void OnPushEventFinished(int request_id);
275   void OnPostMessageToDocument(int client_id,
276                                const base::string16& message,
277                                const std::vector<int>& sent_message_port_ids);
278
279   void ScheduleStopWorker();
280   void DoomInternal();
281
282   const int64 version_id_;
283   int64 registration_id_;
284   GURL script_url_;
285   GURL scope_;
286   Status status_;
287   scoped_ptr<EmbeddedWorkerInstance> embedded_worker_;
288   scoped_ptr<ServiceWorkerCacheListener> cache_listener_;
289   std::vector<StatusCallback> start_callbacks_;
290   std::vector<StatusCallback> stop_callbacks_;
291   std::vector<base::Closure> status_change_callbacks_;
292
293   // Message callbacks.
294   IDMap<StatusCallback, IDMapOwnPointer> activate_callbacks_;
295   IDMap<StatusCallback, IDMapOwnPointer> install_callbacks_;
296   IDMap<FetchCallback, IDMapOwnPointer> fetch_callbacks_;
297   IDMap<StatusCallback, IDMapOwnPointer> sync_callbacks_;
298   IDMap<StatusCallback, IDMapOwnPointer> push_callbacks_;
299
300   ControlleeMap controllee_map_;
301   ControlleeByIDMap controllee_by_id_;
302   base::WeakPtr<ServiceWorkerContextCore> context_;
303   ObserverList<Listener> listeners_;
304   ServiceWorkerScriptCacheMap script_cache_map_;
305   base::OneShotTimer<ServiceWorkerVersion> stop_worker_timer_;
306   base::OneShotTimer<ServiceWorkerVersion> update_timer_;
307   bool is_doomed_;
308
309   base::WeakPtrFactory<ServiceWorkerVersion> weak_factory_;
310
311   DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion);
312 };
313
314 }  // namespace content
315
316 #endif  // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_