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 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
;
349 friend class base::RefCounted
<ClientSocketPoolBaseHelper
>;
351 // Entry for a persistent socket which became idle at time |start_time|.
353 IdleSocket() : socket(NULL
) {}
355 // An idle socket can't be used if it is disconnected or has been used
356 // before and has received data unexpectedly (hence no longer idle). The
357 // unread data would be mistaken for the beginning of the next response if
358 // we were to use the socket for a new request.
360 // Note that a socket that has never been used before (like a preconnected
361 // socket) may be used even with unread data. This may be, e.g., a SPDY
363 bool IsUsable() const;
365 // An idle socket should be removed if it can't be reused, or has been idle
366 // for too long. |now| is the current time value (TimeTicks::Now()).
367 // |timeout| is the length of time to wait before timing out an idle socket.
368 bool ShouldCleanup(base::TimeTicks now
, base::TimeDelta timeout
) const;
370 StreamSocket
* socket
;
371 base::TimeTicks start_time
;
374 typedef PriorityQueue
<const Request
*> RequestQueue
;
375 typedef std::map
<const ClientSocketHandle
*, const Request
*> RequestMap
;
377 // A Group is allocated per group_name when there are idle sockets or pending
378 // requests. Otherwise, the Group object is removed from the map.
379 // |active_socket_count| tracks the number of sockets held by clients.
385 bool IsEmpty() const {
386 return active_socket_count_
== 0 && idle_sockets_
.empty() &&
387 jobs_
.empty() && pending_requests_
.empty();
390 bool HasAvailableSocketSlot(int max_sockets_per_group
) const {
391 return NumActiveSocketSlots() < max_sockets_per_group
;
394 int NumActiveSocketSlots() const {
395 return active_socket_count_
+ static_cast<int>(jobs_
.size()) +
396 static_cast<int>(idle_sockets_
.size());
399 // Returns true if the group could make use of an additional socket slot, if
400 // it were given one.
401 bool CanUseAdditionalSocketSlot(int max_sockets_per_group
) const {
402 return HasAvailableSocketSlot(max_sockets_per_group
) &&
403 pending_requests_
.size() > jobs_
.size();
406 // Returns the priority of the top of the pending request queue
407 // (which may be less than the maximum priority over the entire
408 // queue, due to how we prioritize requests with |ignore_limits|
410 RequestPriority
TopPendingPriority() const {
411 // NOTE: FirstMax().value()->priority() is not the same as
412 // FirstMax().priority()!
413 return pending_requests_
.FirstMax().value()->priority();
416 // Set a timer to create a backup job if it takes too long to
417 // create one and if a timer isn't already running.
418 void StartBackupJobTimer(const std::string
& group_name
,
419 ClientSocketPoolBaseHelper
* pool
);
421 bool BackupJobTimerIsRunning() const;
423 // If there's a ConnectJob that's never been assigned to Request,
424 // decrements |unassigned_job_count_| and returns true.
425 // Otherwise, returns false.
426 bool TryToUseUnassignedConnectJob();
428 void AddJob(scoped_ptr
<ConnectJob
> job
, bool is_preconnect
);
429 // Remove |job| from this group, which must already own |job|.
430 void RemoveJob(ConnectJob
* job
);
431 void RemoveAllJobs();
433 bool has_pending_requests() const {
434 return !pending_requests_
.empty();
437 size_t pending_request_count() const {
438 return pending_requests_
.size();
441 // Gets (but does not remove) the next pending request. Returns
442 // NULL if there are no pending requests.
443 const Request
* GetNextPendingRequest() const;
445 // Returns true if there is a connect job for |handle|.
446 bool HasConnectJobForHandle(const ClientSocketHandle
* handle
) const;
448 // Inserts the request into the queue based on priority
449 // order. Older requests are prioritized over requests of equal
451 void InsertPendingRequest(scoped_ptr
<const Request
> request
);
453 // Gets and removes the next pending request. Returns NULL if
454 // there are no pending requests.
455 scoped_ptr
<const Request
> PopNextPendingRequest();
457 // Finds the pending request for |handle| and removes it. Returns
458 // the removed pending request, or NULL if there was none.
459 scoped_ptr
<const Request
> FindAndRemovePendingRequest(
460 ClientSocketHandle
* handle
);
462 void IncrementActiveSocketCount() { active_socket_count_
++; }
463 void DecrementActiveSocketCount() { active_socket_count_
--; }
465 int unassigned_job_count() const { return unassigned_job_count_
; }
466 const std::list
<ConnectJob
*>& jobs() const { return jobs_
; }
467 const std::list
<IdleSocket
>& idle_sockets() const { return idle_sockets_
; }
468 int active_socket_count() const { return active_socket_count_
; }
469 std::list
<IdleSocket
>* mutable_idle_sockets() { return &idle_sockets_
; }
472 // Returns the iterator's pending request after removing it from
474 scoped_ptr
<const Request
> RemovePendingRequest(
475 const RequestQueue::Pointer
& pointer
);
477 // Called when the backup socket timer fires.
478 void OnBackupJobTimerFired(
479 std::string group_name
,
480 ClientSocketPoolBaseHelper
* pool
);
482 // Checks that |unassigned_job_count_| does not execeed the number of
486 // Total number of ConnectJobs that have never been assigned to a Request.
487 // Since jobs use late binding to requests, which ConnectJobs have or have
488 // not been assigned to a request are not tracked. This is incremented on
489 // preconnect and decremented when a preconnect is assigned, or when there
490 // are fewer than |unassigned_job_count_| ConnectJobs. Not incremented
491 // when a request is cancelled.
492 size_t unassigned_job_count_
;
494 std::list
<IdleSocket
> idle_sockets_
;
495 std::list
<ConnectJob
*> jobs_
;
496 RequestQueue pending_requests_
;
497 int active_socket_count_
; // number of active sockets used by clients
498 // A timer for when to start the backup job.
499 base::OneShotTimer
<Group
> backup_job_timer_
;
502 typedef std::map
<std::string
, Group
*> GroupMap
;
504 typedef std::set
<ConnectJob
*> ConnectJobSet
;
506 struct CallbackResultPair
{
507 CallbackResultPair();
508 CallbackResultPair(const CompletionCallback
& callback_in
, int result_in
);
509 ~CallbackResultPair();
511 CompletionCallback callback
;
515 typedef std::map
<const ClientSocketHandle
*, CallbackResultPair
>
518 Group
* GetOrCreateGroup(const std::string
& group_name
);
519 void RemoveGroup(const std::string
& group_name
);
520 void RemoveGroup(GroupMap::iterator it
);
522 // Called when the number of idle sockets changes.
523 void IncrementIdleCount();
524 void DecrementIdleCount();
526 // Start cleanup timer for idle sockets.
527 void StartIdleSocketTimer();
529 // Scans the group map for groups which have an available socket slot and
530 // at least one pending request. Returns true if any groups are stalled, and
531 // if so (and if both |group| and |group_name| are not NULL), fills |group|
532 // and |group_name| with data of the stalled group having highest priority.
533 bool FindTopStalledGroup(Group
** group
, std::string
* group_name
) const;
535 // Called when timer_ fires. This method scans the idle sockets removing
536 // sockets that timed out or can't be reused.
537 void OnCleanupTimerFired() {
538 CleanupIdleSockets(false);
541 // Removes |job| from |group|, which must already own |job|.
542 void RemoveConnectJob(ConnectJob
* job
, Group
* group
);
544 // Tries to see if we can handle any more requests for |group|.
545 void OnAvailableSocketSlot(const std::string
& group_name
, Group
* group
);
547 // Process a pending socket request for a group.
548 void ProcessPendingRequest(const std::string
& group_name
, Group
* group
);
550 // Assigns |socket| to |handle| and updates |group|'s counters appropriately.
551 void HandOutSocket(scoped_ptr
<StreamSocket
> socket
,
552 ClientSocketHandle::SocketReuseType reuse_type
,
553 const LoadTimingInfo::ConnectTiming
& connect_timing
,
554 ClientSocketHandle
* handle
,
555 base::TimeDelta time_idle
,
557 const BoundNetLog
& net_log
);
559 // Adds |socket| to the list of idle sockets for |group|.
560 void AddIdleSocket(scoped_ptr
<StreamSocket
> socket
, Group
* group
);
562 // Iterates through |group_map_|, canceling all ConnectJobs and deleting
563 // groups if they are no longer needed.
564 void CancelAllConnectJobs();
566 // Iterates through |group_map_|, posting |error| callbacks for all
567 // requests, and then deleting groups if they are no longer needed.
568 void CancelAllRequestsWithError(int error
);
570 // Returns true if we can't create any more sockets due to the total limit.
571 bool ReachedMaxSocketsLimit() const;
573 // This is the internal implementation of RequestSocket(). It differs in that
574 // it does not handle logging into NetLog of the queueing status of
576 int RequestSocketInternal(const std::string
& group_name
,
577 const Request
& request
);
579 // Assigns an idle socket for the group to the request.
580 // Returns |true| if an idle socket is available, false otherwise.
581 bool AssignIdleSocketToRequest(const Request
& request
, Group
* group
);
583 static void LogBoundConnectJobToRequest(
584 const NetLog::Source
& connect_job_source
, const Request
& request
);
586 // Same as CloseOneIdleSocket() except it won't close an idle socket in
587 // |group|. If |group| is NULL, it is ignored. Returns true if it closed a
589 bool CloseOneIdleSocketExceptInGroup(const Group
* group
);
591 // Checks if there are stalled socket groups that should be notified
592 // for possible wakeup.
593 void CheckForStalledSocketGroups();
595 // Posts a task to call InvokeUserCallback() on the next iteration through the
596 // current message loop. Inserts |callback| into |pending_callback_map_|,
597 // keyed by |handle|.
598 void InvokeUserCallbackLater(
599 ClientSocketHandle
* handle
, const CompletionCallback
& callback
, int rv
);
601 // Invokes the user callback for |handle|. By the time this task has run,
602 // it's possible that the request has been cancelled, so |handle| may not
603 // exist in |pending_callback_map_|. We look up the callback and result code
604 // in |pending_callback_map_|.
605 void InvokeUserCallback(ClientSocketHandle
* handle
);
607 // Tries to close idle sockets in a higher level socket pool as long as this
608 // this pool is stalled.
609 void TryToCloseSocketsInLayeredPools();
613 // Map of the ClientSocketHandles for which we have a pending Task to invoke a
614 // callback. This is necessary since, before we invoke said callback, it's
615 // possible that the request is cancelled.
616 PendingCallbackMap pending_callback_map_
;
618 // Timer used to periodically prune idle sockets that timed out or can't be
620 base::RepeatingTimer
<ClientSocketPoolBaseHelper
> timer_
;
622 // The total number of idle sockets in the system.
623 int idle_socket_count_
;
625 // Number of connecting sockets across all groups.
626 int connecting_socket_count_
;
628 // Number of connected sockets we handed out across all groups.
629 int handed_out_socket_count_
;
631 // The maximum total number of sockets. See ReachedMaxSocketsLimit.
632 const int max_sockets_
;
634 // The maximum number of sockets kept per group.
635 const int max_sockets_per_group_
;
637 // Whether to use timer to cleanup idle sockets.
638 bool use_cleanup_timer_
;
640 // The time to wait until closing idle sockets.
641 const base::TimeDelta unused_idle_socket_timeout_
;
642 const base::TimeDelta used_idle_socket_timeout_
;
644 const scoped_ptr
<ConnectJobFactory
> connect_job_factory_
;
646 // TODO(vandebo) Remove when backup jobs move to TransportClientSocketPool
647 bool connect_backup_jobs_enabled_
;
649 // A unique id for the pool. It gets incremented every time we
650 // FlushWithError() the pool. This is so that when sockets get released back
651 // to the pool, we can make sure that they are discarded rather than reused.
652 int pool_generation_number_
;
654 // Used to add |this| as a higher layer pool on top of lower layer pools. May
655 // be NULL if no lower layer pools will be added.
656 HigherLayeredPool
* pool_
;
658 // Pools that create connections through |this|. |this| will try to close
659 // their idle sockets when it stalls. Must be empty on destruction.
660 std::set
<HigherLayeredPool
*> higher_pools_
;
662 // Pools that this goes through. Typically there's only one, but not always.
663 // |this| will check if they're stalled when it has a new idle socket. |this|
664 // will remove itself from all lower layered pools on destruction.
665 std::set
<LowerLayeredPool
*> lower_pools_
;
667 base::WeakPtrFactory
<ClientSocketPoolBaseHelper
> weak_factory_
;
669 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBaseHelper
);
672 } // namespace internal
674 template <typename SocketParams
>
675 class ClientSocketPoolBase
{
677 class Request
: public internal::ClientSocketPoolBaseHelper::Request
{
679 Request(ClientSocketHandle
* handle
,
680 const CompletionCallback
& callback
,
681 RequestPriority priority
,
682 internal::ClientSocketPoolBaseHelper::Flags flags
,
684 const scoped_refptr
<SocketParams
>& params
,
685 const BoundNetLog
& net_log
)
686 : internal::ClientSocketPoolBaseHelper::Request(
687 handle
, callback
, priority
, ignore_limits
, flags
, net_log
),
690 const scoped_refptr
<SocketParams
>& params() const { return params_
; }
693 const scoped_refptr
<SocketParams
> params_
;
696 class ConnectJobFactory
{
698 ConnectJobFactory() {}
699 virtual ~ConnectJobFactory() {}
701 virtual scoped_ptr
<ConnectJob
> NewConnectJob(
702 const std::string
& group_name
,
703 const Request
& request
,
704 ConnectJob::Delegate
* delegate
) const = 0;
706 virtual base::TimeDelta
ConnectionTimeout() const = 0;
709 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory
);
712 // |max_sockets| is the maximum number of sockets to be maintained by this
713 // ClientSocketPool. |max_sockets_per_group| specifies the maximum number of
714 // sockets a "group" can have. |unused_idle_socket_timeout| specifies how
715 // long to leave an unused idle socket open before closing it.
716 // |used_idle_socket_timeout| specifies how long to leave a previously used
717 // idle socket open before closing it.
718 ClientSocketPoolBase(HigherLayeredPool
* self
,
720 int max_sockets_per_group
,
721 base::TimeDelta unused_idle_socket_timeout
,
722 base::TimeDelta used_idle_socket_timeout
,
723 ConnectJobFactory
* connect_job_factory
)
726 max_sockets_per_group
,
727 unused_idle_socket_timeout
,
728 used_idle_socket_timeout
,
729 new ConnectJobFactoryAdaptor(connect_job_factory
)) {}
731 virtual ~ClientSocketPoolBase() {}
733 // These member functions simply forward to ClientSocketPoolBaseHelper.
734 void AddLowerLayeredPool(LowerLayeredPool
* lower_pool
) {
735 helper_
.AddLowerLayeredPool(lower_pool
);
738 void AddHigherLayeredPool(HigherLayeredPool
* higher_pool
) {
739 helper_
.AddHigherLayeredPool(higher_pool
);
742 void RemoveHigherLayeredPool(HigherLayeredPool
* higher_pool
) {
743 helper_
.RemoveHigherLayeredPool(higher_pool
);
746 // RequestSocket bundles up the parameters into a Request and then forwards to
747 // ClientSocketPoolBaseHelper::RequestSocket().
748 int RequestSocket(const std::string
& group_name
,
749 const scoped_refptr
<SocketParams
>& params
,
750 RequestPriority priority
,
751 ClientSocketHandle
* handle
,
752 const CompletionCallback
& callback
,
753 const BoundNetLog
& net_log
) {
754 scoped_ptr
<const Request
> request(
755 new Request(handle
, callback
, priority
,
756 internal::ClientSocketPoolBaseHelper::NORMAL
,
757 params
->ignore_limits(),
759 return helper_
.RequestSocket(group_name
, request
.Pass());
762 // RequestSockets bundles up the parameters into a Request and then forwards
763 // to ClientSocketPoolBaseHelper::RequestSockets(). Note that it assigns the
764 // priority to DEFAULT_PRIORITY and specifies the NO_IDLE_SOCKETS flag.
765 void RequestSockets(const std::string
& group_name
,
766 const scoped_refptr
<SocketParams
>& params
,
768 const BoundNetLog
& net_log
) {
769 const Request
request(NULL
/* no handle */,
770 CompletionCallback(),
772 internal::ClientSocketPoolBaseHelper::NO_IDLE_SOCKETS
,
773 params
->ignore_limits(),
776 helper_
.RequestSockets(group_name
, request
, num_sockets
);
779 void CancelRequest(const std::string
& group_name
,
780 ClientSocketHandle
* handle
) {
781 return helper_
.CancelRequest(group_name
, handle
);
784 void ReleaseSocket(const std::string
& group_name
,
785 scoped_ptr
<StreamSocket
> socket
,
787 return helper_
.ReleaseSocket(group_name
, socket
.Pass(), id
);
790 void FlushWithError(int error
) { helper_
.FlushWithError(error
); }
792 bool IsStalled() const { return helper_
.IsStalled(); }
794 void CloseIdleSockets() { return helper_
.CloseIdleSockets(); }
796 int idle_socket_count() const { return helper_
.idle_socket_count(); }
798 int IdleSocketCountInGroup(const std::string
& group_name
) const {
799 return helper_
.IdleSocketCountInGroup(group_name
);
802 LoadState
GetLoadState(const std::string
& group_name
,
803 const ClientSocketHandle
* handle
) const {
804 return helper_
.GetLoadState(group_name
, handle
);
807 virtual void OnConnectJobComplete(int result
, ConnectJob
* job
) {
808 return helper_
.OnConnectJobComplete(result
, job
);
811 int NumUnassignedConnectJobsInGroup(const std::string
& group_name
) const {
812 return helper_
.NumUnassignedConnectJobsInGroup(group_name
);
815 int NumConnectJobsInGroup(const std::string
& group_name
) const {
816 return helper_
.NumConnectJobsInGroup(group_name
);
819 int NumActiveSocketsInGroup(const std::string
& group_name
) const {
820 return helper_
.NumActiveSocketsInGroup(group_name
);
823 bool HasGroup(const std::string
& group_name
) const {
824 return helper_
.HasGroup(group_name
);
827 void CleanupIdleSockets(bool force
) {
828 return helper_
.CleanupIdleSockets(force
);
831 scoped_ptr
<base::DictionaryValue
> GetInfoAsValue(const std::string
& name
,
832 const std::string
& type
) const {
833 return helper_
.GetInfoAsValue(name
, type
);
836 base::TimeDelta
ConnectionTimeout() const {
837 return helper_
.ConnectionTimeout();
840 void EnableConnectBackupJobs() { helper_
.EnableConnectBackupJobs(); }
842 bool CloseOneIdleSocket() { return helper_
.CloseOneIdleSocket(); }
844 bool CloseOneIdleConnectionInHigherLayeredPool() {
845 return helper_
.CloseOneIdleConnectionInHigherLayeredPool();
849 // This adaptor class exists to bridge the
850 // internal::ClientSocketPoolBaseHelper::ConnectJobFactory and
851 // ClientSocketPoolBase::ConnectJobFactory types, allowing clients to use the
852 // typesafe ClientSocketPoolBase::ConnectJobFactory, rather than having to
853 // static_cast themselves.
854 class ConnectJobFactoryAdaptor
855 : public internal::ClientSocketPoolBaseHelper::ConnectJobFactory
{
857 typedef typename ClientSocketPoolBase
<SocketParams
>::ConnectJobFactory
860 explicit ConnectJobFactoryAdaptor(ConnectJobFactory
* connect_job_factory
)
861 : connect_job_factory_(connect_job_factory
) {}
862 ~ConnectJobFactoryAdaptor() override
{}
864 scoped_ptr
<ConnectJob
> NewConnectJob(
865 const std::string
& group_name
,
866 const internal::ClientSocketPoolBaseHelper::Request
& request
,
867 ConnectJob::Delegate
* delegate
) const override
{
868 const Request
& casted_request
= static_cast<const Request
&>(request
);
869 return connect_job_factory_
->NewConnectJob(
870 group_name
, casted_request
, delegate
);
873 base::TimeDelta
ConnectionTimeout() const override
{
874 return connect_job_factory_
->ConnectionTimeout();
877 const scoped_ptr
<ConnectJobFactory
> connect_job_factory_
;
880 internal::ClientSocketPoolBaseHelper helper_
;
882 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBase
);
887 #endif // NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_