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_
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"
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
43 class CONTENT_EXPORT ServiceWorkerVersion
44 : NON_EXPORTED_BASE(public base::RefCounted<ServiceWorkerVersion>),
45 public EmbeddedWorkerInstance::Listener {
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;
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.
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.
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,
82 const GURL& source_url) {}
83 virtual void OnReportConsoleMessage(ServiceWorkerVersion* version,
84 int source_identifier,
86 const base::string16& message,
88 const GURL& source_url) {}
89 // Fires when a version transitions from having a controllee to not.
90 virtual void OnNoControllees(ServiceWorkerVersion* version) {}
93 virtual ~Listener() {}
97 ServiceWorkerRegistration* registration,
99 base::WeakPtr<ServiceWorkerContextCore> context);
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());
108 ServiceWorkerVersionInfo GetInfo();
109 Status status() const { return status_; }
111 // This sets the new status and also run status change callbacks
112 // if there're any (see RegisterStatusChangeCallback).
113 void SetStatus(Status status);
115 // Registers status change callback. (This is for one-off observation,
116 // the consumer needs to re-register if it wants to continue observing
118 void RegisterStatusChangeCallback(const base::Closure& callback);
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);
124 // Starts an embedded worker for this version.
125 // |potential_process_ids| is a list of processes in which to start the
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);
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);
137 // Schedules an update to be run 'soon'.
138 void ScheduleUpdate();
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();
144 // Starts an update now.
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);
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.
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);
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.
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);
177 // Sends fetch event to the associated embedded worker and calls
178 // |callback| with the response from the worker.
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);
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
189 // This must be called when the status() is ACTIVATED.
190 void DispatchSyncEvent(const StatusCallback& callback);
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
196 // This must be called when the status() is ACTIVATED.
197 void DispatchPushEvent(const StatusCallback& callback,
198 const std::string& data);
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);
206 // Returns true if this has at least one process to run.
207 bool HasProcessToRun() const;
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);
217 // Returns if it has controllee.
218 bool HasControllee() const { return !controllee_map_.empty(); }
220 // Adds and removes Listeners.
221 void AddListener(Listener* listener);
222 void RemoveListener(Listener* listener);
224 ServiceWorkerScriptCacheMap* script_cache_map() { return &script_cache_map_; }
225 EmbeddedWorkerInstance* embedded_worker() { return embedded_worker_.get(); }
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.
231 bool is_doomed() const { return is_doomed_; }
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);
242 virtual ~ServiceWorkerVersion();
244 // EmbeddedWorkerInstance::Listener overrides:
245 virtual void OnStarted() OVERRIDE;
246 virtual void OnStopped() OVERRIDE;
247 virtual void OnReportException(const base::string16& error_message,
250 const GURL& source_url) OVERRIDE;
251 virtual void OnReportConsoleMessage(int source_identifier,
253 const base::string16& message,
255 const GURL& source_url) OVERRIDE;
256 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
258 void RunStartWorkerCallbacksOnError(ServiceWorkerStatusCode status);
260 void DispatchInstallEventAfterStartWorker(int active_version_id,
261 const StatusCallback& callback);
262 void DispatchActivateEventAfterStartWorker(const StatusCallback& callback);
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);
279 void ScheduleStopWorker();
282 const int64 version_id_;
283 int64 registration_id_;
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_;
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_;
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_;
309 base::WeakPtrFactory<ServiceWorkerVersion> weak_factory_;
311 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion);
314 } // namespace content
316 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_