ServiceWorkerVersion: remove unused parameter in DispatchInstallEvent
[chromium-blink-merge.git] / content / browser / service_worker / service_worker_version.h
blob5c53d23f345cb41c8c9f67fb29424abfd0af2784
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 // 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 class ServiceWorkerVersionInfo;
53 struct NavigatorConnectClient;
54 struct PlatformNotificationData;
55 struct ServiceWorkerClientInfo;
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 const IPC::Message& message)> MessageCallback;
70 typedef base::Callback<void(ServiceWorkerStatusCode,
71 ServiceWorkerFetchEventResult,
72 const ServiceWorkerResponse&)> FetchCallback;
73 typedef base::Callback<void(ServiceWorkerStatusCode, bool)>
74 CrossOriginConnectCallback;
76 enum RunningStatus {
77 STOPPED = EmbeddedWorkerInstance::STOPPED,
78 STARTING = EmbeddedWorkerInstance::STARTING,
79 RUNNING = EmbeddedWorkerInstance::RUNNING,
80 STOPPING = EmbeddedWorkerInstance::STOPPING,
83 // Current version status; some of the status (e.g. INSTALLED and ACTIVATED)
84 // should be persisted unlike running status.
85 enum Status {
86 NEW, // The version is just created.
87 INSTALLING, // Install event is dispatched and being handled.
88 INSTALLED, // Install event is finished and is ready to be activated.
89 ACTIVATING, // Activate event is dispatched and being handled.
90 ACTIVATED, // Activation is finished and can run as activated.
91 REDUNDANT, // The version is no longer running as activated, due to
92 // unregistration or replace.
95 class Listener {
96 public:
97 virtual void OnWorkerStarted(ServiceWorkerVersion* version) {}
98 virtual void OnWorkerStopped(ServiceWorkerVersion* version) {}
99 virtual void OnVersionStateChanged(ServiceWorkerVersion* version) {}
100 virtual void OnErrorReported(ServiceWorkerVersion* version,
101 const base::string16& error_message,
102 int line_number,
103 int column_number,
104 const GURL& source_url) {}
105 virtual void OnReportConsoleMessage(ServiceWorkerVersion* version,
106 int source_identifier,
107 int message_level,
108 const base::string16& message,
109 int line_number,
110 const GURL& source_url) {}
111 // Fires when a version transitions from having a controllee to not.
112 virtual void OnNoControllees(ServiceWorkerVersion* version) {}
113 virtual void OnCachedMetadataUpdated(ServiceWorkerVersion* version) {}
115 protected:
116 virtual ~Listener() {}
119 ServiceWorkerVersion(
120 ServiceWorkerRegistration* registration,
121 const GURL& script_url,
122 int64 version_id,
123 base::WeakPtr<ServiceWorkerContextCore> context);
125 int64 version_id() const { return version_id_; }
126 int64 registration_id() const { return registration_id_; }
127 const GURL& script_url() const { return script_url_; }
128 const GURL& scope() const { return scope_; }
129 RunningStatus running_status() const {
130 return static_cast<RunningStatus>(embedded_worker_->status());
132 ServiceWorkerVersionInfo GetInfo();
133 Status status() const { return status_; }
135 // This sets the new status and also run status change callbacks
136 // if there're any (see RegisterStatusChangeCallback).
137 void SetStatus(Status status);
139 // Registers status change callback. (This is for one-off observation,
140 // the consumer needs to re-register if it wants to continue observing
141 // status changes)
142 void RegisterStatusChangeCallback(const base::Closure& callback);
144 // Starts an embedded worker for this version.
145 // This returns OK (success) if the worker is already running.
146 void StartWorker(const StatusCallback& callback);
148 // Starts an embedded worker for this version.
149 // |pause_after_download| notifies worker to pause after download finished
150 // which could be resumed by EmbeddedWorkerInstance::ResumeAfterDownload.
151 // This returns OK (success) if the worker is already running.
152 void StartWorker(bool pause_after_download,
153 const StatusCallback& callback);
155 // Stops an embedded worker for this version.
156 // This returns OK (success) if the worker is already stopped.
157 void StopWorker(const StatusCallback& callback);
159 // Schedules an update to be run 'soon'.
160 void ScheduleUpdate();
162 // If an update is scheduled but not yet started, this resets the timer
163 // delaying the start time by a 'small' amount.
164 void DeferScheduledUpdate();
166 // Starts an update now.
167 void StartUpdate();
169 // Sends a message event to the associated embedded worker.
170 void DispatchMessageEvent(
171 const base::string16& message,
172 const std::vector<TransferredMessagePort>& sent_message_ports,
173 const StatusCallback& callback);
175 // Sends install event to the associated embedded worker and asynchronously
176 // calls |callback| when it errors out or it gets a response from the worker
177 // to notify install completion.
179 // This must be called when the status() is NEW. Calling this changes
180 // the version's status to INSTALLING.
181 // Upon completion, the version's status will be changed to INSTALLED
182 // on success, or back to NEW on failure.
183 void DispatchInstallEvent(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 NavigatorConnectClient& 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 NavigatorConnectClient& client,
258 const base::string16& message,
259 const std::vector<TransferredMessagePort>& sent_message_ports,
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 // Sets the HttpResponseInfo used to load the main script.
296 // This HttpResponseInfo will be used for all responses sent back from the
297 // service worker, as the effective security of these responses is equivalent
298 // to that of the ServiceWorker.
299 void SetMainScriptHttpResponseInfo(const net::HttpResponseInfo& http_info);
300 const net::HttpResponseInfo* GetMainScriptHttpResponseInfo();
302 private:
303 class GetClientDocumentsCallback;
305 friend class base::RefCounted<ServiceWorkerVersion>;
306 friend class ServiceWorkerURLRequestJobTest;
307 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest,
308 ActivateWaitingVersion);
309 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, ScheduleStopWorker);
310 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, KeepAlive);
311 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest, ListenerAvailability);
312 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest,
313 TimeoutStartingWorker);
314 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest,
315 TimeoutWorkerInEvent);
316 friend class ServiceWorkerVersionBrowserTest;
318 typedef ServiceWorkerVersion self;
319 typedef std::map<ServiceWorkerProviderHost*, int> ControlleeMap;
320 typedef IDMap<ServiceWorkerProviderHost> ControlleeByIDMap;
322 ~ServiceWorkerVersion() override;
324 // EmbeddedWorkerInstance::Listener overrides:
325 void OnScriptLoaded() override;
326 void OnStarted() override;
327 void OnStopped(EmbeddedWorkerInstance::Status old_status) override;
328 void OnReportException(const base::string16& error_message,
329 int line_number,
330 int column_number,
331 const GURL& source_url) override;
332 void OnReportConsoleMessage(int source_identifier,
333 int message_level,
334 const base::string16& message,
335 int line_number,
336 const GURL& source_url) override;
337 bool OnMessageReceived(const IPC::Message& message) override;
339 void OnStartMessageSent(ServiceWorkerStatusCode status);
341 void DispatchInstallEventAfterStartWorker(const StatusCallback& callback);
342 void DispatchActivateEventAfterStartWorker(const StatusCallback& callback);
344 void DispatchMessageEventInternal(
345 const base::string16& message,
346 const std::vector<TransferredMessagePort>& sent_message_ports,
347 const StatusCallback& callback);
349 // Message handlers.
350 void OnGetClientDocuments(int request_id);
351 void OnActivateEventFinished(int request_id,
352 blink::WebServiceWorkerEventResult result);
353 void OnInstallEventFinished(int request_id,
354 blink::WebServiceWorkerEventResult result);
355 void OnFetchEventFinished(int request_id,
356 ServiceWorkerFetchEventResult result,
357 const ServiceWorkerResponse& response);
358 void OnSyncEventFinished(int request_id);
359 void OnNotificationClickEventFinished(int request_id);
360 void OnPushEventFinished(int request_id,
361 blink::WebServiceWorkerEventResult result);
362 void OnGeofencingEventFinished(int request_id);
363 void OnCrossOriginConnectEventFinished(int request_id,
364 bool accept_connection);
365 void OnOpenWindow(int request_id, const GURL& url);
366 void DidOpenWindow(int request_id,
367 int render_process_id,
368 int render_frame_id);
369 void OnOpenWindowFinished(int request_id,
370 int client_id,
371 const ServiceWorkerClientInfo& client_info);
373 void OnSetCachedMetadata(const GURL& url, const std::vector<char>& data);
374 void OnSetCachedMetadataFinished(int64 callback_id, int result);
375 void OnClearCachedMetadata(const GURL& url);
376 void OnClearCachedMetadataFinished(int64 callback_id, int result);
378 void OnPostMessageToDocument(
379 int client_id,
380 const base::string16& message,
381 const std::vector<TransferredMessagePort>& sent_message_ports);
382 void OnFocusClient(int request_id, int client_id);
383 void OnSkipWaiting(int request_id);
384 void OnClaimClients(int request_id);
385 void OnPongFromWorker();
387 void OnFocusClientFinished(int request_id,
388 int client_id,
389 const ServiceWorkerClientInfo& client);
391 void DidSkipWaiting(int request_id);
392 void DidClaimClients(int request_id, ServiceWorkerStatusCode status);
393 void DidGetClientInfo(int client_id,
394 scoped_refptr<GetClientDocumentsCallback> callback,
395 const ServiceWorkerClientInfo& info);
397 // The ping protocol is for terminating workers that are taking excessively
398 // long executing JavaScript (e.g., stuck in while(true) {}). Periodically a
399 // ping IPC is sent to the worker context and if we timeout waiting for a
400 // pong, the worker is terminated.
401 void PingWorker();
402 void StartPingWorker();
403 void SchedulePingWorker();
404 void OnPingTimeout();
406 // ScheduleStopWorker is for terminating idle workers. It schedules an attempt
407 // to stop: if the worker has no inflight requests when the attempt runs, the
408 // worker is terminated, otherwise the attempt is rescheduled.
409 void ScheduleStopWorker();
410 void StopWorkerIfIdle();
411 bool HasInflightRequests() const;
413 void DoomInternal();
415 template <typename IDMAP>
416 void RemoveCallbackAndStopIfDoomed(IDMAP* callbacks, int request_id);
418 const int64 version_id_;
419 int64 registration_id_;
420 GURL script_url_;
421 GURL scope_;
422 Status status_;
423 scoped_ptr<EmbeddedWorkerInstance> embedded_worker_;
424 scoped_ptr<ServiceWorkerCacheListener> cache_listener_;
425 std::vector<StatusCallback> start_callbacks_;
426 std::vector<StatusCallback> stop_callbacks_;
427 std::vector<base::Closure> status_change_callbacks_;
429 // Message callbacks. (Update HasInflightRequests() too when you update this
430 // list.)
431 IDMap<StatusCallback, IDMapOwnPointer> activate_callbacks_;
432 IDMap<StatusCallback, IDMapOwnPointer> install_callbacks_;
433 IDMap<FetchCallback, IDMapOwnPointer> fetch_callbacks_;
434 IDMap<StatusCallback, IDMapOwnPointer> sync_callbacks_;
435 IDMap<StatusCallback, IDMapOwnPointer> notification_click_callbacks_;
436 IDMap<StatusCallback, IDMapOwnPointer> push_callbacks_;
437 IDMap<StatusCallback, IDMapOwnPointer> geofencing_callbacks_;
438 IDMap<CrossOriginConnectCallback, IDMapOwnPointer>
439 cross_origin_connect_callbacks_;
441 std::set<const ServiceWorkerURLRequestJob*> streaming_url_request_jobs_;
443 ControlleeMap controllee_map_;
444 ControlleeByIDMap controllee_by_id_;
445 // Will be null while shutting down.
446 base::WeakPtr<ServiceWorkerContextCore> context_;
447 ObserverList<Listener> listeners_;
448 ServiceWorkerScriptCacheMap script_cache_map_;
449 base::OneShotTimer<ServiceWorkerVersion> stop_worker_timer_;
450 base::OneShotTimer<ServiceWorkerVersion> update_timer_;
451 base::OneShotTimer<ServiceWorkerVersion> ping_worker_timer_;
452 bool ping_timed_out_;
453 bool is_doomed_;
454 std::vector<int> pending_skip_waiting_requests_;
455 bool skip_waiting_;
456 scoped_ptr<net::HttpResponseInfo> main_script_http_info_;
458 base::WeakPtrFactory<ServiceWorkerVersion> weak_factory_;
460 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion);
463 } // namespace content
465 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_