[Storage] Blob Storage Refactoring pt 1:
[chromium-blink-merge.git] / content / browser / service_worker / service_worker_version.h
blob136cee9b8809c4afcf5f053ae67abaa65e9048ad
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 <set>
10 #include <string>
11 #include <vector>
13 #include "base/basictypes.h"
14 #include "base/callback.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/id_map.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/observer_list.h"
20 #include "base/timer/timer.h"
21 #include "content/browser/service_worker/embedded_worker_instance.h"
22 #include "content/browser/service_worker/service_worker_cache_listener.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 class GURL;
32 namespace blink {
33 struct WebCircularGeofencingRegion;
36 namespace content {
38 struct CrossOriginServiceWorkerClient;
39 class EmbeddedWorkerRegistry;
40 struct PlatformNotificationData;
41 class ServiceWorkerContextCore;
42 class ServiceWorkerProviderHost;
43 class ServiceWorkerRegistration;
44 class ServiceWorkerURLRequestJob;
45 class ServiceWorkerVersionInfo;
47 // This class corresponds to a specific version of a ServiceWorker
48 // script for a given pattern. When a script is upgraded, there may be
49 // more than one ServiceWorkerVersion "running" at a time, but only
50 // one of them is activated. This class connects the actual script with a
51 // running worker.
52 class CONTENT_EXPORT ServiceWorkerVersion
53 : NON_EXPORTED_BASE(public base::RefCounted<ServiceWorkerVersion>),
54 public EmbeddedWorkerInstance::Listener {
55 public:
56 typedef base::Callback<void(ServiceWorkerStatusCode)> StatusCallback;
57 typedef base::Callback<void(ServiceWorkerStatusCode,
58 const IPC::Message& message)> MessageCallback;
59 typedef base::Callback<void(ServiceWorkerStatusCode,
60 ServiceWorkerFetchEventResult,
61 const ServiceWorkerResponse&)> FetchCallback;
62 typedef base::Callback<void(ServiceWorkerStatusCode,
63 const ServiceWorkerClientInfo&)>
64 GetClientInfoCallback;
65 typedef base::Callback<void(ServiceWorkerStatusCode, bool)>
66 CrossOriginConnectCallback;
68 enum RunningStatus {
69 STOPPED = EmbeddedWorkerInstance::STOPPED,
70 STARTING = EmbeddedWorkerInstance::STARTING,
71 RUNNING = EmbeddedWorkerInstance::RUNNING,
72 STOPPING = EmbeddedWorkerInstance::STOPPING,
75 // Current version status; some of the status (e.g. INSTALLED and ACTIVATED)
76 // should be persisted unlike running status.
77 enum Status {
78 NEW, // The version is just created.
79 INSTALLING, // Install event is dispatched and being handled.
80 INSTALLED, // Install event is finished and is ready to be activated.
81 ACTIVATING, // Activate event is dispatched and being handled.
82 ACTIVATED, // Activation is finished and can run as activated.
83 REDUNDANT, // The version is no longer running as activated, due to
84 // unregistration or replace.
87 class Listener {
88 public:
89 virtual void OnWorkerStarted(ServiceWorkerVersion* version) {}
90 virtual void OnWorkerStopped(ServiceWorkerVersion* version) {}
91 virtual void OnVersionStateChanged(ServiceWorkerVersion* version) {}
92 virtual void OnErrorReported(ServiceWorkerVersion* version,
93 const base::string16& error_message,
94 int line_number,
95 int column_number,
96 const GURL& source_url) {}
97 virtual void OnReportConsoleMessage(ServiceWorkerVersion* version,
98 int source_identifier,
99 int message_level,
100 const base::string16& message,
101 int line_number,
102 const GURL& source_url) {}
103 // Fires when a version transitions from having a controllee to not.
104 virtual void OnNoControllees(ServiceWorkerVersion* version) {}
106 protected:
107 virtual ~Listener() {}
110 ServiceWorkerVersion(
111 ServiceWorkerRegistration* registration,
112 const GURL& script_url,
113 int64 version_id,
114 base::WeakPtr<ServiceWorkerContextCore> context);
116 int64 version_id() const { return version_id_; }
117 int64 registration_id() const { return registration_id_; }
118 const GURL& script_url() const { return script_url_; }
119 const GURL& scope() const { return scope_; }
120 RunningStatus running_status() const {
121 return static_cast<RunningStatus>(embedded_worker_->status());
123 ServiceWorkerVersionInfo GetInfo();
124 Status status() const { return status_; }
126 // This sets the new status and also run status change callbacks
127 // if there're any (see RegisterStatusChangeCallback).
128 void SetStatus(Status status);
130 // Registers status change callback. (This is for one-off observation,
131 // the consumer needs to re-register if it wants to continue observing
132 // status changes)
133 void RegisterStatusChangeCallback(const base::Closure& callback);
135 // Starts an embedded worker for this version.
136 // This returns OK (success) if the worker is already running.
137 void StartWorker(const StatusCallback& callback);
139 // Starts an embedded worker for this version.
140 // |pause_after_download| notifies worker to pause after download finished
141 // which could be resumed by EmbeddedWorkerInstance::ResumeAfterDownload.
142 // This returns OK (success) if the worker is already running.
143 void StartWorker(bool pause_after_download,
144 const StatusCallback& callback);
146 // Stops an embedded worker for this version.
147 // This returns OK (success) if the worker is already stopped.
148 void StopWorker(const StatusCallback& callback);
150 // Schedules an update to be run 'soon'.
151 void ScheduleUpdate();
153 // If an update is scheduled but not yet started, this resets the timer
154 // delaying the start time by a 'small' amount.
155 void DeferScheduledUpdate();
157 // Starts an update now.
158 void StartUpdate();
160 // Sends an IPC message to the worker.
161 // If the worker is not running this first tries to start it by
162 // calling StartWorker internally.
163 // |callback| can be null if the sender does not need to know if the
164 // message is successfully sent or not.
165 void SendMessage(const IPC::Message& message, const StatusCallback& callback);
167 // Sends a message event to the associated embedded worker.
168 void DispatchMessageEvent(const base::string16& message,
169 const std::vector<int>& sent_message_port_ids,
170 const StatusCallback& callback);
172 // Sends install event to the associated embedded worker and asynchronously
173 // calls |callback| when it errors out or it gets a response from the worker
174 // to notify install completion.
175 // |active_version_id| must be a valid positive ID
176 // if there's an activated (previous) version running.
178 // This must be called when the status() is NEW. Calling this changes
179 // the version's status to INSTALLING.
180 // Upon completion, the version's status will be changed to INSTALLED
181 // on success, or back to NEW on failure.
182 void DispatchInstallEvent(int active_version_id,
183 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 CrossOriginServiceWorkerClient& 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 CrossOriginServiceWorkerClient& client,
258 const base::string16& message,
259 const std::vector<int>& sent_message_port_ids,
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 // Dooms this version to have REDUNDANT status and its resources deleted. If
286 // the version is controlling a page, these changes will happen when the
287 // version no longer controls any pages.
288 void Doom();
289 bool is_doomed() const { return is_doomed_; }
291 bool skip_waiting() const { return skip_waiting_; }
293 void SetDevToolsAttached(bool attached);
295 private:
296 class GetClientDocumentsCallback;
298 friend class base::RefCounted<ServiceWorkerVersion>;
299 friend class ServiceWorkerURLRequestJobTest;
300 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest,
301 ActivateWaitingVersion);
302 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, ScheduleStopWorker);
303 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, KeepAlive);
304 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, ListenerAvailability);
305 typedef ServiceWorkerVersion self;
306 typedef std::map<ServiceWorkerProviderHost*, int> ControlleeMap;
307 typedef IDMap<ServiceWorkerProviderHost> ControlleeByIDMap;
309 ~ServiceWorkerVersion() override;
311 // EmbeddedWorkerInstance::Listener overrides:
312 void OnStarted() override;
313 void OnStopped(EmbeddedWorkerInstance::Status old_status) override;
314 void OnReportException(const base::string16& error_message,
315 int line_number,
316 int column_number,
317 const GURL& source_url) override;
318 void OnReportConsoleMessage(int source_identifier,
319 int message_level,
320 const base::string16& message,
321 int line_number,
322 const GURL& source_url) override;
323 bool OnMessageReceived(const IPC::Message& message) override;
325 void OnStartMessageSent(ServiceWorkerStatusCode status);
327 void DispatchInstallEventAfterStartWorker(int active_version_id,
328 const StatusCallback& callback);
329 void DispatchActivateEventAfterStartWorker(const StatusCallback& callback);
331 void DispatchMessageEventInternal(
332 const base::string16& message,
333 const std::vector<int>& sent_message_port_ids,
334 const StatusCallback& callback);
336 // Message handlers.
337 void OnGetClientDocuments(int request_id);
338 void OnGetClientInfoSuccess(int request_id,
339 const ServiceWorkerClientInfo& info);
340 void OnGetClientInfoError(int request_id);
341 void OnActivateEventFinished(int request_id,
342 blink::WebServiceWorkerEventResult result);
343 void OnInstallEventFinished(int request_id,
344 blink::WebServiceWorkerEventResult result);
345 void OnFetchEventFinished(int request_id,
346 ServiceWorkerFetchEventResult result,
347 const ServiceWorkerResponse& response);
348 void OnSyncEventFinished(int request_id);
349 void OnNotificationClickEventFinished(int request_id);
350 void OnPushEventFinished(int request_id,
351 blink::WebServiceWorkerEventResult result);
352 void OnGeofencingEventFinished(int request_id);
353 void OnCrossOriginConnectEventFinished(int request_id,
354 bool accept_connection);
355 void OnPostMessageToDocument(int client_id,
356 const base::string16& message,
357 const std::vector<int>& sent_message_port_ids);
358 void OnFocusClient(int request_id, int client_id);
359 void OnSkipWaiting(int request_id);
361 void OnFocusClientFinished(int request_id, bool result);
362 void DidSkipWaiting(int request_id);
363 void DidGetClientInfo(int client_id,
364 scoped_refptr<GetClientDocumentsCallback> callback,
365 ServiceWorkerStatusCode status,
366 const ServiceWorkerClientInfo& info);
367 void ScheduleStopWorker();
368 void StopWorkerIfIdle();
369 bool HasInflightRequests() const;
371 void DoomInternal();
373 template <typename IDMAP>
374 void RemoveCallbackAndStopIfDoomed(IDMAP* callbacks, int request_id);
376 const int64 version_id_;
377 int64 registration_id_;
378 GURL script_url_;
379 GURL scope_;
380 Status status_;
381 scoped_ptr<EmbeddedWorkerInstance> embedded_worker_;
382 scoped_ptr<ServiceWorkerCacheListener> cache_listener_;
383 std::vector<StatusCallback> start_callbacks_;
384 std::vector<StatusCallback> stop_callbacks_;
385 std::vector<base::Closure> status_change_callbacks_;
387 // Message callbacks. (Update HasInflightRequests() too when you update this
388 // list.)
389 IDMap<StatusCallback, IDMapOwnPointer> activate_callbacks_;
390 IDMap<StatusCallback, IDMapOwnPointer> install_callbacks_;
391 IDMap<FetchCallback, IDMapOwnPointer> fetch_callbacks_;
392 IDMap<StatusCallback, IDMapOwnPointer> sync_callbacks_;
393 IDMap<StatusCallback, IDMapOwnPointer> notification_click_callbacks_;
394 IDMap<StatusCallback, IDMapOwnPointer> push_callbacks_;
395 IDMap<StatusCallback, IDMapOwnPointer> geofencing_callbacks_;
396 IDMap<GetClientInfoCallback, IDMapOwnPointer> get_client_info_callbacks_;
397 IDMap<CrossOriginConnectCallback, IDMapOwnPointer>
398 cross_origin_connect_callbacks_;
400 std::set<const ServiceWorkerURLRequestJob*> streaming_url_request_jobs_;
402 ControlleeMap controllee_map_;
403 ControlleeByIDMap controllee_by_id_;
404 base::WeakPtr<ServiceWorkerContextCore> context_;
405 ObserverList<Listener> listeners_;
406 ServiceWorkerScriptCacheMap script_cache_map_;
407 base::OneShotTimer<ServiceWorkerVersion> stop_worker_timer_;
408 base::OneShotTimer<ServiceWorkerVersion> update_timer_;
409 bool is_doomed_;
410 std::vector<int> pending_skip_waiting_requests_;
411 bool skip_waiting_;
413 base::WeakPtrFactory<ServiceWorkerVersion> weak_factory_;
415 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion);
418 } // namespace content
420 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_