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_
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.
38 struct WebCircularGeofencingRegion
;
42 class HttpResponseInfo
;
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
63 class CONTENT_EXPORT ServiceWorkerVersion
64 : NON_EXPORTED_BASE(public base::RefCounted
<ServiceWorkerVersion
>),
65 public EmbeddedWorkerInstance::Listener
{
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
;
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.
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.
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
,
104 const GURL
& source_url
) {}
105 virtual void OnReportConsoleMessage(ServiceWorkerVersion
* version
,
106 int source_identifier
,
108 const base::string16
& message
,
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
) {}
116 virtual ~Listener() {}
119 ServiceWorkerVersion(
120 ServiceWorkerRegistration
* registration
,
121 const GURL
& script_url
,
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
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.
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.
178 // |active_version_id| must be a valid positive ID
179 // if there's an activated (previous) version running.
181 // This must be called when the status() is NEW. Calling this changes
182 // the version's status to INSTALLING.
183 // Upon completion, the version's status will be changed to INSTALLED
184 // on success, or back to NEW on failure.
185 void DispatchInstallEvent(int active_version_id
,
186 const StatusCallback
& callback
);
188 // Sends activate event to the associated embedded worker and asynchronously
189 // calls |callback| when it errors out or it gets a response from the worker
190 // to notify activation completion.
192 // This must be called when the status() is INSTALLED. Calling this changes
193 // the version's status to ACTIVATING.
194 // Upon completion, the version's status will be changed to ACTIVATED
195 // on success, or back to INSTALLED on failure.
196 void DispatchActivateEvent(const StatusCallback
& callback
);
198 // Sends fetch event to the associated embedded worker and calls
199 // |callback| with the response from the worker.
201 // This must be called when the status() is ACTIVATED. Calling this in other
202 // statuses will result in an error SERVICE_WORKER_ERROR_FAILED.
203 void DispatchFetchEvent(const ServiceWorkerFetchRequest
& request
,
204 const base::Closure
& prepare_callback
,
205 const FetchCallback
& fetch_callback
);
207 // Sends sync event to the associated embedded worker and asynchronously calls
208 // |callback| when it errors out or it gets a response from the worker to
209 // notify completion.
211 // This must be called when the status() is ACTIVATED.
212 void DispatchSyncEvent(const StatusCallback
& callback
);
214 // Sends notificationclick event to the associated embedded worker and
215 // asynchronously calls |callback| when it errors out or it gets a response
216 // from the worker to notify completion.
218 // This must be called when the status() is ACTIVATED.
219 void DispatchNotificationClickEvent(
220 const StatusCallback
& callback
,
221 const std::string
& notification_id
,
222 const PlatformNotificationData
& notification_data
);
224 // Sends push event to the associated embedded worker and asynchronously calls
225 // |callback| when it errors out or it gets a response from the worker to
226 // notify completion.
228 // This must be called when the status() is ACTIVATED.
229 void DispatchPushEvent(const StatusCallback
& callback
,
230 const std::string
& data
);
232 // Sends geofencing event to the associated embedded worker and asynchronously
233 // calls |callback| when it errors out or it gets a response from the worker
234 // to notify completion.
236 // This must be called when the status() is ACTIVATED.
237 void DispatchGeofencingEvent(
238 const StatusCallback
& callback
,
239 blink::WebGeofencingEventType event_type
,
240 const std::string
& region_id
,
241 const blink::WebCircularGeofencingRegion
& region
);
243 // Sends a cross origin connect event to the associated embedded worker and
244 // asynchronously calls |callback| with the response from the worker.
246 // This must be called when the status() is ACTIVATED.
247 void DispatchCrossOriginConnectEvent(
248 const CrossOriginConnectCallback
& callback
,
249 const NavigatorConnectClient
& client
);
251 // Sends a cross origin message event to the associated embedded worker and
252 // asynchronously calls |callback| when the message was sent (or failed to
254 // It is the responsibility of the code calling this method to make sure that
255 // any transferred message ports are put on hold while potentially a process
256 // for the service worker is spun up.
258 // This must be called when the status() is ACTIVATED.
259 void DispatchCrossOriginMessageEvent(
260 const NavigatorConnectClient
& client
,
261 const base::string16
& message
,
262 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
263 const StatusCallback
& callback
);
265 // Adds and removes |provider_host| as a controllee of this ServiceWorker.
266 // A potential controllee is a host having the version as its .installing
267 // or .waiting version.
268 void AddControllee(ServiceWorkerProviderHost
* provider_host
);
269 void RemoveControllee(ServiceWorkerProviderHost
* provider_host
);
271 // Returns if it has controllee.
272 bool HasControllee() const { return !controllee_map_
.empty(); }
274 // Adds and removes |request_job| as a dependent job not to stop the
275 // ServiceWorker while |request_job| is reading the stream of the fetch event
276 // response from the ServiceWorker.
277 void AddStreamingURLRequestJob(const ServiceWorkerURLRequestJob
* request_job
);
278 void RemoveStreamingURLRequestJob(
279 const ServiceWorkerURLRequestJob
* request_job
);
281 // Adds and removes Listeners.
282 void AddListener(Listener
* listener
);
283 void RemoveListener(Listener
* listener
);
285 ServiceWorkerScriptCacheMap
* script_cache_map() { return &script_cache_map_
; }
286 EmbeddedWorkerInstance
* embedded_worker() { return embedded_worker_
.get(); }
288 // Dooms this version to have REDUNDANT status and its resources deleted. If
289 // the version is controlling a page, these changes will happen when the
290 // version no longer controls any pages.
292 bool is_doomed() const { return is_doomed_
; }
294 bool skip_waiting() const { return skip_waiting_
; }
296 void SetDevToolsAttached(bool attached
);
298 // Sets the HttpResponseInfo used to load the main script.
299 // This HttpResponseInfo will be used for all responses sent back from the
300 // service worker, as the effective security of these responses is equivalent
301 // to that of the ServiceWorker.
302 void SetMainScriptHttpResponseInfo(const net::HttpResponseInfo
& http_info
);
303 const net::HttpResponseInfo
* GetMainScriptHttpResponseInfo();
306 class GetClientDocumentsCallback
;
308 friend class base::RefCounted
<ServiceWorkerVersion
>;
309 friend class ServiceWorkerURLRequestJobTest
;
310 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest
,
311 ActivateWaitingVersion
);
312 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, ScheduleStopWorker
);
313 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, KeepAlive
);
314 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionTest
, ListenerAvailability
);
315 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest
,
316 TimeoutStartingWorker
);
317 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerVersionBrowserTest
,
318 TimeoutWorkerInEvent
);
319 friend class ServiceWorkerVersionBrowserTest
;
321 typedef ServiceWorkerVersion self
;
322 typedef std::map
<ServiceWorkerProviderHost
*, int> ControlleeMap
;
323 typedef IDMap
<ServiceWorkerProviderHost
> ControlleeByIDMap
;
325 ~ServiceWorkerVersion() override
;
327 // EmbeddedWorkerInstance::Listener overrides:
328 void OnScriptLoaded() override
;
329 void OnStarted() override
;
330 void OnStopped(EmbeddedWorkerInstance::Status old_status
) override
;
331 void OnReportException(const base::string16
& error_message
,
334 const GURL
& source_url
) override
;
335 void OnReportConsoleMessage(int source_identifier
,
337 const base::string16
& message
,
339 const GURL
& source_url
) override
;
340 bool OnMessageReceived(const IPC::Message
& message
) override
;
342 void OnStartMessageSent(ServiceWorkerStatusCode status
);
344 void DispatchInstallEventAfterStartWorker(int active_version_id
,
345 const StatusCallback
& callback
);
346 void DispatchActivateEventAfterStartWorker(const StatusCallback
& callback
);
348 void DispatchMessageEventInternal(
349 const base::string16
& message
,
350 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
351 const StatusCallback
& callback
);
354 void OnGetClientDocuments(int request_id
);
355 void OnActivateEventFinished(int request_id
,
356 blink::WebServiceWorkerEventResult result
);
357 void OnInstallEventFinished(int request_id
,
358 blink::WebServiceWorkerEventResult result
);
359 void OnFetchEventFinished(int request_id
,
360 ServiceWorkerFetchEventResult result
,
361 const ServiceWorkerResponse
& response
);
362 void OnSyncEventFinished(int request_id
);
363 void OnNotificationClickEventFinished(int request_id
);
364 void OnPushEventFinished(int request_id
,
365 blink::WebServiceWorkerEventResult result
);
366 void OnGeofencingEventFinished(int request_id
);
367 void OnCrossOriginConnectEventFinished(int request_id
,
368 bool accept_connection
);
369 void OnOpenWindow(int request_id
, const GURL
& url
);
370 void DidOpenWindow(int request_id
,
371 int render_process_id
,
372 int render_frame_id
);
373 void OnOpenWindowFinished(int request_id
,
375 const ServiceWorkerClientInfo
& client_info
);
377 void OnSetCachedMetadata(const GURL
& url
, const std::vector
<char>& data
);
378 void OnSetCachedMetadataFinished(int64 callback_id
, int result
);
379 void OnClearCachedMetadata(const GURL
& url
);
380 void OnClearCachedMetadataFinished(int64 callback_id
, int result
);
382 void OnPostMessageToDocument(
384 const base::string16
& message
,
385 const std::vector
<TransferredMessagePort
>& sent_message_ports
);
386 void OnFocusClient(int request_id
, int client_id
);
387 void OnSkipWaiting(int request_id
);
388 void OnClaimClients(int request_id
);
389 void OnPongFromWorker();
391 void OnFocusClientFinished(int request_id
,
393 const ServiceWorkerClientInfo
& client
);
395 void DidSkipWaiting(int request_id
);
396 void DidClaimClients(int request_id
, ServiceWorkerStatusCode status
);
397 void DidGetClientInfo(int client_id
,
398 scoped_refptr
<GetClientDocumentsCallback
> callback
,
399 const ServiceWorkerClientInfo
& info
);
401 // The ping protocol is for terminating workers that are taking excessively
402 // long executing JavaScript (e.g., stuck in while(true) {}). Periodically a
403 // ping IPC is sent to the worker context and if we timeout waiting for a
404 // pong, the worker is terminated.
406 void StartPingWorker();
407 void SchedulePingWorker();
408 void OnPingTimeout();
410 // ScheduleStopWorker is for terminating idle workers. It schedules an attempt
411 // to stop: if the worker has no inflight requests when the attempt runs, the
412 // worker is terminated, otherwise the attempt is rescheduled.
413 void ScheduleStopWorker();
414 void StopWorkerIfIdle();
415 bool HasInflightRequests() const;
419 template <typename IDMAP
>
420 void RemoveCallbackAndStopIfDoomed(IDMAP
* callbacks
, int request_id
);
422 const int64 version_id_
;
423 int64 registration_id_
;
427 scoped_ptr
<EmbeddedWorkerInstance
> embedded_worker_
;
428 scoped_ptr
<ServiceWorkerCacheListener
> cache_listener_
;
429 std::vector
<StatusCallback
> start_callbacks_
;
430 std::vector
<StatusCallback
> stop_callbacks_
;
431 std::vector
<base::Closure
> status_change_callbacks_
;
433 // Message callbacks. (Update HasInflightRequests() too when you update this
435 IDMap
<StatusCallback
, IDMapOwnPointer
> activate_callbacks_
;
436 IDMap
<StatusCallback
, IDMapOwnPointer
> install_callbacks_
;
437 IDMap
<FetchCallback
, IDMapOwnPointer
> fetch_callbacks_
;
438 IDMap
<StatusCallback
, IDMapOwnPointer
> sync_callbacks_
;
439 IDMap
<StatusCallback
, IDMapOwnPointer
> notification_click_callbacks_
;
440 IDMap
<StatusCallback
, IDMapOwnPointer
> push_callbacks_
;
441 IDMap
<StatusCallback
, IDMapOwnPointer
> geofencing_callbacks_
;
442 IDMap
<CrossOriginConnectCallback
, IDMapOwnPointer
>
443 cross_origin_connect_callbacks_
;
445 std::set
<const ServiceWorkerURLRequestJob
*> streaming_url_request_jobs_
;
447 ControlleeMap controllee_map_
;
448 ControlleeByIDMap controllee_by_id_
;
449 // Will be null while shutting down.
450 base::WeakPtr
<ServiceWorkerContextCore
> context_
;
451 ObserverList
<Listener
> listeners_
;
452 ServiceWorkerScriptCacheMap script_cache_map_
;
453 base::OneShotTimer
<ServiceWorkerVersion
> stop_worker_timer_
;
454 base::OneShotTimer
<ServiceWorkerVersion
> update_timer_
;
455 base::OneShotTimer
<ServiceWorkerVersion
> ping_worker_timer_
;
456 bool ping_timed_out_
;
458 std::vector
<int> pending_skip_waiting_requests_
;
460 scoped_ptr
<net::HttpResponseInfo
> main_script_http_info_
;
462 base::WeakPtrFactory
<ServiceWorkerVersion
> weak_factory_
;
464 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersion
);
467 } // namespace content
469 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_VERSION_H_