Battery Status API: add UMA logging for Linux.
[chromium-blink-merge.git] / content / browser / service_worker / service_worker_version.h
blobee1194ef75b33ada1fd65868cacc5a35ac2f400c
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 <string>
10 #include <vector>
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"
28 class GURL;
30 namespace content {
32 class EmbeddedWorkerRegistry;
33 class ServiceWorkerContextCore;
34 class ServiceWorkerProviderHost;
35 class ServiceWorkerRegistration;
36 class ServiceWorkerVersionInfo;
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;
54 enum RunningStatus {
55 STOPPED = EmbeddedWorkerInstance::STOPPED,
56 STARTING = EmbeddedWorkerInstance::STARTING,
57 RUNNING = EmbeddedWorkerInstance::RUNNING,
58 STOPPING = EmbeddedWorkerInstance::STOPPING,
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.
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) {}
92 protected:
93 virtual ~Listener() {}
96 ServiceWorkerVersion(
97 ServiceWorkerRegistration* registration,
98 const GURL& script_url,
99 int64 version_id,
100 base::WeakPtr<ServiceWorkerContextCore> context);
102 int64 version_id() const { return version_id_; }
103 int64 registration_id() const { return registration_id_; }
104 const GURL& script_url() const { return script_url_; }
105 const GURL& scope() const { return scope_; }
106 RunningStatus running_status() const {
107 return static_cast<RunningStatus>(embedded_worker_->status());
109 ServiceWorkerVersionInfo GetInfo();
110 Status status() const { return status_; }
112 // This sets the new status and also run status change callbacks
113 // if there're any (see RegisterStatusChangeCallback).
114 void SetStatus(Status status);
116 // Registers status change callback. (This is for one-off observation,
117 // the consumer needs to re-register if it wants to continue observing
118 // status changes)
119 void RegisterStatusChangeCallback(const base::Closure& callback);
121 // Starts an embedded worker for this version.
122 // This returns OK (success) if the worker is already running.
123 void StartWorker(const StatusCallback& callback);
125 // Starts an embedded worker for this version.
126 // |potential_process_ids| is a list of processes in which to start the
127 // worker.
128 // This returns OK (success) if the worker is already running.
129 void StartWorkerWithCandidateProcesses(
130 const std::vector<int>& potential_process_ids,
131 bool pause_after_download,
132 const StatusCallback& callback);
134 // Stops an embedded worker for this version.
135 // This returns OK (success) if the worker is already stopped.
136 void StopWorker(const StatusCallback& callback);
138 // Schedules an update to be run 'soon'.
139 void ScheduleUpdate();
141 // If an update is scheduled but not yet started, this resets the timer
142 // delaying the start time by a 'small' amount.
143 void DeferScheduledUpdate();
145 // Starts an update now.
146 void StartUpdate();
148 // Sends an IPC message to the worker.
149 // If the worker is not running this first tries to start it by
150 // calling StartWorker internally.
151 // |callback| can be null if the sender does not need to know if the
152 // message is successfully sent or not.
153 void SendMessage(const IPC::Message& message, const StatusCallback& callback);
155 // Sends install event to the associated embedded worker and asynchronously
156 // calls |callback| when it errors out or it gets response from the worker
157 // to notify install completion.
158 // |active_version_id| must be a valid positive ID
159 // if there's an activated (previous) version running.
161 // This must be called when the status() is NEW. Calling this changes
162 // the version's status to INSTALLING.
163 // Upon completion, the version's status will be changed to INSTALLED
164 // on success, or back to NEW on failure.
165 void DispatchInstallEvent(int active_version_id,
166 const StatusCallback& callback);
168 // Sends activate event to the associated embedded worker and asynchronously
169 // calls |callback| when it errors out or it gets response from the worker
170 // to notify activation completion.
172 // This must be called when the status() is INSTALLED. Calling this changes
173 // the version's status to ACTIVATING.
174 // Upon completion, the version's status will be changed to ACTIVATED
175 // on success, or back to INSTALLED on failure.
176 void DispatchActivateEvent(const StatusCallback& callback);
178 // Sends fetch event to the associated embedded worker and calls
179 // |callback| with the response from the worker.
181 // This must be called when the status() is ACTIVATED. Calling this in other
182 // statuses will result in an error SERVICE_WORKER_ERROR_FAILED.
183 void DispatchFetchEvent(const ServiceWorkerFetchRequest& request,
184 const base::Closure& prepare_callback,
185 const FetchCallback& fetch_callback);
187 // Sends sync event to the associated embedded worker and asynchronously calls
188 // |callback| when it errors out or it gets response from the worker to notify
189 // completion.
191 // This must be called when the status() is ACTIVATED.
192 void DispatchSyncEvent(const StatusCallback& callback);
194 // Sends push event to the associated embedded worker and asynchronously calls
195 // |callback| when it errors out or it gets response from the worker to notify
196 // completion.
198 // This must be called when the status() is ACTIVATED.
199 void DispatchPushEvent(const StatusCallback& callback,
200 const std::string& data);
202 // These are expected to be called when a renderer process host for the
203 // same-origin as for this ServiceWorkerVersion is created. The added
204 // processes are used to run an in-renderer embedded worker.
205 void AddProcessToWorker(int process_id);
206 void RemoveProcessFromWorker(int process_id);
208 // Returns true if this has at least one process to run.
209 bool HasProcessToRun() const;
211 // Adds and removes |provider_host| as a controllee of this ServiceWorker.
212 // A potential controllee is a host having the version as its .installing
213 // or .waiting version.
214 void AddControllee(ServiceWorkerProviderHost* provider_host);
215 void RemoveControllee(ServiceWorkerProviderHost* provider_host);
216 void AddPotentialControllee(ServiceWorkerProviderHost* provider_host);
217 void RemovePotentialControllee(ServiceWorkerProviderHost* provider_host);
219 // Returns if it has controllee.
220 bool HasControllee() const { return !controllee_map_.empty(); }
222 // Adds and removes Listeners.
223 void AddListener(Listener* listener);
224 void RemoveListener(Listener* listener);
226 ServiceWorkerScriptCacheMap* script_cache_map() { return &script_cache_map_; }
227 EmbeddedWorkerInstance* embedded_worker() { return embedded_worker_.get(); }
229 // Dooms this version to have REDUNDANT status and its resources deleted. If
230 // the version is controlling a page, these changes will happen when the
231 // version no longer controls any pages.
232 void Doom();
233 bool is_doomed() const { return is_doomed_; }
235 private:
236 friend class base::RefCounted<ServiceWorkerVersion>;
237 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest,
238 ActivateWaitingVersion);
239 typedef ServiceWorkerVersion self;
240 typedef std::map<ServiceWorkerProviderHost*, int> ControlleeMap;
241 typedef IDMap<ServiceWorkerProviderHost> ControlleeByIDMap;
242 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, ScheduleStopWorker);
244 virtual ~ServiceWorkerVersion();
246 // EmbeddedWorkerInstance::Listener overrides:
247 virtual void OnStarted() OVERRIDE;
248 virtual void OnStopped() OVERRIDE;
249 virtual void OnReportException(const base::string16& error_message,
250 int line_number,
251 int column_number,
252 const GURL& source_url) OVERRIDE;
253 virtual void OnReportConsoleMessage(int source_identifier,
254 int message_level,
255 const base::string16& message,
256 int line_number,
257 const GURL& source_url) OVERRIDE;
258 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
260 void RunStartWorkerCallbacksOnError(ServiceWorkerStatusCode status);
262 void DispatchInstallEventAfterStartWorker(int active_version_id,
263 const StatusCallback& callback);
264 void DispatchActivateEventAfterStartWorker(const StatusCallback& callback);
266 // Message handlers.
267 void OnGetClientDocuments(int request_id);
268 void OnActivateEventFinished(int request_id,
269 blink::WebServiceWorkerEventResult result);
270 void OnInstallEventFinished(int request_id,
271 blink::WebServiceWorkerEventResult result);
272 void OnFetchEventFinished(int request_id,
273 ServiceWorkerFetchEventResult result,
274 const ServiceWorkerResponse& response);
275 void OnSyncEventFinished(int request_id);
276 void OnPushEventFinished(int request_id);
277 void OnPostMessageToDocument(int client_id,
278 const base::string16& message,
279 const std::vector<int>& sent_message_port_ids);
281 void ScheduleStopWorker();
282 void DoomInternal();
284 const int64 version_id_;
285 int64 registration_id_;
286 GURL script_url_;
287 GURL scope_;
288 Status status_;
289 scoped_ptr<EmbeddedWorkerInstance> embedded_worker_;
290 scoped_ptr<ServiceWorkerCacheListener> cache_listener_;
291 std::vector<StatusCallback> start_callbacks_;
292 std::vector<StatusCallback> stop_callbacks_;
293 std::vector<base::Closure> status_change_callbacks_;
295 // Message callbacks.
296 IDMap<StatusCallback, IDMapOwnPointer> activate_callbacks_;
297 IDMap<StatusCallback, IDMapOwnPointer> install_callbacks_;
298 IDMap<FetchCallback, IDMapOwnPointer> fetch_callbacks_;
299 IDMap<StatusCallback, IDMapOwnPointer> sync_callbacks_;
300 IDMap<StatusCallback, IDMapOwnPointer> push_callbacks_;
302 ControlleeMap controllee_map_;
303 ControlleeByIDMap controllee_by_id_;
304 base::WeakPtr<ServiceWorkerContextCore> context_;
305 ObserverList<Listener> listeners_;
306 ServiceWorkerScriptCacheMap script_cache_map_;
307 base::OneShotTimer<ServiceWorkerVersion> stop_worker_timer_;
308 base::OneShotTimer<ServiceWorkerVersion> update_timer_;
309 bool is_doomed_;
311 base::WeakPtrFactory<ServiceWorkerVersion> weak_factory_;
313 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion);
316 } // namespace content
318 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_