Delete unused downloads page asset.
[chromium-blink-merge.git] / net / socket / client_socket_pool_base.h
blob601ab6db1910a0ed068d798fdd9f7db568c10c8a
1 // Copyright (c) 2012 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.
4 //
5 // A ClientSocketPoolBase is used to restrict the number of sockets open at
6 // a time. It also maintains a list of idle persistent sockets for reuse.
7 // Subclasses of ClientSocketPool should compose ClientSocketPoolBase to handle
8 // the core logic of (1) restricting the number of active (connected or
9 // connecting) sockets per "group" (generally speaking, the hostname), (2)
10 // maintaining a per-group list of idle, persistent sockets for reuse, and (3)
11 // limiting the total number of active sockets in the system.
13 // ClientSocketPoolBase abstracts socket connection details behind ConnectJob,
14 // ConnectJobFactory, and SocketParams. When a socket "slot" becomes available,
15 // the ClientSocketPoolBase will ask the ConnectJobFactory to create a
16 // ConnectJob with a SocketParams. Subclasses of ClientSocketPool should
17 // implement their socket specific connection by subclassing ConnectJob and
18 // implementing ConnectJob::ConnectInternal(). They can control the parameters
19 // passed to each new ConnectJob instance via their ConnectJobFactory subclass
20 // and templated SocketParams parameter.
22 #ifndef NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_
23 #define NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_
25 #include <cstddef>
26 #include <deque>
27 #include <list>
28 #include <map>
29 #include <set>
30 #include <string>
31 #include <vector>
33 #include "base/basictypes.h"
34 #include "base/memory/ref_counted.h"
35 #include "base/memory/scoped_ptr.h"
36 #include "base/memory/weak_ptr.h"
37 #include "base/time/time.h"
38 #include "base/timer/timer.h"
39 #include "net/base/address_list.h"
40 #include "net/base/completion_callback.h"
41 #include "net/base/load_states.h"
42 #include "net/base/load_timing_info.h"
43 #include "net/base/net_errors.h"
44 #include "net/base/net_export.h"
45 #include "net/base/network_change_notifier.h"
46 #include "net/base/priority_queue.h"
47 #include "net/base/request_priority.h"
48 #include "net/log/net_log.h"
49 #include "net/socket/client_socket_handle.h"
50 #include "net/socket/client_socket_pool.h"
51 #include "net/socket/stream_socket.h"
53 namespace net {
55 class ClientSocketHandle;
57 // ConnectJob provides an abstract interface for "connecting" a socket.
58 // The connection may involve host resolution, tcp connection, ssl connection,
59 // etc.
60 class NET_EXPORT_PRIVATE ConnectJob {
61 public:
62 class NET_EXPORT_PRIVATE Delegate {
63 public:
64 Delegate() {}
65 virtual ~Delegate() {}
67 // Alerts the delegate that the connection completed. |job| must
68 // be destroyed by the delegate. A scoped_ptr<> isn't used because
69 // the caller of this function doesn't own |job|.
70 virtual void OnConnectJobComplete(int result,
71 ConnectJob* job) = 0;
73 private:
74 DISALLOW_COPY_AND_ASSIGN(Delegate);
77 // A |timeout_duration| of 0 corresponds to no timeout.
78 ConnectJob(const std::string& group_name,
79 base::TimeDelta timeout_duration,
80 RequestPriority priority,
81 Delegate* delegate,
82 const BoundNetLog& net_log);
83 virtual ~ConnectJob();
85 // Accessors
86 const std::string& group_name() const { return group_name_; }
87 const BoundNetLog& net_log() { return net_log_; }
89 // Releases ownership of the underlying socket to the caller.
90 // Returns the released socket, or NULL if there was a connection
91 // error.
92 scoped_ptr<StreamSocket> PassSocket();
94 // Begins connecting the socket. Returns OK on success, ERR_IO_PENDING if it
95 // cannot complete synchronously without blocking, or another net error code
96 // on error. In asynchronous completion, the ConnectJob will notify
97 // |delegate_| via OnConnectJobComplete. In both asynchronous and synchronous
98 // completion, ReleaseSocket() can be called to acquire the connected socket
99 // if it succeeded.
100 int Connect();
102 virtual LoadState GetLoadState() const = 0;
104 // If Connect returns an error (or OnConnectJobComplete reports an error
105 // result) this method will be called, allowing the pool to add
106 // additional error state to the ClientSocketHandle (post late-binding).
107 virtual void GetAdditionalErrorState(ClientSocketHandle* handle) {}
109 const LoadTimingInfo::ConnectTiming& connect_timing() const {
110 return connect_timing_;
113 const BoundNetLog& net_log() const { return net_log_; }
115 protected:
116 RequestPriority priority() const { return priority_; }
117 void SetSocket(scoped_ptr<StreamSocket> socket);
118 StreamSocket* socket() { return socket_.get(); }
119 void NotifyDelegateOfCompletion(int rv);
120 void ResetTimer(base::TimeDelta remainingTime);
122 // Connection establishment timing information.
123 LoadTimingInfo::ConnectTiming connect_timing_;
125 private:
126 virtual int ConnectInternal() = 0;
128 void LogConnectStart();
129 void LogConnectCompletion(int net_error);
131 // Alerts the delegate that the ConnectJob has timed out.
132 void OnTimeout();
134 const std::string group_name_;
135 const base::TimeDelta timeout_duration_;
136 // TODO(akalin): Support reprioritization.
137 const RequestPriority priority_;
138 // Timer to abort jobs that take too long.
139 base::OneShotTimer<ConnectJob> timer_;
140 Delegate* delegate_;
141 scoped_ptr<StreamSocket> socket_;
142 BoundNetLog net_log_;
143 // A ConnectJob is idle until Connect() has been called.
144 bool idle_;
146 DISALLOW_COPY_AND_ASSIGN(ConnectJob);
149 namespace internal {
151 // ClientSocketPoolBaseHelper is an internal class that implements almost all
152 // the functionality from ClientSocketPoolBase without using templates.
153 // ClientSocketPoolBase adds templated definitions built on top of
154 // ClientSocketPoolBaseHelper. This class is not for external use, please use
155 // ClientSocketPoolBase instead.
156 class NET_EXPORT_PRIVATE ClientSocketPoolBaseHelper
157 : public ConnectJob::Delegate,
158 public NetworkChangeNotifier::IPAddressObserver {
159 public:
160 typedef uint32 Flags;
162 // Used to specify specific behavior for the ClientSocketPool.
163 enum Flag {
164 NORMAL = 0, // Normal behavior.
165 NO_IDLE_SOCKETS = 0x1, // Do not return an idle socket. Create a new one.
168 class NET_EXPORT_PRIVATE Request {
169 public:
170 Request(ClientSocketHandle* handle,
171 const CompletionCallback& callback,
172 RequestPriority priority,
173 bool ignore_limits,
174 Flags flags,
175 const BoundNetLog& net_log);
177 virtual ~Request();
179 ClientSocketHandle* handle() const { return handle_; }
180 const CompletionCallback& callback() const { return callback_; }
181 RequestPriority priority() const { return priority_; }
182 bool ignore_limits() const { return ignore_limits_; }
183 Flags flags() const { return flags_; }
184 const BoundNetLog& net_log() const { return net_log_; }
186 // TODO(eroman): Temporary until crbug.com/467797 is solved.
187 void CrashIfInvalid() const;
189 private:
190 // TODO(eroman): Temporary until crbug.com/467797 is solved.
191 enum Liveness {
192 ALIVE = 0xCA11AB13,
193 DEAD = 0xDEADBEEF,
196 ClientSocketHandle* const handle_;
197 const CompletionCallback callback_;
198 // TODO(akalin): Support reprioritization.
199 const RequestPriority priority_;
200 const bool ignore_limits_;
201 const Flags flags_;
202 const BoundNetLog net_log_;
204 // TODO(eroman): Temporary until crbug.com/467797 is solved.
205 Liveness liveness_ = ALIVE;
207 DISALLOW_COPY_AND_ASSIGN(Request);
210 class ConnectJobFactory {
211 public:
212 ConnectJobFactory() {}
213 virtual ~ConnectJobFactory() {}
215 virtual scoped_ptr<ConnectJob> NewConnectJob(
216 const std::string& group_name,
217 const Request& request,
218 ConnectJob::Delegate* delegate) const = 0;
220 virtual base::TimeDelta ConnectionTimeout() const = 0;
222 private:
223 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory);
226 ClientSocketPoolBaseHelper(
227 HigherLayeredPool* pool,
228 int max_sockets,
229 int max_sockets_per_group,
230 base::TimeDelta unused_idle_socket_timeout,
231 base::TimeDelta used_idle_socket_timeout,
232 ConnectJobFactory* connect_job_factory);
234 ~ClientSocketPoolBaseHelper() override;
236 // Adds a lower layered pool to |this|, and adds |this| as a higher layered
237 // pool on top of |lower_pool|.
238 void AddLowerLayeredPool(LowerLayeredPool* lower_pool);
240 // See LowerLayeredPool::IsStalled for documentation on this function.
241 bool IsStalled() const;
243 // See LowerLayeredPool for documentation on these functions. It is expected
244 // in the destructor that no higher layer pools remain.
245 void AddHigherLayeredPool(HigherLayeredPool* higher_pool);
246 void RemoveHigherLayeredPool(HigherLayeredPool* higher_pool);
248 // See ClientSocketPool::RequestSocket for documentation on this function.
249 int RequestSocket(const std::string& group_name,
250 scoped_ptr<const Request> request);
252 // See ClientSocketPool::RequestSocket for documentation on this function.
253 void RequestSockets(const std::string& group_name,
254 const Request& request,
255 int num_sockets);
257 // See ClientSocketPool::CancelRequest for documentation on this function.
258 void CancelRequest(const std::string& group_name,
259 ClientSocketHandle* handle);
261 // See ClientSocketPool::ReleaseSocket for documentation on this function.
262 void ReleaseSocket(const std::string& group_name,
263 scoped_ptr<StreamSocket> socket,
264 int id);
266 // See ClientSocketPool::FlushWithError for documentation on this function.
267 void FlushWithError(int error);
269 // See ClientSocketPool::CloseIdleSockets for documentation on this function.
270 void CloseIdleSockets();
272 // See ClientSocketPool::IdleSocketCount() for documentation on this function.
273 int idle_socket_count() const {
274 return idle_socket_count_;
277 // See ClientSocketPool::IdleSocketCountInGroup() for documentation on this
278 // function.
279 int IdleSocketCountInGroup(const std::string& group_name) const;
281 // See ClientSocketPool::GetLoadState() for documentation on this function.
282 LoadState GetLoadState(const std::string& group_name,
283 const ClientSocketHandle* handle) const;
285 base::TimeDelta ConnectRetryInterval() const {
286 // TODO(mbelshe): Make this tuned dynamically based on measured RTT.
287 // For now, just use the max retry interval.
288 return base::TimeDelta::FromMilliseconds(
289 ClientSocketPool::kMaxConnectRetryIntervalMs);
292 int NumUnassignedConnectJobsInGroup(const std::string& group_name) const {
293 return group_map_.find(group_name)->second->unassigned_job_count();
296 int NumConnectJobsInGroup(const std::string& group_name) const {
297 return group_map_.find(group_name)->second->jobs().size();
300 int NumActiveSocketsInGroup(const std::string& group_name) const {
301 return group_map_.find(group_name)->second->active_socket_count();
304 bool HasGroup(const std::string& group_name) const;
306 // Called to enable/disable cleaning up idle sockets. When enabled,
307 // idle sockets that have been around for longer than a period defined
308 // by kCleanupInterval are cleaned up using a timer. Otherwise they are
309 // closed next time client makes a request. This may reduce network
310 // activity and power consumption.
311 static bool cleanup_timer_enabled();
312 static bool set_cleanup_timer_enabled(bool enabled);
314 // Closes all idle sockets if |force| is true. Else, only closes idle
315 // sockets that timed out or can't be reused. Made public for testing.
316 void CleanupIdleSockets(bool force);
318 // Closes one idle socket. Picks the first one encountered.
319 // TODO(willchan): Consider a better algorithm for doing this. Perhaps we
320 // should keep an ordered list of idle sockets, and close them in order.
321 // Requires maintaining more state. It's not clear if it's worth it since
322 // I'm not sure if we hit this situation often.
323 bool CloseOneIdleSocket();
325 // Checks higher layered pools to see if they can close an idle connection.
326 bool CloseOneIdleConnectionInHigherLayeredPool();
328 // See ClientSocketPool::GetInfoAsValue for documentation on this function.
329 scoped_ptr<base::DictionaryValue> GetInfoAsValue(
330 const std::string& name,
331 const std::string& type) const;
333 base::TimeDelta ConnectionTimeout() const {
334 return connect_job_factory_->ConnectionTimeout();
337 static bool connect_backup_jobs_enabled();
338 static bool set_connect_backup_jobs_enabled(bool enabled);
340 void EnableConnectBackupJobs();
342 // ConnectJob::Delegate methods:
343 void OnConnectJobComplete(int result, ConnectJob* job) override;
345 // NetworkChangeNotifier::IPAddressObserver methods:
346 void OnIPAddressChanged() override;
348 private:
349 // Entry for a persistent socket which became idle at time |start_time|.
350 struct IdleSocket {
351 IdleSocket() : socket(NULL) {}
353 // An idle socket can't be used if it is disconnected or has been used
354 // before and has received data unexpectedly (hence no longer idle). The
355 // unread data would be mistaken for the beginning of the next response if
356 // we were to use the socket for a new request.
358 // Note that a socket that has never been used before (like a preconnected
359 // socket) may be used even with unread data. This may be, e.g., a SPDY
360 // SETTINGS frame.
361 bool IsUsable() const;
363 // An idle socket should be removed if it can't be reused, or has been idle
364 // for too long. |now| is the current time value (TimeTicks::Now()).
365 // |timeout| is the length of time to wait before timing out an idle socket.
366 bool ShouldCleanup(base::TimeTicks now, base::TimeDelta timeout) const;
368 StreamSocket* socket;
369 base::TimeTicks start_time;
372 typedef PriorityQueue<const Request*> RequestQueue;
373 typedef std::map<const ClientSocketHandle*, const Request*> RequestMap;
375 // A Group is allocated per group_name when there are idle sockets or pending
376 // requests. Otherwise, the Group object is removed from the map.
377 // |active_socket_count| tracks the number of sockets held by clients.
378 class Group {
379 public:
380 Group();
381 ~Group();
383 bool IsEmpty() const {
384 return active_socket_count_ == 0 && idle_sockets_.empty() &&
385 jobs_.empty() && pending_requests_.empty();
388 bool HasAvailableSocketSlot(int max_sockets_per_group) const {
389 return NumActiveSocketSlots() < max_sockets_per_group;
392 int NumActiveSocketSlots() const {
393 return active_socket_count_ + static_cast<int>(jobs_.size()) +
394 static_cast<int>(idle_sockets_.size());
397 // Returns true if the group could make use of an additional socket slot, if
398 // it were given one.
399 bool CanUseAdditionalSocketSlot(int max_sockets_per_group) const {
400 return HasAvailableSocketSlot(max_sockets_per_group) &&
401 pending_requests_.size() > jobs_.size();
404 // Returns the priority of the top of the pending request queue
405 // (which may be less than the maximum priority over the entire
406 // queue, due to how we prioritize requests with |ignore_limits|
407 // set over others).
408 RequestPriority TopPendingPriority() const {
409 // NOTE: FirstMax().value()->priority() is not the same as
410 // FirstMax().priority()!
411 return pending_requests_.FirstMax().value()->priority();
414 // Set a timer to create a backup job if it takes too long to
415 // create one and if a timer isn't already running.
416 void StartBackupJobTimer(const std::string& group_name,
417 ClientSocketPoolBaseHelper* pool);
419 bool BackupJobTimerIsRunning() const;
421 // If there's a ConnectJob that's never been assigned to Request,
422 // decrements |unassigned_job_count_| and returns true.
423 // Otherwise, returns false.
424 bool TryToUseUnassignedConnectJob();
426 void AddJob(scoped_ptr<ConnectJob> job, bool is_preconnect);
427 // Remove |job| from this group, which must already own |job|.
428 void RemoveJob(ConnectJob* job);
429 void RemoveAllJobs();
431 bool has_pending_requests() const {
432 return !pending_requests_.empty();
435 size_t pending_request_count() const {
436 return pending_requests_.size();
439 // Gets (but does not remove) the next pending request. Returns
440 // NULL if there are no pending requests.
441 const Request* GetNextPendingRequest() const;
443 // Returns true if there is a connect job for |handle|.
444 bool HasConnectJobForHandle(const ClientSocketHandle* handle) const;
446 // Inserts the request into the queue based on priority
447 // order. Older requests are prioritized over requests of equal
448 // priority.
449 void InsertPendingRequest(scoped_ptr<const Request> request);
451 // Gets and removes the next pending request. Returns NULL if
452 // there are no pending requests.
453 scoped_ptr<const Request> PopNextPendingRequest();
455 // Finds the pending request for |handle| and removes it. Returns
456 // the removed pending request, or NULL if there was none.
457 scoped_ptr<const Request> FindAndRemovePendingRequest(
458 ClientSocketHandle* handle);
460 void IncrementActiveSocketCount() { active_socket_count_++; }
461 void DecrementActiveSocketCount() { active_socket_count_--; }
463 int unassigned_job_count() const { return unassigned_job_count_; }
464 const std::list<ConnectJob*>& jobs() const { return jobs_; }
465 const std::list<IdleSocket>& idle_sockets() const { return idle_sockets_; }
466 int active_socket_count() const { return active_socket_count_; }
467 std::list<IdleSocket>* mutable_idle_sockets() { return &idle_sockets_; }
469 private:
470 // Returns the iterator's pending request after removing it from
471 // the queue.
472 scoped_ptr<const Request> RemovePendingRequest(
473 const RequestQueue::Pointer& pointer);
475 // Called when the backup socket timer fires.
476 void OnBackupJobTimerFired(
477 std::string group_name,
478 ClientSocketPoolBaseHelper* pool);
480 // Checks that |unassigned_job_count_| does not execeed the number of
481 // ConnectJobs.
482 void SanityCheck();
484 // Total number of ConnectJobs that have never been assigned to a Request.
485 // Since jobs use late binding to requests, which ConnectJobs have or have
486 // not been assigned to a request are not tracked. This is incremented on
487 // preconnect and decremented when a preconnect is assigned, or when there
488 // are fewer than |unassigned_job_count_| ConnectJobs. Not incremented
489 // when a request is cancelled.
490 size_t unassigned_job_count_;
492 std::list<IdleSocket> idle_sockets_;
493 std::list<ConnectJob*> jobs_;
494 RequestQueue pending_requests_;
495 int active_socket_count_; // number of active sockets used by clients
496 // A timer for when to start the backup job.
497 base::OneShotTimer<Group> backup_job_timer_;
500 typedef std::map<std::string, Group*> GroupMap;
502 typedef std::set<ConnectJob*> ConnectJobSet;
504 struct CallbackResultPair {
505 CallbackResultPair();
506 CallbackResultPair(const CompletionCallback& callback_in, int result_in);
507 ~CallbackResultPair();
509 CompletionCallback callback;
510 int result;
513 typedef std::map<const ClientSocketHandle*, CallbackResultPair>
514 PendingCallbackMap;
516 Group* GetOrCreateGroup(const std::string& group_name);
517 void RemoveGroup(const std::string& group_name);
518 void RemoveGroup(GroupMap::iterator it);
520 // Called when the number of idle sockets changes.
521 void IncrementIdleCount();
522 void DecrementIdleCount();
524 // Start cleanup timer for idle sockets.
525 void StartIdleSocketTimer();
527 // Scans the group map for groups which have an available socket slot and
528 // at least one pending request. Returns true if any groups are stalled, and
529 // if so (and if both |group| and |group_name| are not NULL), fills |group|
530 // and |group_name| with data of the stalled group having highest priority.
531 bool FindTopStalledGroup(Group** group, std::string* group_name) const;
533 // Called when timer_ fires. This method scans the idle sockets removing
534 // sockets that timed out or can't be reused.
535 void OnCleanupTimerFired() {
536 CleanupIdleSockets(false);
539 // Removes |job| from |group|, which must already own |job|.
540 void RemoveConnectJob(ConnectJob* job, Group* group);
542 // Tries to see if we can handle any more requests for |group|.
543 void OnAvailableSocketSlot(const std::string& group_name, Group* group);
545 // Process a pending socket request for a group.
546 void ProcessPendingRequest(const std::string& group_name, Group* group);
548 // Assigns |socket| to |handle| and updates |group|'s counters appropriately.
549 void HandOutSocket(scoped_ptr<StreamSocket> socket,
550 ClientSocketHandle::SocketReuseType reuse_type,
551 const LoadTimingInfo::ConnectTiming& connect_timing,
552 ClientSocketHandle* handle,
553 base::TimeDelta time_idle,
554 Group* group,
555 const BoundNetLog& net_log);
557 // Adds |socket| to the list of idle sockets for |group|.
558 void AddIdleSocket(scoped_ptr<StreamSocket> socket, Group* group);
560 // Iterates through |group_map_|, canceling all ConnectJobs and deleting
561 // groups if they are no longer needed.
562 void CancelAllConnectJobs();
564 // Iterates through |group_map_|, posting |error| callbacks for all
565 // requests, and then deleting groups if they are no longer needed.
566 void CancelAllRequestsWithError(int error);
568 // Returns true if we can't create any more sockets due to the total limit.
569 bool ReachedMaxSocketsLimit() const;
571 // This is the internal implementation of RequestSocket(). It differs in that
572 // it does not handle logging into NetLog of the queueing status of
573 // |request|.
574 int RequestSocketInternal(const std::string& group_name,
575 const Request& request);
577 // Assigns an idle socket for the group to the request.
578 // Returns |true| if an idle socket is available, false otherwise.
579 bool AssignIdleSocketToRequest(const Request& request, Group* group);
581 static void LogBoundConnectJobToRequest(
582 const NetLog::Source& connect_job_source, const Request& request);
584 // Same as CloseOneIdleSocket() except it won't close an idle socket in
585 // |group|. If |group| is NULL, it is ignored. Returns true if it closed a
586 // socket.
587 bool CloseOneIdleSocketExceptInGroup(const Group* group);
589 // Checks if there are stalled socket groups that should be notified
590 // for possible wakeup.
591 void CheckForStalledSocketGroups();
593 // Posts a task to call InvokeUserCallback() on the next iteration through the
594 // current message loop. Inserts |callback| into |pending_callback_map_|,
595 // keyed by |handle|.
596 void InvokeUserCallbackLater(
597 ClientSocketHandle* handle, const CompletionCallback& callback, int rv);
599 // Invokes the user callback for |handle|. By the time this task has run,
600 // it's possible that the request has been cancelled, so |handle| may not
601 // exist in |pending_callback_map_|. We look up the callback and result code
602 // in |pending_callback_map_|.
603 void InvokeUserCallback(ClientSocketHandle* handle);
605 // Tries to close idle sockets in a higher level socket pool as long as this
606 // this pool is stalled.
607 void TryToCloseSocketsInLayeredPools();
609 GroupMap group_map_;
611 // Map of the ClientSocketHandles for which we have a pending Task to invoke a
612 // callback. This is necessary since, before we invoke said callback, it's
613 // possible that the request is cancelled.
614 PendingCallbackMap pending_callback_map_;
616 // Timer used to periodically prune idle sockets that timed out or can't be
617 // reused.
618 base::RepeatingTimer<ClientSocketPoolBaseHelper> timer_;
620 // The total number of idle sockets in the system.
621 int idle_socket_count_;
623 // Number of connecting sockets across all groups.
624 int connecting_socket_count_;
626 // Number of connected sockets we handed out across all groups.
627 int handed_out_socket_count_;
629 // The maximum total number of sockets. See ReachedMaxSocketsLimit.
630 const int max_sockets_;
632 // The maximum number of sockets kept per group.
633 const int max_sockets_per_group_;
635 // Whether to use timer to cleanup idle sockets.
636 bool use_cleanup_timer_;
638 // The time to wait until closing idle sockets.
639 const base::TimeDelta unused_idle_socket_timeout_;
640 const base::TimeDelta used_idle_socket_timeout_;
642 const scoped_ptr<ConnectJobFactory> connect_job_factory_;
644 // TODO(vandebo) Remove when backup jobs move to TransportClientSocketPool
645 bool connect_backup_jobs_enabled_;
647 // A unique id for the pool. It gets incremented every time we
648 // FlushWithError() the pool. This is so that when sockets get released back
649 // to the pool, we can make sure that they are discarded rather than reused.
650 int pool_generation_number_;
652 // Used to add |this| as a higher layer pool on top of lower layer pools. May
653 // be NULL if no lower layer pools will be added.
654 HigherLayeredPool* pool_;
656 // Pools that create connections through |this|. |this| will try to close
657 // their idle sockets when it stalls. Must be empty on destruction.
658 std::set<HigherLayeredPool*> higher_pools_;
660 // Pools that this goes through. Typically there's only one, but not always.
661 // |this| will check if they're stalled when it has a new idle socket. |this|
662 // will remove itself from all lower layered pools on destruction.
663 std::set<LowerLayeredPool*> lower_pools_;
665 base::WeakPtrFactory<ClientSocketPoolBaseHelper> weak_factory_;
667 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBaseHelper);
670 } // namespace internal
672 template <typename SocketParams>
673 class ClientSocketPoolBase {
674 public:
675 class Request : public internal::ClientSocketPoolBaseHelper::Request {
676 public:
677 Request(ClientSocketHandle* handle,
678 const CompletionCallback& callback,
679 RequestPriority priority,
680 internal::ClientSocketPoolBaseHelper::Flags flags,
681 bool ignore_limits,
682 const scoped_refptr<SocketParams>& params,
683 const BoundNetLog& net_log)
684 : internal::ClientSocketPoolBaseHelper::Request(
685 handle, callback, priority, ignore_limits, flags, net_log),
686 params_(params) {}
688 const scoped_refptr<SocketParams>& params() const { return params_; }
690 private:
691 const scoped_refptr<SocketParams> params_;
694 class ConnectJobFactory {
695 public:
696 ConnectJobFactory() {}
697 virtual ~ConnectJobFactory() {}
699 virtual scoped_ptr<ConnectJob> NewConnectJob(
700 const std::string& group_name,
701 const Request& request,
702 ConnectJob::Delegate* delegate) const = 0;
704 virtual base::TimeDelta ConnectionTimeout() const = 0;
706 private:
707 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory);
710 // |max_sockets| is the maximum number of sockets to be maintained by this
711 // ClientSocketPool. |max_sockets_per_group| specifies the maximum number of
712 // sockets a "group" can have. |unused_idle_socket_timeout| specifies how
713 // long to leave an unused idle socket open before closing it.
714 // |used_idle_socket_timeout| specifies how long to leave a previously used
715 // idle socket open before closing it.
716 ClientSocketPoolBase(HigherLayeredPool* self,
717 int max_sockets,
718 int max_sockets_per_group,
719 base::TimeDelta unused_idle_socket_timeout,
720 base::TimeDelta used_idle_socket_timeout,
721 ConnectJobFactory* connect_job_factory)
722 : helper_(self,
723 max_sockets,
724 max_sockets_per_group,
725 unused_idle_socket_timeout,
726 used_idle_socket_timeout,
727 new ConnectJobFactoryAdaptor(connect_job_factory)) {}
729 virtual ~ClientSocketPoolBase() {}
731 // These member functions simply forward to ClientSocketPoolBaseHelper.
732 void AddLowerLayeredPool(LowerLayeredPool* lower_pool) {
733 helper_.AddLowerLayeredPool(lower_pool);
736 void AddHigherLayeredPool(HigherLayeredPool* higher_pool) {
737 helper_.AddHigherLayeredPool(higher_pool);
740 void RemoveHigherLayeredPool(HigherLayeredPool* higher_pool) {
741 helper_.RemoveHigherLayeredPool(higher_pool);
744 // RequestSocket bundles up the parameters into a Request and then forwards to
745 // ClientSocketPoolBaseHelper::RequestSocket().
746 int RequestSocket(const std::string& group_name,
747 const scoped_refptr<SocketParams>& params,
748 RequestPriority priority,
749 ClientSocketHandle* handle,
750 const CompletionCallback& callback,
751 const BoundNetLog& net_log) {
752 scoped_ptr<const Request> request(
753 new Request(handle, callback, priority,
754 internal::ClientSocketPoolBaseHelper::NORMAL,
755 params->ignore_limits(),
756 params, net_log));
757 return helper_.RequestSocket(group_name, request.Pass());
760 // RequestSockets bundles up the parameters into a Request and then forwards
761 // to ClientSocketPoolBaseHelper::RequestSockets(). Note that it assigns the
762 // priority to IDLE and specifies the NO_IDLE_SOCKETS flag.
763 void RequestSockets(const std::string& group_name,
764 const scoped_refptr<SocketParams>& params,
765 int num_sockets,
766 const BoundNetLog& net_log) {
767 const Request request(NULL /* no handle */, CompletionCallback(), IDLE,
768 internal::ClientSocketPoolBaseHelper::NO_IDLE_SOCKETS,
769 params->ignore_limits(), params, net_log);
770 helper_.RequestSockets(group_name, request, num_sockets);
773 void CancelRequest(const std::string& group_name,
774 ClientSocketHandle* handle) {
775 return helper_.CancelRequest(group_name, handle);
778 void ReleaseSocket(const std::string& group_name,
779 scoped_ptr<StreamSocket> socket,
780 int id) {
781 return helper_.ReleaseSocket(group_name, socket.Pass(), id);
784 void FlushWithError(int error) { helper_.FlushWithError(error); }
786 bool IsStalled() const { return helper_.IsStalled(); }
788 void CloseIdleSockets() { return helper_.CloseIdleSockets(); }
790 int idle_socket_count() const { return helper_.idle_socket_count(); }
792 int IdleSocketCountInGroup(const std::string& group_name) const {
793 return helper_.IdleSocketCountInGroup(group_name);
796 LoadState GetLoadState(const std::string& group_name,
797 const ClientSocketHandle* handle) const {
798 return helper_.GetLoadState(group_name, handle);
801 virtual void OnConnectJobComplete(int result, ConnectJob* job) {
802 return helper_.OnConnectJobComplete(result, job);
805 int NumUnassignedConnectJobsInGroup(const std::string& group_name) const {
806 return helper_.NumUnassignedConnectJobsInGroup(group_name);
809 int NumConnectJobsInGroup(const std::string& group_name) const {
810 return helper_.NumConnectJobsInGroup(group_name);
813 int NumActiveSocketsInGroup(const std::string& group_name) const {
814 return helper_.NumActiveSocketsInGroup(group_name);
817 bool HasGroup(const std::string& group_name) const {
818 return helper_.HasGroup(group_name);
821 void CleanupIdleSockets(bool force) {
822 return helper_.CleanupIdleSockets(force);
825 scoped_ptr<base::DictionaryValue> GetInfoAsValue(const std::string& name,
826 const std::string& type) const {
827 return helper_.GetInfoAsValue(name, type);
830 base::TimeDelta ConnectionTimeout() const {
831 return helper_.ConnectionTimeout();
834 void EnableConnectBackupJobs() { helper_.EnableConnectBackupJobs(); }
836 bool CloseOneIdleSocket() { return helper_.CloseOneIdleSocket(); }
838 bool CloseOneIdleConnectionInHigherLayeredPool() {
839 return helper_.CloseOneIdleConnectionInHigherLayeredPool();
842 private:
843 // This adaptor class exists to bridge the
844 // internal::ClientSocketPoolBaseHelper::ConnectJobFactory and
845 // ClientSocketPoolBase::ConnectJobFactory types, allowing clients to use the
846 // typesafe ClientSocketPoolBase::ConnectJobFactory, rather than having to
847 // static_cast themselves.
848 class ConnectJobFactoryAdaptor
849 : public internal::ClientSocketPoolBaseHelper::ConnectJobFactory {
850 public:
851 typedef typename ClientSocketPoolBase<SocketParams>::ConnectJobFactory
852 ConnectJobFactory;
854 explicit ConnectJobFactoryAdaptor(ConnectJobFactory* connect_job_factory)
855 : connect_job_factory_(connect_job_factory) {}
856 ~ConnectJobFactoryAdaptor() override {}
858 scoped_ptr<ConnectJob> NewConnectJob(
859 const std::string& group_name,
860 const internal::ClientSocketPoolBaseHelper::Request& request,
861 ConnectJob::Delegate* delegate) const override {
862 const Request& casted_request = static_cast<const Request&>(request);
863 return connect_job_factory_->NewConnectJob(
864 group_name, casted_request, delegate);
867 base::TimeDelta ConnectionTimeout() const override {
868 return connect_job_factory_->ConnectionTimeout();
871 const scoped_ptr<ConnectJobFactory> connect_job_factory_;
874 internal::ClientSocketPoolBaseHelper helper_;
876 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBase);
879 } // namespace net
881 #endif // NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_