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_
; }
186 // TODO(eroman): Temporary until crbug.com/467797 is solved.
187 void CrashIfInvalid() const;
190 // TODO(eroman): Temporary until crbug.com/467797 is solved.
196 ClientSocketHandle
* const handle_
;
197 const CompletionCallback callback_
;
198 // TODO(akalin): Support reprioritization.
199 const RequestPriority priority_
;
200 const bool ignore_limits_
;
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
{
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;
223 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory
);
226 ClientSocketPoolBaseHelper(
227 HigherLayeredPool
* pool
,
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
,
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
,
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
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 base::DictionaryValue
* GetInfoAsValue(const std::string
& name
,
330 const std::string
& type
) const;
332 base::TimeDelta
ConnectionTimeout() const {
333 return connect_job_factory_
->ConnectionTimeout();
336 static bool connect_backup_jobs_enabled();
337 static bool set_connect_backup_jobs_enabled(bool enabled
);
339 void EnableConnectBackupJobs();
341 // ConnectJob::Delegate methods:
342 void OnConnectJobComplete(int result
, ConnectJob
* job
) override
;
344 // NetworkChangeNotifier::IPAddressObserver methods:
345 void OnIPAddressChanged() override
;
348 friend class base::RefCounted
<ClientSocketPoolBaseHelper
>;
350 // Entry for a persistent socket which became idle at time |start_time|.
352 IdleSocket() : socket(NULL
) {}
354 // An idle socket can't be used if it is disconnected or has been used
355 // before and has received data unexpectedly (hence no longer idle). The
356 // unread data would be mistaken for the beginning of the next response if
357 // we were to use the socket for a new request.
359 // Note that a socket that has never been used before (like a preconnected
360 // socket) may be used even with unread data. This may be, e.g., a SPDY
362 bool IsUsable() const;
364 // An idle socket should be removed if it can't be reused, or has been idle
365 // for too long. |now| is the current time value (TimeTicks::Now()).
366 // |timeout| is the length of time to wait before timing out an idle socket.
367 bool ShouldCleanup(base::TimeTicks now
, base::TimeDelta timeout
) const;
369 StreamSocket
* socket
;
370 base::TimeTicks start_time
;
373 typedef PriorityQueue
<const Request
*> RequestQueue
;
374 typedef std::map
<const ClientSocketHandle
*, const Request
*> RequestMap
;
376 // A Group is allocated per group_name when there are idle sockets or pending
377 // requests. Otherwise, the Group object is removed from the map.
378 // |active_socket_count| tracks the number of sockets held by clients.
384 bool IsEmpty() const {
385 return active_socket_count_
== 0 && idle_sockets_
.empty() &&
386 jobs_
.empty() && pending_requests_
.empty();
389 bool HasAvailableSocketSlot(int max_sockets_per_group
) const {
390 return NumActiveSocketSlots() < max_sockets_per_group
;
393 int NumActiveSocketSlots() const {
394 return active_socket_count_
+ static_cast<int>(jobs_
.size()) +
395 static_cast<int>(idle_sockets_
.size());
398 // Returns true if the group could make use of an additional socket slot, if
399 // it were given one.
400 bool CanUseAdditionalSocketSlot(int max_sockets_per_group
) const {
401 return HasAvailableSocketSlot(max_sockets_per_group
) &&
402 pending_requests_
.size() > jobs_
.size();
405 // Returns the priority of the top of the pending request queue
406 // (which may be less than the maximum priority over the entire
407 // queue, due to how we prioritize requests with |ignore_limits|
409 RequestPriority
TopPendingPriority() const {
410 // NOTE: FirstMax().value()->priority() is not the same as
411 // FirstMax().priority()!
412 return pending_requests_
.FirstMax().value()->priority();
415 // Set a timer to create a backup job if it takes too long to
416 // create one and if a timer isn't already running.
417 void StartBackupJobTimer(const std::string
& group_name
,
418 ClientSocketPoolBaseHelper
* pool
);
420 bool BackupJobTimerIsRunning() const;
422 // If there's a ConnectJob that's never been assigned to Request,
423 // decrements |unassigned_job_count_| and returns true.
424 // Otherwise, returns false.
425 bool TryToUseUnassignedConnectJob();
427 void AddJob(scoped_ptr
<ConnectJob
> job
, bool is_preconnect
);
428 // Remove |job| from this group, which must already own |job|.
429 void RemoveJob(ConnectJob
* job
);
430 void RemoveAllJobs();
432 bool has_pending_requests() const {
433 return !pending_requests_
.empty();
436 size_t pending_request_count() const {
437 return pending_requests_
.size();
440 // Gets (but does not remove) the next pending request. Returns
441 // NULL if there are no pending requests.
442 const Request
* GetNextPendingRequest() const;
444 // Returns true if there is a connect job for |handle|.
445 bool HasConnectJobForHandle(const ClientSocketHandle
* handle
) const;
447 // Inserts the request into the queue based on priority
448 // order. Older requests are prioritized over requests of equal
450 void InsertPendingRequest(scoped_ptr
<const Request
> request
);
452 // Gets and removes the next pending request. Returns NULL if
453 // there are no pending requests.
454 scoped_ptr
<const Request
> PopNextPendingRequest();
456 // Finds the pending request for |handle| and removes it. Returns
457 // the removed pending request, or NULL if there was none.
458 scoped_ptr
<const Request
> FindAndRemovePendingRequest(
459 ClientSocketHandle
* handle
);
461 void IncrementActiveSocketCount() { active_socket_count_
++; }
462 void DecrementActiveSocketCount() { active_socket_count_
--; }
464 int unassigned_job_count() const { return unassigned_job_count_
; }
465 const std::list
<ConnectJob
*>& jobs() const { return jobs_
; }
466 const std::list
<IdleSocket
>& idle_sockets() const { return idle_sockets_
; }
467 int active_socket_count() const { return active_socket_count_
; }
468 std::list
<IdleSocket
>* mutable_idle_sockets() { return &idle_sockets_
; }
471 // Returns the iterator's pending request after removing it from
473 scoped_ptr
<const Request
> RemovePendingRequest(
474 const RequestQueue::Pointer
& pointer
);
476 // Called when the backup socket timer fires.
477 void OnBackupJobTimerFired(
478 std::string group_name
,
479 ClientSocketPoolBaseHelper
* pool
);
481 // Checks that |unassigned_job_count_| does not execeed the number of
485 // Total number of ConnectJobs that have never been assigned to a Request.
486 // Since jobs use late binding to requests, which ConnectJobs have or have
487 // not been assigned to a request are not tracked. This is incremented on
488 // preconnect and decremented when a preconnect is assigned, or when there
489 // are fewer than |unassigned_job_count_| ConnectJobs. Not incremented
490 // when a request is cancelled.
491 size_t unassigned_job_count_
;
493 std::list
<IdleSocket
> idle_sockets_
;
494 std::list
<ConnectJob
*> jobs_
;
495 RequestQueue pending_requests_
;
496 int active_socket_count_
; // number of active sockets used by clients
497 // A timer for when to start the backup job.
498 base::OneShotTimer
<Group
> backup_job_timer_
;
501 typedef std::map
<std::string
, Group
*> GroupMap
;
503 typedef std::set
<ConnectJob
*> ConnectJobSet
;
505 struct CallbackResultPair
{
506 CallbackResultPair();
507 CallbackResultPair(const CompletionCallback
& callback_in
, int result_in
);
508 ~CallbackResultPair();
510 CompletionCallback callback
;
514 typedef std::map
<const ClientSocketHandle
*, CallbackResultPair
>
517 Group
* GetOrCreateGroup(const std::string
& group_name
);
518 void RemoveGroup(const std::string
& group_name
);
519 void RemoveGroup(GroupMap::iterator it
);
521 // Called when the number of idle sockets changes.
522 void IncrementIdleCount();
523 void DecrementIdleCount();
525 // Start cleanup timer for idle sockets.
526 void StartIdleSocketTimer();
528 // Scans the group map for groups which have an available socket slot and
529 // at least one pending request. Returns true if any groups are stalled, and
530 // if so (and if both |group| and |group_name| are not NULL), fills |group|
531 // and |group_name| with data of the stalled group having highest priority.
532 bool FindTopStalledGroup(Group
** group
, std::string
* group_name
) const;
534 // Called when timer_ fires. This method scans the idle sockets removing
535 // sockets that timed out or can't be reused.
536 void OnCleanupTimerFired() {
537 CleanupIdleSockets(false);
540 // Removes |job| from |group|, which must already own |job|.
541 void RemoveConnectJob(ConnectJob
* job
, Group
* group
);
543 // Tries to see if we can handle any more requests for |group|.
544 void OnAvailableSocketSlot(const std::string
& group_name
, Group
* group
);
546 // Process a pending socket request for a group.
547 void ProcessPendingRequest(const std::string
& group_name
, Group
* group
);
549 // Assigns |socket| to |handle| and updates |group|'s counters appropriately.
550 void HandOutSocket(scoped_ptr
<StreamSocket
> socket
,
551 ClientSocketHandle::SocketReuseType reuse_type
,
552 const LoadTimingInfo::ConnectTiming
& connect_timing
,
553 ClientSocketHandle
* handle
,
554 base::TimeDelta time_idle
,
556 const BoundNetLog
& net_log
);
558 // Adds |socket| to the list of idle sockets for |group|.
559 void AddIdleSocket(scoped_ptr
<StreamSocket
> socket
, Group
* group
);
561 // Iterates through |group_map_|, canceling all ConnectJobs and deleting
562 // groups if they are no longer needed.
563 void CancelAllConnectJobs();
565 // Iterates through |group_map_|, posting |error| callbacks for all
566 // requests, and then deleting groups if they are no longer needed.
567 void CancelAllRequestsWithError(int error
);
569 // Returns true if we can't create any more sockets due to the total limit.
570 bool ReachedMaxSocketsLimit() const;
572 // This is the internal implementation of RequestSocket(). It differs in that
573 // it does not handle logging into NetLog of the queueing status of
575 int RequestSocketInternal(const std::string
& group_name
,
576 const Request
& request
);
578 // Assigns an idle socket for the group to the request.
579 // Returns |true| if an idle socket is available, false otherwise.
580 bool AssignIdleSocketToRequest(const Request
& request
, Group
* group
);
582 static void LogBoundConnectJobToRequest(
583 const NetLog::Source
& connect_job_source
, const Request
& request
);
585 // Same as CloseOneIdleSocket() except it won't close an idle socket in
586 // |group|. If |group| is NULL, it is ignored. Returns true if it closed a
588 bool CloseOneIdleSocketExceptInGroup(const Group
* group
);
590 // Checks if there are stalled socket groups that should be notified
591 // for possible wakeup.
592 void CheckForStalledSocketGroups();
594 // Posts a task to call InvokeUserCallback() on the next iteration through the
595 // current message loop. Inserts |callback| into |pending_callback_map_|,
596 // keyed by |handle|.
597 void InvokeUserCallbackLater(
598 ClientSocketHandle
* handle
, const CompletionCallback
& callback
, int rv
);
600 // Invokes the user callback for |handle|. By the time this task has run,
601 // it's possible that the request has been cancelled, so |handle| may not
602 // exist in |pending_callback_map_|. We look up the callback and result code
603 // in |pending_callback_map_|.
604 void InvokeUserCallback(ClientSocketHandle
* handle
);
606 // Tries to close idle sockets in a higher level socket pool as long as this
607 // this pool is stalled.
608 void TryToCloseSocketsInLayeredPools();
612 // Map of the ClientSocketHandles for which we have a pending Task to invoke a
613 // callback. This is necessary since, before we invoke said callback, it's
614 // possible that the request is cancelled.
615 PendingCallbackMap pending_callback_map_
;
617 // Timer used to periodically prune idle sockets that timed out or can't be
619 base::RepeatingTimer
<ClientSocketPoolBaseHelper
> timer_
;
621 // The total number of idle sockets in the system.
622 int idle_socket_count_
;
624 // Number of connecting sockets across all groups.
625 int connecting_socket_count_
;
627 // Number of connected sockets we handed out across all groups.
628 int handed_out_socket_count_
;
630 // The maximum total number of sockets. See ReachedMaxSocketsLimit.
631 const int max_sockets_
;
633 // The maximum number of sockets kept per group.
634 const int max_sockets_per_group_
;
636 // Whether to use timer to cleanup idle sockets.
637 bool use_cleanup_timer_
;
639 // The time to wait until closing idle sockets.
640 const base::TimeDelta unused_idle_socket_timeout_
;
641 const base::TimeDelta used_idle_socket_timeout_
;
643 const scoped_ptr
<ConnectJobFactory
> connect_job_factory_
;
645 // TODO(vandebo) Remove when backup jobs move to TransportClientSocketPool
646 bool connect_backup_jobs_enabled_
;
648 // A unique id for the pool. It gets incremented every time we
649 // FlushWithError() the pool. This is so that when sockets get released back
650 // to the pool, we can make sure that they are discarded rather than reused.
651 int pool_generation_number_
;
653 // Used to add |this| as a higher layer pool on top of lower layer pools. May
654 // be NULL if no lower layer pools will be added.
655 HigherLayeredPool
* pool_
;
657 // Pools that create connections through |this|. |this| will try to close
658 // their idle sockets when it stalls. Must be empty on destruction.
659 std::set
<HigherLayeredPool
*> higher_pools_
;
661 // Pools that this goes through. Typically there's only one, but not always.
662 // |this| will check if they're stalled when it has a new idle socket. |this|
663 // will remove itself from all lower layered pools on destruction.
664 std::set
<LowerLayeredPool
*> lower_pools_
;
666 base::WeakPtrFactory
<ClientSocketPoolBaseHelper
> weak_factory_
;
668 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBaseHelper
);
671 } // namespace internal
673 template <typename SocketParams
>
674 class ClientSocketPoolBase
{
676 class Request
: public internal::ClientSocketPoolBaseHelper::Request
{
678 Request(ClientSocketHandle
* handle
,
679 const CompletionCallback
& callback
,
680 RequestPriority priority
,
681 internal::ClientSocketPoolBaseHelper::Flags flags
,
683 const scoped_refptr
<SocketParams
>& params
,
684 const BoundNetLog
& net_log
)
685 : internal::ClientSocketPoolBaseHelper::Request(
686 handle
, callback
, priority
, ignore_limits
, flags
, net_log
),
689 const scoped_refptr
<SocketParams
>& params() const { return params_
; }
692 const scoped_refptr
<SocketParams
> params_
;
695 class ConnectJobFactory
{
697 ConnectJobFactory() {}
698 virtual ~ConnectJobFactory() {}
700 virtual scoped_ptr
<ConnectJob
> NewConnectJob(
701 const std::string
& group_name
,
702 const Request
& request
,
703 ConnectJob::Delegate
* delegate
) const = 0;
705 virtual base::TimeDelta
ConnectionTimeout() const = 0;
708 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory
);
711 // |max_sockets| is the maximum number of sockets to be maintained by this
712 // ClientSocketPool. |max_sockets_per_group| specifies the maximum number of
713 // sockets a "group" can have. |unused_idle_socket_timeout| specifies how
714 // long to leave an unused idle socket open before closing it.
715 // |used_idle_socket_timeout| specifies how long to leave a previously used
716 // idle socket open before closing it.
717 ClientSocketPoolBase(HigherLayeredPool
* self
,
719 int max_sockets_per_group
,
720 base::TimeDelta unused_idle_socket_timeout
,
721 base::TimeDelta used_idle_socket_timeout
,
722 ConnectJobFactory
* connect_job_factory
)
725 max_sockets_per_group
,
726 unused_idle_socket_timeout
,
727 used_idle_socket_timeout
,
728 new ConnectJobFactoryAdaptor(connect_job_factory
)) {}
730 virtual ~ClientSocketPoolBase() {}
732 // These member functions simply forward to ClientSocketPoolBaseHelper.
733 void AddLowerLayeredPool(LowerLayeredPool
* lower_pool
) {
734 helper_
.AddLowerLayeredPool(lower_pool
);
737 void AddHigherLayeredPool(HigherLayeredPool
* higher_pool
) {
738 helper_
.AddHigherLayeredPool(higher_pool
);
741 void RemoveHigherLayeredPool(HigherLayeredPool
* higher_pool
) {
742 helper_
.RemoveHigherLayeredPool(higher_pool
);
745 // RequestSocket bundles up the parameters into a Request and then forwards to
746 // ClientSocketPoolBaseHelper::RequestSocket().
747 int RequestSocket(const std::string
& group_name
,
748 const scoped_refptr
<SocketParams
>& params
,
749 RequestPriority priority
,
750 ClientSocketHandle
* handle
,
751 const CompletionCallback
& callback
,
752 const BoundNetLog
& net_log
) {
753 scoped_ptr
<const Request
> request(
754 new Request(handle
, callback
, priority
,
755 internal::ClientSocketPoolBaseHelper::NORMAL
,
756 params
->ignore_limits(),
758 return helper_
.RequestSocket(group_name
, request
.Pass());
761 // RequestSockets bundles up the parameters into a Request and then forwards
762 // to ClientSocketPoolBaseHelper::RequestSockets(). Note that it assigns the
763 // priority to DEFAULT_PRIORITY and specifies the NO_IDLE_SOCKETS flag.
764 void RequestSockets(const std::string
& group_name
,
765 const scoped_refptr
<SocketParams
>& params
,
767 const BoundNetLog
& net_log
) {
768 const Request
request(NULL
/* no handle */,
769 CompletionCallback(),
771 internal::ClientSocketPoolBaseHelper::NO_IDLE_SOCKETS
,
772 params
->ignore_limits(),
775 helper_
.RequestSockets(group_name
, request
, num_sockets
);
778 void CancelRequest(const std::string
& group_name
,
779 ClientSocketHandle
* handle
) {
780 return helper_
.CancelRequest(group_name
, handle
);
783 void ReleaseSocket(const std::string
& group_name
,
784 scoped_ptr
<StreamSocket
> socket
,
786 return helper_
.ReleaseSocket(group_name
, socket
.Pass(), id
);
789 void FlushWithError(int error
) { helper_
.FlushWithError(error
); }
791 bool IsStalled() const { return helper_
.IsStalled(); }
793 void CloseIdleSockets() { return helper_
.CloseIdleSockets(); }
795 int idle_socket_count() const { return helper_
.idle_socket_count(); }
797 int IdleSocketCountInGroup(const std::string
& group_name
) const {
798 return helper_
.IdleSocketCountInGroup(group_name
);
801 LoadState
GetLoadState(const std::string
& group_name
,
802 const ClientSocketHandle
* handle
) const {
803 return helper_
.GetLoadState(group_name
, handle
);
806 virtual void OnConnectJobComplete(int result
, ConnectJob
* job
) {
807 return helper_
.OnConnectJobComplete(result
, job
);
810 int NumUnassignedConnectJobsInGroup(const std::string
& group_name
) const {
811 return helper_
.NumUnassignedConnectJobsInGroup(group_name
);
814 int NumConnectJobsInGroup(const std::string
& group_name
) const {
815 return helper_
.NumConnectJobsInGroup(group_name
);
818 int NumActiveSocketsInGroup(const std::string
& group_name
) const {
819 return helper_
.NumActiveSocketsInGroup(group_name
);
822 bool HasGroup(const std::string
& group_name
) const {
823 return helper_
.HasGroup(group_name
);
826 void CleanupIdleSockets(bool force
) {
827 return helper_
.CleanupIdleSockets(force
);
830 base::DictionaryValue
* GetInfoAsValue(const std::string
& name
,
831 const std::string
& type
) const {
832 return helper_
.GetInfoAsValue(name
, type
);
835 base::TimeDelta
ConnectionTimeout() const {
836 return helper_
.ConnectionTimeout();
839 void EnableConnectBackupJobs() { helper_
.EnableConnectBackupJobs(); }
841 bool CloseOneIdleSocket() { return helper_
.CloseOneIdleSocket(); }
843 bool CloseOneIdleConnectionInHigherLayeredPool() {
844 return helper_
.CloseOneIdleConnectionInHigherLayeredPool();
848 // This adaptor class exists to bridge the
849 // internal::ClientSocketPoolBaseHelper::ConnectJobFactory and
850 // ClientSocketPoolBase::ConnectJobFactory types, allowing clients to use the
851 // typesafe ClientSocketPoolBase::ConnectJobFactory, rather than having to
852 // static_cast themselves.
853 class ConnectJobFactoryAdaptor
854 : public internal::ClientSocketPoolBaseHelper::ConnectJobFactory
{
856 typedef typename ClientSocketPoolBase
<SocketParams
>::ConnectJobFactory
859 explicit ConnectJobFactoryAdaptor(ConnectJobFactory
* connect_job_factory
)
860 : connect_job_factory_(connect_job_factory
) {}
861 ~ConnectJobFactoryAdaptor() override
{}
863 scoped_ptr
<ConnectJob
> NewConnectJob(
864 const std::string
& group_name
,
865 const internal::ClientSocketPoolBaseHelper::Request
& request
,
866 ConnectJob::Delegate
* delegate
) const override
{
867 const Request
& casted_request
= static_cast<const Request
&>(request
);
868 return connect_job_factory_
->NewConnectJob(
869 group_name
, casted_request
, delegate
);
872 base::TimeDelta
ConnectionTimeout() const override
{
873 return connect_job_factory_
->ConnectionTimeout();
876 const scoped_ptr
<ConnectJobFactory
> connect_job_factory_
;
879 internal::ClientSocketPoolBaseHelper helper_
;
881 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBase
);
886 #endif // NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_