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.
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_
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"
55 class ClientSocketHandle
;
57 // ConnectJob provides an abstract interface for "connecting" a socket.
58 // The connection may involve host resolution, tcp connection, ssl connection,
60 class NET_EXPORT_PRIVATE ConnectJob
{
62 class NET_EXPORT_PRIVATE 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
,
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
,
82 const BoundNetLog
& net_log
);
83 virtual ~ConnectJob();
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
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
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_
; }
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_
;
126 virtual int ConnectInternal() = 0;
128 void LogConnectStart();
129 void LogConnectCompletion(int net_error
);
131 // Alerts the delegate that the ConnectJob has timed out.
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_
;
141 scoped_ptr
<StreamSocket
> socket_
;
142 BoundNetLog net_log_
;
143 // A ConnectJob is idle until Connect() has been called.
146 DISALLOW_COPY_AND_ASSIGN(ConnectJob
);
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
{
160 typedef uint32 Flags
;
162 // Used to specify specific behavior for the ClientSocketPool.
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
{
170 Request(ClientSocketHandle
* handle
,
171 const CompletionCallback
& callback
,
172 RequestPriority priority
,
175 const BoundNetLog
& net_log
);
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_
; }
187 ClientSocketHandle
* const handle_
;
188 const CompletionCallback callback_
;
189 // TODO(akalin): Support reprioritization.
190 const RequestPriority priority_
;
191 const bool ignore_limits_
;
193 const BoundNetLog net_log_
;
195 DISALLOW_COPY_AND_ASSIGN(Request
);
198 class ConnectJobFactory
{
200 ConnectJobFactory() {}
201 virtual ~ConnectJobFactory() {}
203 virtual scoped_ptr
<ConnectJob
> NewConnectJob(
204 const std::string
& group_name
,
205 const Request
& request
,
206 ConnectJob::Delegate
* delegate
) const = 0;
208 virtual base::TimeDelta
ConnectionTimeout() const = 0;
211 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory
);
214 ClientSocketPoolBaseHelper(
215 HigherLayeredPool
* pool
,
217 int max_sockets_per_group
,
218 base::TimeDelta unused_idle_socket_timeout
,
219 base::TimeDelta used_idle_socket_timeout
,
220 ConnectJobFactory
* connect_job_factory
);
222 ~ClientSocketPoolBaseHelper() override
;
224 // Adds a lower layered pool to |this|, and adds |this| as a higher layered
225 // pool on top of |lower_pool|.
226 void AddLowerLayeredPool(LowerLayeredPool
* lower_pool
);
228 // See LowerLayeredPool::IsStalled for documentation on this function.
229 bool IsStalled() const;
231 // See LowerLayeredPool for documentation on these functions. It is expected
232 // in the destructor that no higher layer pools remain.
233 void AddHigherLayeredPool(HigherLayeredPool
* higher_pool
);
234 void RemoveHigherLayeredPool(HigherLayeredPool
* higher_pool
);
236 // See ClientSocketPool::RequestSocket for documentation on this function.
237 int RequestSocket(const std::string
& group_name
,
238 scoped_ptr
<const Request
> request
);
240 // See ClientSocketPool::RequestSocket for documentation on this function.
241 void RequestSockets(const std::string
& group_name
,
242 const Request
& request
,
245 // See ClientSocketPool::CancelRequest for documentation on this function.
246 void CancelRequest(const std::string
& group_name
,
247 ClientSocketHandle
* handle
);
249 // See ClientSocketPool::ReleaseSocket for documentation on this function.
250 void ReleaseSocket(const std::string
& group_name
,
251 scoped_ptr
<StreamSocket
> socket
,
254 // See ClientSocketPool::FlushWithError for documentation on this function.
255 void FlushWithError(int error
);
257 // See ClientSocketPool::CloseIdleSockets for documentation on this function.
258 void CloseIdleSockets();
260 // See ClientSocketPool::IdleSocketCount() for documentation on this function.
261 int idle_socket_count() const {
262 return idle_socket_count_
;
265 // See ClientSocketPool::IdleSocketCountInGroup() for documentation on this
267 int IdleSocketCountInGroup(const std::string
& group_name
) const;
269 // See ClientSocketPool::GetLoadState() for documentation on this function.
270 LoadState
GetLoadState(const std::string
& group_name
,
271 const ClientSocketHandle
* handle
) const;
273 base::TimeDelta
ConnectRetryInterval() const {
274 // TODO(mbelshe): Make this tuned dynamically based on measured RTT.
275 // For now, just use the max retry interval.
276 return base::TimeDelta::FromMilliseconds(
277 ClientSocketPool::kMaxConnectRetryIntervalMs
);
280 int NumUnassignedConnectJobsInGroup(const std::string
& group_name
) const {
281 return group_map_
.find(group_name
)->second
->unassigned_job_count();
284 int NumConnectJobsInGroup(const std::string
& group_name
) const {
285 return group_map_
.find(group_name
)->second
->jobs().size();
288 int NumActiveSocketsInGroup(const std::string
& group_name
) const {
289 return group_map_
.find(group_name
)->second
->active_socket_count();
292 bool HasGroup(const std::string
& group_name
) const;
294 // Called to enable/disable cleaning up idle sockets. When enabled,
295 // idle sockets that have been around for longer than a period defined
296 // by kCleanupInterval are cleaned up using a timer. Otherwise they are
297 // closed next time client makes a request. This may reduce network
298 // activity and power consumption.
299 static bool cleanup_timer_enabled();
300 static bool set_cleanup_timer_enabled(bool enabled
);
302 // Closes all idle sockets if |force| is true. Else, only closes idle
303 // sockets that timed out or can't be reused. Made public for testing.
304 void CleanupIdleSockets(bool force
);
306 // Closes one idle socket. Picks the first one encountered.
307 // TODO(willchan): Consider a better algorithm for doing this. Perhaps we
308 // should keep an ordered list of idle sockets, and close them in order.
309 // Requires maintaining more state. It's not clear if it's worth it since
310 // I'm not sure if we hit this situation often.
311 bool CloseOneIdleSocket();
313 // Checks higher layered pools to see if they can close an idle connection.
314 bool CloseOneIdleConnectionInHigherLayeredPool();
316 // See ClientSocketPool::GetInfoAsValue for documentation on this function.
317 base::DictionaryValue
* GetInfoAsValue(const std::string
& name
,
318 const std::string
& type
) const;
320 base::TimeDelta
ConnectionTimeout() const {
321 return connect_job_factory_
->ConnectionTimeout();
324 static bool connect_backup_jobs_enabled();
325 static bool set_connect_backup_jobs_enabled(bool enabled
);
327 void EnableConnectBackupJobs();
329 // ConnectJob::Delegate methods:
330 void OnConnectJobComplete(int result
, ConnectJob
* job
) override
;
332 // NetworkChangeNotifier::IPAddressObserver methods:
333 void OnIPAddressChanged() override
;
336 friend class base::RefCounted
<ClientSocketPoolBaseHelper
>;
338 // Entry for a persistent socket which became idle at time |start_time|.
340 IdleSocket() : socket(NULL
) {}
342 // An idle socket can't be used if it is disconnected or has been used
343 // before and has received data unexpectedly (hence no longer idle). The
344 // unread data would be mistaken for the beginning of the next response if
345 // we were to use the socket for a new request.
347 // Note that a socket that has never been used before (like a preconnected
348 // socket) may be used even with unread data. This may be, e.g., a SPDY
350 bool IsUsable() const;
352 // An idle socket should be removed if it can't be reused, or has been idle
353 // for too long. |now| is the current time value (TimeTicks::Now()).
354 // |timeout| is the length of time to wait before timing out an idle socket.
355 bool ShouldCleanup(base::TimeTicks now
, base::TimeDelta timeout
) const;
357 StreamSocket
* socket
;
358 base::TimeTicks start_time
;
361 typedef PriorityQueue
<const Request
*> RequestQueue
;
362 typedef std::map
<const ClientSocketHandle
*, const Request
*> RequestMap
;
364 // A Group is allocated per group_name when there are idle sockets or pending
365 // requests. Otherwise, the Group object is removed from the map.
366 // |active_socket_count| tracks the number of sockets held by clients.
372 bool IsEmpty() const {
373 return active_socket_count_
== 0 && idle_sockets_
.empty() &&
374 jobs_
.empty() && pending_requests_
.empty();
377 bool HasAvailableSocketSlot(int max_sockets_per_group
) const {
378 return NumActiveSocketSlots() < max_sockets_per_group
;
381 int NumActiveSocketSlots() const {
382 return active_socket_count_
+ static_cast<int>(jobs_
.size()) +
383 static_cast<int>(idle_sockets_
.size());
386 // Returns true if the group could make use of an additional socket slot, if
387 // it were given one.
388 bool CanUseAdditionalSocketSlot(int max_sockets_per_group
) const {
389 return HasAvailableSocketSlot(max_sockets_per_group
) &&
390 pending_requests_
.size() > jobs_
.size();
393 // Returns the priority of the top of the pending request queue
394 // (which may be less than the maximum priority over the entire
395 // queue, due to how we prioritize requests with |ignore_limits|
397 RequestPriority
TopPendingPriority() const {
398 // NOTE: FirstMax().value()->priority() is not the same as
399 // FirstMax().priority()!
400 return pending_requests_
.FirstMax().value()->priority();
403 // Set a timer to create a backup job if it takes too long to
404 // create one and if a timer isn't already running.
405 void StartBackupJobTimer(const std::string
& group_name
,
406 ClientSocketPoolBaseHelper
* pool
);
408 bool BackupJobTimerIsRunning() const;
410 // If there's a ConnectJob that's never been assigned to Request,
411 // decrements |unassigned_job_count_| and returns true.
412 // Otherwise, returns false.
413 bool TryToUseUnassignedConnectJob();
415 void AddJob(scoped_ptr
<ConnectJob
> job
, bool is_preconnect
);
416 // Remove |job| from this group, which must already own |job|.
417 void RemoveJob(ConnectJob
* job
);
418 void RemoveAllJobs();
420 bool has_pending_requests() const {
421 return !pending_requests_
.empty();
424 size_t pending_request_count() const {
425 return pending_requests_
.size();
428 // Gets (but does not remove) the next pending request. Returns
429 // NULL if there are no pending requests.
430 const Request
* GetNextPendingRequest() const;
432 // Returns true if there is a connect job for |handle|.
433 bool HasConnectJobForHandle(const ClientSocketHandle
* handle
) const;
435 // Inserts the request into the queue based on priority
436 // order. Older requests are prioritized over requests of equal
438 void InsertPendingRequest(scoped_ptr
<const Request
> request
);
440 // Gets and removes the next pending request. Returns NULL if
441 // there are no pending requests.
442 scoped_ptr
<const Request
> PopNextPendingRequest();
444 // Finds the pending request for |handle| and removes it. Returns
445 // the removed pending request, or NULL if there was none.
446 scoped_ptr
<const Request
> FindAndRemovePendingRequest(
447 ClientSocketHandle
* handle
);
449 void IncrementActiveSocketCount() { active_socket_count_
++; }
450 void DecrementActiveSocketCount() { active_socket_count_
--; }
452 int unassigned_job_count() const { return unassigned_job_count_
; }
453 const std::list
<ConnectJob
*>& jobs() const { return jobs_
; }
454 const std::list
<IdleSocket
>& idle_sockets() const { return idle_sockets_
; }
455 int active_socket_count() const { return active_socket_count_
; }
456 std::list
<IdleSocket
>* mutable_idle_sockets() { return &idle_sockets_
; }
459 // Returns the iterator's pending request after removing it from
461 scoped_ptr
<const Request
> RemovePendingRequest(
462 const RequestQueue::Pointer
& pointer
);
464 // Called when the backup socket timer fires.
465 void OnBackupJobTimerFired(
466 std::string group_name
,
467 ClientSocketPoolBaseHelper
* pool
);
469 // Checks that |unassigned_job_count_| does not execeed the number of
473 // Total number of ConnectJobs that have never been assigned to a Request.
474 // Since jobs use late binding to requests, which ConnectJobs have or have
475 // not been assigned to a request are not tracked. This is incremented on
476 // preconnect and decremented when a preconnect is assigned, or when there
477 // are fewer than |unassigned_job_count_| ConnectJobs. Not incremented
478 // when a request is cancelled.
479 size_t unassigned_job_count_
;
481 std::list
<IdleSocket
> idle_sockets_
;
482 std::list
<ConnectJob
*> jobs_
;
483 RequestQueue pending_requests_
;
484 int active_socket_count_
; // number of active sockets used by clients
485 // A timer for when to start the backup job.
486 base::OneShotTimer
<Group
> backup_job_timer_
;
489 typedef std::map
<std::string
, Group
*> GroupMap
;
491 typedef std::set
<ConnectJob
*> ConnectJobSet
;
493 struct CallbackResultPair
{
494 CallbackResultPair();
495 CallbackResultPair(const CompletionCallback
& callback_in
, int result_in
);
496 ~CallbackResultPair();
498 CompletionCallback callback
;
502 typedef std::map
<const ClientSocketHandle
*, CallbackResultPair
>
505 Group
* GetOrCreateGroup(const std::string
& group_name
);
506 void RemoveGroup(const std::string
& group_name
);
507 void RemoveGroup(GroupMap::iterator it
);
509 // Called when the number of idle sockets changes.
510 void IncrementIdleCount();
511 void DecrementIdleCount();
513 // Start cleanup timer for idle sockets.
514 void StartIdleSocketTimer();
516 // Scans the group map for groups which have an available socket slot and
517 // at least one pending request. Returns true if any groups are stalled, and
518 // if so (and if both |group| and |group_name| are not NULL), fills |group|
519 // and |group_name| with data of the stalled group having highest priority.
520 bool FindTopStalledGroup(Group
** group
, std::string
* group_name
) const;
522 // Called when timer_ fires. This method scans the idle sockets removing
523 // sockets that timed out or can't be reused.
524 void OnCleanupTimerFired() {
525 CleanupIdleSockets(false);
528 // Removes |job| from |group|, which must already own |job|.
529 void RemoveConnectJob(ConnectJob
* job
, Group
* group
);
531 // Tries to see if we can handle any more requests for |group|.
532 void OnAvailableSocketSlot(const std::string
& group_name
, Group
* group
);
534 // Process a pending socket request for a group.
535 void ProcessPendingRequest(const std::string
& group_name
, Group
* group
);
537 // Assigns |socket| to |handle| and updates |group|'s counters appropriately.
538 void HandOutSocket(scoped_ptr
<StreamSocket
> socket
,
539 ClientSocketHandle::SocketReuseType reuse_type
,
540 const LoadTimingInfo::ConnectTiming
& connect_timing
,
541 ClientSocketHandle
* handle
,
542 base::TimeDelta time_idle
,
544 const BoundNetLog
& net_log
);
546 // Adds |socket| to the list of idle sockets for |group|.
547 void AddIdleSocket(scoped_ptr
<StreamSocket
> socket
, Group
* group
);
549 // Iterates through |group_map_|, canceling all ConnectJobs and deleting
550 // groups if they are no longer needed.
551 void CancelAllConnectJobs();
553 // Iterates through |group_map_|, posting |error| callbacks for all
554 // requests, and then deleting groups if they are no longer needed.
555 void CancelAllRequestsWithError(int error
);
557 // Returns true if we can't create any more sockets due to the total limit.
558 bool ReachedMaxSocketsLimit() const;
560 // This is the internal implementation of RequestSocket(). It differs in that
561 // it does not handle logging into NetLog of the queueing status of
563 int RequestSocketInternal(const std::string
& group_name
,
564 const Request
& request
);
566 // Assigns an idle socket for the group to the request.
567 // Returns |true| if an idle socket is available, false otherwise.
568 bool AssignIdleSocketToRequest(const Request
& request
, Group
* group
);
570 static void LogBoundConnectJobToRequest(
571 const NetLog::Source
& connect_job_source
, const Request
& request
);
573 // Same as CloseOneIdleSocket() except it won't close an idle socket in
574 // |group|. If |group| is NULL, it is ignored. Returns true if it closed a
576 bool CloseOneIdleSocketExceptInGroup(const Group
* group
);
578 // Checks if there are stalled socket groups that should be notified
579 // for possible wakeup.
580 void CheckForStalledSocketGroups();
582 // Posts a task to call InvokeUserCallback() on the next iteration through the
583 // current message loop. Inserts |callback| into |pending_callback_map_|,
584 // keyed by |handle|.
585 void InvokeUserCallbackLater(
586 ClientSocketHandle
* handle
, const CompletionCallback
& callback
, int rv
);
588 // Invokes the user callback for |handle|. By the time this task has run,
589 // it's possible that the request has been cancelled, so |handle| may not
590 // exist in |pending_callback_map_|. We look up the callback and result code
591 // in |pending_callback_map_|.
592 void InvokeUserCallback(ClientSocketHandle
* handle
);
594 // Tries to close idle sockets in a higher level socket pool as long as this
595 // this pool is stalled.
596 void TryToCloseSocketsInLayeredPools();
600 // Map of the ClientSocketHandles for which we have a pending Task to invoke a
601 // callback. This is necessary since, before we invoke said callback, it's
602 // possible that the request is cancelled.
603 PendingCallbackMap pending_callback_map_
;
605 // Timer used to periodically prune idle sockets that timed out or can't be
607 base::RepeatingTimer
<ClientSocketPoolBaseHelper
> timer_
;
609 // The total number of idle sockets in the system.
610 int idle_socket_count_
;
612 // Number of connecting sockets across all groups.
613 int connecting_socket_count_
;
615 // Number of connected sockets we handed out across all groups.
616 int handed_out_socket_count_
;
618 // The maximum total number of sockets. See ReachedMaxSocketsLimit.
619 const int max_sockets_
;
621 // The maximum number of sockets kept per group.
622 const int max_sockets_per_group_
;
624 // Whether to use timer to cleanup idle sockets.
625 bool use_cleanup_timer_
;
627 // The time to wait until closing idle sockets.
628 const base::TimeDelta unused_idle_socket_timeout_
;
629 const base::TimeDelta used_idle_socket_timeout_
;
631 const scoped_ptr
<ConnectJobFactory
> connect_job_factory_
;
633 // TODO(vandebo) Remove when backup jobs move to TransportClientSocketPool
634 bool connect_backup_jobs_enabled_
;
636 // A unique id for the pool. It gets incremented every time we
637 // FlushWithError() the pool. This is so that when sockets get released back
638 // to the pool, we can make sure that they are discarded rather than reused.
639 int pool_generation_number_
;
641 // Used to add |this| as a higher layer pool on top of lower layer pools. May
642 // be NULL if no lower layer pools will be added.
643 HigherLayeredPool
* pool_
;
645 // Pools that create connections through |this|. |this| will try to close
646 // their idle sockets when it stalls. Must be empty on destruction.
647 std::set
<HigherLayeredPool
*> higher_pools_
;
649 // Pools that this goes through. Typically there's only one, but not always.
650 // |this| will check if they're stalled when it has a new idle socket. |this|
651 // will remove itself from all lower layered pools on destruction.
652 std::set
<LowerLayeredPool
*> lower_pools_
;
654 base::WeakPtrFactory
<ClientSocketPoolBaseHelper
> weak_factory_
;
656 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBaseHelper
);
659 } // namespace internal
661 template <typename SocketParams
>
662 class ClientSocketPoolBase
{
664 class Request
: public internal::ClientSocketPoolBaseHelper::Request
{
666 Request(ClientSocketHandle
* handle
,
667 const CompletionCallback
& callback
,
668 RequestPriority priority
,
669 internal::ClientSocketPoolBaseHelper::Flags flags
,
671 const scoped_refptr
<SocketParams
>& params
,
672 const BoundNetLog
& net_log
)
673 : internal::ClientSocketPoolBaseHelper::Request(
674 handle
, callback
, priority
, ignore_limits
, flags
, net_log
),
677 const scoped_refptr
<SocketParams
>& params() const { return params_
; }
680 const scoped_refptr
<SocketParams
> params_
;
683 class ConnectJobFactory
{
685 ConnectJobFactory() {}
686 virtual ~ConnectJobFactory() {}
688 virtual scoped_ptr
<ConnectJob
> NewConnectJob(
689 const std::string
& group_name
,
690 const Request
& request
,
691 ConnectJob::Delegate
* delegate
) const = 0;
693 virtual base::TimeDelta
ConnectionTimeout() const = 0;
696 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory
);
699 // |max_sockets| is the maximum number of sockets to be maintained by this
700 // ClientSocketPool. |max_sockets_per_group| specifies the maximum number of
701 // sockets a "group" can have. |unused_idle_socket_timeout| specifies how
702 // long to leave an unused idle socket open before closing it.
703 // |used_idle_socket_timeout| specifies how long to leave a previously used
704 // idle socket open before closing it.
705 ClientSocketPoolBase(HigherLayeredPool
* self
,
707 int max_sockets_per_group
,
708 base::TimeDelta unused_idle_socket_timeout
,
709 base::TimeDelta used_idle_socket_timeout
,
710 ConnectJobFactory
* connect_job_factory
)
713 max_sockets_per_group
,
714 unused_idle_socket_timeout
,
715 used_idle_socket_timeout
,
716 new ConnectJobFactoryAdaptor(connect_job_factory
)) {}
718 virtual ~ClientSocketPoolBase() {}
720 // These member functions simply forward to ClientSocketPoolBaseHelper.
721 void AddLowerLayeredPool(LowerLayeredPool
* lower_pool
) {
722 helper_
.AddLowerLayeredPool(lower_pool
);
725 void AddHigherLayeredPool(HigherLayeredPool
* higher_pool
) {
726 helper_
.AddHigherLayeredPool(higher_pool
);
729 void RemoveHigherLayeredPool(HigherLayeredPool
* higher_pool
) {
730 helper_
.RemoveHigherLayeredPool(higher_pool
);
733 // RequestSocket bundles up the parameters into a Request and then forwards to
734 // ClientSocketPoolBaseHelper::RequestSocket().
735 int RequestSocket(const std::string
& group_name
,
736 const scoped_refptr
<SocketParams
>& params
,
737 RequestPriority priority
,
738 ClientSocketHandle
* handle
,
739 const CompletionCallback
& callback
,
740 const BoundNetLog
& net_log
) {
741 scoped_ptr
<const Request
> request(
742 new Request(handle
, callback
, priority
,
743 internal::ClientSocketPoolBaseHelper::NORMAL
,
744 params
->ignore_limits(),
746 return helper_
.RequestSocket(group_name
, request
.Pass());
749 // RequestSockets bundles up the parameters into a Request and then forwards
750 // to ClientSocketPoolBaseHelper::RequestSockets(). Note that it assigns the
751 // priority to DEFAULT_PRIORITY and specifies the NO_IDLE_SOCKETS flag.
752 void RequestSockets(const std::string
& group_name
,
753 const scoped_refptr
<SocketParams
>& params
,
755 const BoundNetLog
& net_log
) {
756 const Request
request(NULL
/* no handle */,
757 CompletionCallback(),
759 internal::ClientSocketPoolBaseHelper::NO_IDLE_SOCKETS
,
760 params
->ignore_limits(),
763 helper_
.RequestSockets(group_name
, request
, num_sockets
);
766 void CancelRequest(const std::string
& group_name
,
767 ClientSocketHandle
* handle
) {
768 return helper_
.CancelRequest(group_name
, handle
);
771 void ReleaseSocket(const std::string
& group_name
,
772 scoped_ptr
<StreamSocket
> socket
,
774 return helper_
.ReleaseSocket(group_name
, socket
.Pass(), id
);
777 void FlushWithError(int error
) { helper_
.FlushWithError(error
); }
779 bool IsStalled() const { return helper_
.IsStalled(); }
781 void CloseIdleSockets() { return helper_
.CloseIdleSockets(); }
783 int idle_socket_count() const { return helper_
.idle_socket_count(); }
785 int IdleSocketCountInGroup(const std::string
& group_name
) const {
786 return helper_
.IdleSocketCountInGroup(group_name
);
789 LoadState
GetLoadState(const std::string
& group_name
,
790 const ClientSocketHandle
* handle
) const {
791 return helper_
.GetLoadState(group_name
, handle
);
794 virtual void OnConnectJobComplete(int result
, ConnectJob
* job
) {
795 return helper_
.OnConnectJobComplete(result
, job
);
798 int NumUnassignedConnectJobsInGroup(const std::string
& group_name
) const {
799 return helper_
.NumUnassignedConnectJobsInGroup(group_name
);
802 int NumConnectJobsInGroup(const std::string
& group_name
) const {
803 return helper_
.NumConnectJobsInGroup(group_name
);
806 int NumActiveSocketsInGroup(const std::string
& group_name
) const {
807 return helper_
.NumActiveSocketsInGroup(group_name
);
810 bool HasGroup(const std::string
& group_name
) const {
811 return helper_
.HasGroup(group_name
);
814 void CleanupIdleSockets(bool force
) {
815 return helper_
.CleanupIdleSockets(force
);
818 base::DictionaryValue
* GetInfoAsValue(const std::string
& name
,
819 const std::string
& type
) const {
820 return helper_
.GetInfoAsValue(name
, type
);
823 base::TimeDelta
ConnectionTimeout() const {
824 return helper_
.ConnectionTimeout();
827 void EnableConnectBackupJobs() { helper_
.EnableConnectBackupJobs(); }
829 bool CloseOneIdleSocket() { return helper_
.CloseOneIdleSocket(); }
831 bool CloseOneIdleConnectionInHigherLayeredPool() {
832 return helper_
.CloseOneIdleConnectionInHigherLayeredPool();
836 // This adaptor class exists to bridge the
837 // internal::ClientSocketPoolBaseHelper::ConnectJobFactory and
838 // ClientSocketPoolBase::ConnectJobFactory types, allowing clients to use the
839 // typesafe ClientSocketPoolBase::ConnectJobFactory, rather than having to
840 // static_cast themselves.
841 class ConnectJobFactoryAdaptor
842 : public internal::ClientSocketPoolBaseHelper::ConnectJobFactory
{
844 typedef typename ClientSocketPoolBase
<SocketParams
>::ConnectJobFactory
847 explicit ConnectJobFactoryAdaptor(ConnectJobFactory
* connect_job_factory
)
848 : connect_job_factory_(connect_job_factory
) {}
849 ~ConnectJobFactoryAdaptor() override
{}
851 scoped_ptr
<ConnectJob
> NewConnectJob(
852 const std::string
& group_name
,
853 const internal::ClientSocketPoolBaseHelper::Request
& request
,
854 ConnectJob::Delegate
* delegate
) const override
{
855 const Request
& casted_request
= static_cast<const Request
&>(request
);
856 return connect_job_factory_
->NewConnectJob(
857 group_name
, casted_request
, delegate
);
860 base::TimeDelta
ConnectionTimeout() const override
{
861 return connect_job_factory_
->ConnectionTimeout();
864 const scoped_ptr
<ConnectJobFactory
> connect_job_factory_
;
867 internal::ClientSocketPoolBaseHelper helper_
;
869 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBase
);
874 #endif // NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_