cc: Added inline to Tile::IsReadyToDraw
[chromium-blink-merge.git] / net / socket / client_socket_pool_base.h
blob31ec9bf7b131c2f0e789ffe573d8b20f3e7b058a
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 //
5 // A ClientSocketPoolBase is used to restrict the number of sockets open at
6 // a time. It also maintains a list of idle persistent sockets for reuse.
7 // Subclasses of ClientSocketPool should compose ClientSocketPoolBase to handle
8 // the core logic of (1) restricting the number of active (connected or
9 // connecting) sockets per "group" (generally speaking, the hostname), (2)
10 // maintaining a per-group list of idle, persistent sockets for reuse, and (3)
11 // limiting the total number of active sockets in the system.
13 // ClientSocketPoolBase abstracts socket connection details behind ConnectJob,
14 // ConnectJobFactory, and SocketParams. When a socket "slot" becomes available,
15 // the ClientSocketPoolBase will ask the ConnectJobFactory to create a
16 // ConnectJob with a SocketParams. Subclasses of ClientSocketPool should
17 // implement their socket specific connection by subclassing ConnectJob and
18 // implementing ConnectJob::ConnectInternal(). They can control the parameters
19 // passed to each new ConnectJob instance via their ConnectJobFactory subclass
20 // and templated SocketParams parameter.
22 #ifndef NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_
23 #define NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_
25 #include <deque>
26 #include <list>
27 #include <map>
28 #include <set>
29 #include <string>
30 #include <vector>
32 #include "base/basictypes.h"
33 #include "base/memory/ref_counted.h"
34 #include "base/memory/scoped_ptr.h"
35 #include "base/memory/weak_ptr.h"
36 #include "base/time/time.h"
37 #include "base/timer/timer.h"
38 #include "net/base/address_list.h"
39 #include "net/base/completion_callback.h"
40 #include "net/base/load_states.h"
41 #include "net/base/load_timing_info.h"
42 #include "net/base/net_errors.h"
43 #include "net/base/net_export.h"
44 #include "net/base/net_log.h"
45 #include "net/base/network_change_notifier.h"
46 #include "net/base/request_priority.h"
47 #include "net/socket/client_socket_pool.h"
48 #include "net/socket/stream_socket.h"
50 namespace net {
52 class ClientSocketHandle;
54 // ConnectJob provides an abstract interface for "connecting" a socket.
55 // The connection may involve host resolution, tcp connection, ssl connection,
56 // etc.
57 class NET_EXPORT_PRIVATE ConnectJob {
58 public:
59 class NET_EXPORT_PRIVATE Delegate {
60 public:
61 Delegate() {}
62 virtual ~Delegate() {}
64 // Alerts the delegate that the connection completed. |job| must
65 // be destroyed by the delegate. A scoped_ptr<> isn't used because
66 // the caller of this function doesn't own |job|.
67 virtual void OnConnectJobComplete(int result,
68 ConnectJob* job) = 0;
70 private:
71 DISALLOW_COPY_AND_ASSIGN(Delegate);
74 // A |timeout_duration| of 0 corresponds to no timeout.
75 ConnectJob(const std::string& group_name,
76 base::TimeDelta timeout_duration,
77 RequestPriority priority,
78 Delegate* delegate,
79 const BoundNetLog& net_log);
80 virtual ~ConnectJob();
82 // Accessors
83 const std::string& group_name() const { return group_name_; }
84 const BoundNetLog& net_log() { return net_log_; }
86 // Releases ownership of the underlying socket to the caller.
87 // Returns the released socket, or NULL if there was a connection
88 // error.
89 scoped_ptr<StreamSocket> PassSocket();
91 // Begins connecting the socket. Returns OK on success, ERR_IO_PENDING if it
92 // cannot complete synchronously without blocking, or another net error code
93 // on error. In asynchronous completion, the ConnectJob will notify
94 // |delegate_| via OnConnectJobComplete. In both asynchronous and synchronous
95 // completion, ReleaseSocket() can be called to acquire the connected socket
96 // if it succeeded.
97 int Connect();
99 virtual LoadState GetLoadState() const = 0;
101 // If Connect returns an error (or OnConnectJobComplete reports an error
102 // result) this method will be called, allowing the pool to add
103 // additional error state to the ClientSocketHandle (post late-binding).
104 virtual void GetAdditionalErrorState(ClientSocketHandle* handle) {}
106 const LoadTimingInfo::ConnectTiming& connect_timing() const {
107 return connect_timing_;
110 const BoundNetLog& net_log() const { return net_log_; }
112 protected:
113 RequestPriority priority() const { return priority_; }
114 void SetSocket(scoped_ptr<StreamSocket> socket);
115 StreamSocket* socket() { return socket_.get(); }
116 void NotifyDelegateOfCompletion(int rv);
117 void ResetTimer(base::TimeDelta remainingTime);
119 // Connection establishment timing information.
120 LoadTimingInfo::ConnectTiming connect_timing_;
122 private:
123 virtual int ConnectInternal() = 0;
125 void LogConnectStart();
126 void LogConnectCompletion(int net_error);
128 // Alerts the delegate that the ConnectJob has timed out.
129 void OnTimeout();
131 const std::string group_name_;
132 const base::TimeDelta timeout_duration_;
133 // TODO(akalin): Support reprioritization.
134 const RequestPriority priority_;
135 // Timer to abort jobs that take too long.
136 base::OneShotTimer<ConnectJob> timer_;
137 Delegate* delegate_;
138 scoped_ptr<StreamSocket> socket_;
139 BoundNetLog net_log_;
140 // A ConnectJob is idle until Connect() has been called.
141 bool idle_;
143 DISALLOW_COPY_AND_ASSIGN(ConnectJob);
146 namespace internal {
148 // ClientSocketPoolBaseHelper is an internal class that implements almost all
149 // the functionality from ClientSocketPoolBase without using templates.
150 // ClientSocketPoolBase adds templated definitions built on top of
151 // ClientSocketPoolBaseHelper. This class is not for external use, please use
152 // ClientSocketPoolBase instead.
153 class NET_EXPORT_PRIVATE ClientSocketPoolBaseHelper
154 : public ConnectJob::Delegate,
155 public NetworkChangeNotifier::IPAddressObserver {
156 public:
157 typedef uint32 Flags;
159 // Used to specify specific behavior for the ClientSocketPool.
160 enum Flag {
161 NORMAL = 0, // Normal behavior.
162 NO_IDLE_SOCKETS = 0x1, // Do not return an idle socket. Create a new one.
165 class NET_EXPORT_PRIVATE Request {
166 public:
167 Request(ClientSocketHandle* handle,
168 const CompletionCallback& callback,
169 RequestPriority priority,
170 bool ignore_limits,
171 Flags flags,
172 const BoundNetLog& net_log);
174 virtual ~Request();
176 ClientSocketHandle* handle() const { return handle_; }
177 const CompletionCallback& callback() const { return callback_; }
178 RequestPriority priority() const { return priority_; }
179 bool ignore_limits() const { return ignore_limits_; }
180 Flags flags() const { return flags_; }
181 const BoundNetLog& net_log() const { return net_log_; }
183 private:
184 ClientSocketHandle* const handle_;
185 CompletionCallback callback_;
186 // TODO(akalin): Support reprioritization.
187 const RequestPriority priority_;
188 bool ignore_limits_;
189 const Flags flags_;
190 BoundNetLog net_log_;
192 DISALLOW_COPY_AND_ASSIGN(Request);
195 class ConnectJobFactory {
196 public:
197 ConnectJobFactory() {}
198 virtual ~ConnectJobFactory() {}
200 virtual scoped_ptr<ConnectJob> NewConnectJob(
201 const std::string& group_name,
202 const Request& request,
203 ConnectJob::Delegate* delegate) const = 0;
205 virtual base::TimeDelta ConnectionTimeout() const = 0;
207 private:
208 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory);
211 ClientSocketPoolBaseHelper(
212 HigherLayeredPool* pool,
213 int max_sockets,
214 int max_sockets_per_group,
215 base::TimeDelta unused_idle_socket_timeout,
216 base::TimeDelta used_idle_socket_timeout,
217 ConnectJobFactory* connect_job_factory);
219 virtual ~ClientSocketPoolBaseHelper();
221 // Adds a lower layered pool to |this|, and adds |this| as a higher layered
222 // pool on top of |lower_pool|.
223 void AddLowerLayeredPool(LowerLayeredPool* lower_pool);
225 // See LowerLayeredPool::IsStalled for documentation on this function.
226 bool IsStalled() const;
228 // See LowerLayeredPool for documentation on these functions. It is expected
229 // in the destructor that no higher layer pools remain.
230 void AddHigherLayeredPool(HigherLayeredPool* higher_pool);
231 void RemoveHigherLayeredPool(HigherLayeredPool* higher_pool);
233 // See ClientSocketPool::RequestSocket for documentation on this function.
234 int RequestSocket(const std::string& group_name,
235 scoped_ptr<const Request> request);
237 // See ClientSocketPool::RequestSocket for documentation on this function.
238 void RequestSockets(const std::string& group_name,
239 const Request& request,
240 int num_sockets);
242 // See ClientSocketPool::CancelRequest for documentation on this function.
243 void CancelRequest(const std::string& group_name,
244 ClientSocketHandle* handle);
246 // See ClientSocketPool::ReleaseSocket for documentation on this function.
247 void ReleaseSocket(const std::string& group_name,
248 scoped_ptr<StreamSocket> socket,
249 int id);
251 // See ClientSocketPool::FlushWithError for documentation on this function.
252 void FlushWithError(int error);
254 // See ClientSocketPool::CloseIdleSockets for documentation on this function.
255 void CloseIdleSockets();
257 // See ClientSocketPool::IdleSocketCount() for documentation on this function.
258 int idle_socket_count() const {
259 return idle_socket_count_;
262 // See ClientSocketPool::IdleSocketCountInGroup() for documentation on this
263 // function.
264 int IdleSocketCountInGroup(const std::string& group_name) const;
266 // See ClientSocketPool::GetLoadState() for documentation on this function.
267 LoadState GetLoadState(const std::string& group_name,
268 const ClientSocketHandle* handle) const;
270 base::TimeDelta ConnectRetryInterval() const {
271 // TODO(mbelshe): Make this tuned dynamically based on measured RTT.
272 // For now, just use the max retry interval.
273 return base::TimeDelta::FromMilliseconds(
274 ClientSocketPool::kMaxConnectRetryIntervalMs);
277 int NumUnassignedConnectJobsInGroup(const std::string& group_name) const {
278 return group_map_.find(group_name)->second->unassigned_job_count();
281 int NumConnectJobsInGroup(const std::string& group_name) const {
282 return group_map_.find(group_name)->second->jobs().size();
285 int NumActiveSocketsInGroup(const std::string& group_name) const {
286 return group_map_.find(group_name)->second->active_socket_count();
289 bool HasGroup(const std::string& group_name) const;
291 // Called to enable/disable cleaning up idle sockets. When enabled,
292 // idle sockets that have been around for longer than a period defined
293 // by kCleanupInterval are cleaned up using a timer. Otherwise they are
294 // closed next time client makes a request. This may reduce network
295 // activity and power consumption.
296 static bool cleanup_timer_enabled();
297 static bool set_cleanup_timer_enabled(bool enabled);
299 // Closes all idle sockets if |force| is true. Else, only closes idle
300 // sockets that timed out or can't be reused. Made public for testing.
301 void CleanupIdleSockets(bool force);
303 // Closes one idle socket. Picks the first one encountered.
304 // TODO(willchan): Consider a better algorithm for doing this. Perhaps we
305 // should keep an ordered list of idle sockets, and close them in order.
306 // Requires maintaining more state. It's not clear if it's worth it since
307 // I'm not sure if we hit this situation often.
308 bool CloseOneIdleSocket();
310 // Checks higher layered pools to see if they can close an idle connection.
311 bool CloseOneIdleConnectionInHigherLayeredPool();
313 // See ClientSocketPool::GetInfoAsValue for documentation on this function.
314 base::DictionaryValue* GetInfoAsValue(const std::string& name,
315 const std::string& type) const;
317 base::TimeDelta ConnectionTimeout() const {
318 return connect_job_factory_->ConnectionTimeout();
321 static bool connect_backup_jobs_enabled();
322 static bool set_connect_backup_jobs_enabled(bool enabled);
324 void EnableConnectBackupJobs();
326 // ConnectJob::Delegate methods:
327 virtual void OnConnectJobComplete(int result, ConnectJob* job) OVERRIDE;
329 // NetworkChangeNotifier::IPAddressObserver methods:
330 virtual void OnIPAddressChanged() OVERRIDE;
332 private:
333 friend class base::RefCounted<ClientSocketPoolBaseHelper>;
335 // Entry for a persistent socket which became idle at time |start_time|.
336 struct IdleSocket {
337 IdleSocket() : socket(NULL) {}
339 // An idle socket should be removed if it can't be reused, or has been idle
340 // for too long. |now| is the current time value (TimeTicks::Now()).
341 // |timeout| is the length of time to wait before timing out an idle socket.
343 // An idle socket can't be reused if it is disconnected or has received
344 // data unexpectedly (hence no longer idle). The unread data would be
345 // mistaken for the beginning of the next response if we were to reuse the
346 // socket for a new request.
347 bool ShouldCleanup(base::TimeTicks now, base::TimeDelta timeout) const;
349 StreamSocket* socket;
350 base::TimeTicks start_time;
353 typedef std::deque<const Request* > RequestQueue;
354 typedef std::map<const ClientSocketHandle*, const Request*> RequestMap;
356 // A Group is allocated per group_name when there are idle sockets or pending
357 // requests. Otherwise, the Group object is removed from the map.
358 // |active_socket_count| tracks the number of sockets held by clients.
359 class Group {
360 public:
361 Group();
362 ~Group();
364 bool IsEmpty() const {
365 return active_socket_count_ == 0 && idle_sockets_.empty() &&
366 jobs_.empty() && pending_requests_.empty();
369 bool HasAvailableSocketSlot(int max_sockets_per_group) const {
370 return NumActiveSocketSlots() < max_sockets_per_group;
373 int NumActiveSocketSlots() const {
374 return active_socket_count_ + static_cast<int>(jobs_.size()) +
375 static_cast<int>(idle_sockets_.size());
378 bool IsStalledOnPoolMaxSockets(int max_sockets_per_group) const {
379 return HasAvailableSocketSlot(max_sockets_per_group) &&
380 pending_requests_.size() > jobs_.size();
383 RequestPriority TopPendingPriority() const {
384 return pending_requests_.front()->priority();
387 bool HasBackupJob() const { return weak_factory_.HasWeakPtrs(); }
389 void CleanupBackupJob() {
390 weak_factory_.InvalidateWeakPtrs();
393 // Set a timer to create a backup socket if it takes too long to create one.
394 void StartBackupSocketTimer(const std::string& group_name,
395 ClientSocketPoolBaseHelper* pool);
397 // If there's a ConnectJob that's never been assigned to Request,
398 // decrements |unassigned_job_count_| and returns true.
399 // Otherwise, returns false.
400 bool TryToUseUnassignedConnectJob();
402 void AddJob(scoped_ptr<ConnectJob> job, bool is_preconnect);
403 // Remove |job| from this group, which must already own |job|.
404 void RemoveJob(ConnectJob* job);
405 void RemoveAllJobs();
407 bool has_pending_requests() const {
408 return !pending_requests_.empty();
411 size_t pending_request_count() const {
412 return pending_requests_.size();
415 // Gets (but does not remove) the next pending request. Returns
416 // NULL if there are no pending requests.
417 const Request* GetNextPendingRequest() const;
419 // Returns true if there is a connect job for |handle|.
420 bool HasConnectJobForHandle(const ClientSocketHandle* handle) const;
422 // Inserts the request into the queue based on priority
423 // order. Older requests are prioritized over requests of equal
424 // priority.
425 void InsertPendingRequest(scoped_ptr<const Request> r);
427 // Gets and removes the next pending request. Returns NULL if
428 // there are no pending requests.
429 scoped_ptr<const Request> PopNextPendingRequest();
431 // Finds the pending request for |handle| and removes it. Returns
432 // the removed pending request, or NULL if there was none.
433 scoped_ptr<const Request> FindAndRemovePendingRequest(
434 ClientSocketHandle* handle);
436 void IncrementActiveSocketCount() { active_socket_count_++; }
437 void DecrementActiveSocketCount() { active_socket_count_--; }
439 int unassigned_job_count() const { return unassigned_job_count_; }
440 const std::set<ConnectJob*>& jobs() const { return jobs_; }
441 const std::list<IdleSocket>& idle_sockets() const { return idle_sockets_; }
442 int active_socket_count() const { return active_socket_count_; }
443 std::list<IdleSocket>* mutable_idle_sockets() { return &idle_sockets_; }
445 private:
446 // Returns the iterator's pending request after removing it from
447 // the queue.
448 scoped_ptr<const Request> RemovePendingRequest(
449 const RequestQueue::iterator& it);
451 // Called when the backup socket timer fires.
452 void OnBackupSocketTimerFired(
453 std::string group_name,
454 ClientSocketPoolBaseHelper* pool);
456 // Checks that |unassigned_job_count_| does not execeed the number of
457 // ConnectJobs.
458 void SanityCheck();
460 // Total number of ConnectJobs that have never been assigned to a Request.
461 // Since jobs use late binding to requests, which ConnectJobs have or have
462 // not been assigned to a request are not tracked. This is incremented on
463 // preconnect and decremented when a preconnect is assigned, or when there
464 // are fewer than |unassigned_job_count_| ConnectJobs. Not incremented
465 // when a request is cancelled.
466 size_t unassigned_job_count_;
468 std::list<IdleSocket> idle_sockets_;
469 std::set<ConnectJob*> jobs_;
470 RequestQueue pending_requests_;
471 int active_socket_count_; // number of active sockets used by clients
472 // A factory to pin the backup_job tasks.
473 base::WeakPtrFactory<Group> weak_factory_;
476 typedef std::map<std::string, Group*> GroupMap;
478 typedef std::set<ConnectJob*> ConnectJobSet;
480 struct CallbackResultPair {
481 CallbackResultPair();
482 CallbackResultPair(const CompletionCallback& callback_in, int result_in);
483 ~CallbackResultPair();
485 CompletionCallback callback;
486 int result;
489 typedef std::map<const ClientSocketHandle*, CallbackResultPair>
490 PendingCallbackMap;
492 Group* GetOrCreateGroup(const std::string& group_name);
493 void RemoveGroup(const std::string& group_name);
494 void RemoveGroup(GroupMap::iterator it);
496 // Called when the number of idle sockets changes.
497 void IncrementIdleCount();
498 void DecrementIdleCount();
500 // Start cleanup timer for idle sockets.
501 void StartIdleSocketTimer();
503 // Scans the group map for groups which have an available socket slot and
504 // at least one pending request. Returns true if any groups are stalled, and
505 // if so (and if both |group| and |group_name| are not NULL), fills |group|
506 // and |group_name| with data of the stalled group having highest priority.
507 bool FindTopStalledGroup(Group** group, std::string* group_name) const;
509 // Called when timer_ fires. This method scans the idle sockets removing
510 // sockets that timed out or can't be reused.
511 void OnCleanupTimerFired() {
512 CleanupIdleSockets(false);
515 // Removes |job| from |group|, which must already own |job|.
516 void RemoveConnectJob(ConnectJob* job, Group* group);
518 // Tries to see if we can handle any more requests for |group|.
519 void OnAvailableSocketSlot(const std::string& group_name, Group* group);
521 // Process a pending socket request for a group.
522 void ProcessPendingRequest(const std::string& group_name, Group* group);
524 // Assigns |socket| to |handle| and updates |group|'s counters appropriately.
525 void HandOutSocket(scoped_ptr<StreamSocket> socket,
526 bool reused,
527 const LoadTimingInfo::ConnectTiming& connect_timing,
528 ClientSocketHandle* handle,
529 base::TimeDelta time_idle,
530 Group* group,
531 const BoundNetLog& net_log);
533 // Adds |socket| to the list of idle sockets for |group|.
534 void AddIdleSocket(scoped_ptr<StreamSocket> socket, Group* group);
536 // Iterates through |group_map_|, canceling all ConnectJobs and deleting
537 // groups if they are no longer needed.
538 void CancelAllConnectJobs();
540 // Iterates through |group_map_|, posting |error| callbacks for all
541 // requests, and then deleting groups if they are no longer needed.
542 void CancelAllRequestsWithError(int error);
544 // Returns true if we can't create any more sockets due to the total limit.
545 bool ReachedMaxSocketsLimit() const;
547 // This is the internal implementation of RequestSocket(). It differs in that
548 // it does not handle logging into NetLog of the queueing status of
549 // |request|.
550 int RequestSocketInternal(const std::string& group_name,
551 const Request& request);
553 // Assigns an idle socket for the group to the request.
554 // Returns |true| if an idle socket is available, false otherwise.
555 bool AssignIdleSocketToRequest(const Request& request, Group* group);
557 static void LogBoundConnectJobToRequest(
558 const NetLog::Source& connect_job_source, const Request& request);
560 // Same as CloseOneIdleSocket() except it won't close an idle socket in
561 // |group|. If |group| is NULL, it is ignored. Returns true if it closed a
562 // socket.
563 bool CloseOneIdleSocketExceptInGroup(const Group* group);
565 // Checks if there are stalled socket groups that should be notified
566 // for possible wakeup.
567 void CheckForStalledSocketGroups();
569 // Posts a task to call InvokeUserCallback() on the next iteration through the
570 // current message loop. Inserts |callback| into |pending_callback_map_|,
571 // keyed by |handle|.
572 void InvokeUserCallbackLater(
573 ClientSocketHandle* handle, const CompletionCallback& callback, int rv);
575 // Invokes the user callback for |handle|. By the time this task has run,
576 // it's possible that the request has been cancelled, so |handle| may not
577 // exist in |pending_callback_map_|. We look up the callback and result code
578 // in |pending_callback_map_|.
579 void InvokeUserCallback(ClientSocketHandle* handle);
581 // Tries to close idle sockets in a higher level socket pool as long as this
582 // this pool is stalled.
583 void TryToCloseSocketsInLayeredPools();
585 GroupMap group_map_;
587 // Map of the ClientSocketHandles for which we have a pending Task to invoke a
588 // callback. This is necessary since, before we invoke said callback, it's
589 // possible that the request is cancelled.
590 PendingCallbackMap pending_callback_map_;
592 // Timer used to periodically prune idle sockets that timed out or can't be
593 // reused.
594 base::RepeatingTimer<ClientSocketPoolBaseHelper> timer_;
596 // The total number of idle sockets in the system.
597 int idle_socket_count_;
599 // Number of connecting sockets across all groups.
600 int connecting_socket_count_;
602 // Number of connected sockets we handed out across all groups.
603 int handed_out_socket_count_;
605 // The maximum total number of sockets. See ReachedMaxSocketsLimit.
606 const int max_sockets_;
608 // The maximum number of sockets kept per group.
609 const int max_sockets_per_group_;
611 // Whether to use timer to cleanup idle sockets.
612 bool use_cleanup_timer_;
614 // The time to wait until closing idle sockets.
615 const base::TimeDelta unused_idle_socket_timeout_;
616 const base::TimeDelta used_idle_socket_timeout_;
618 const scoped_ptr<ConnectJobFactory> connect_job_factory_;
620 // TODO(vandebo) Remove when backup jobs move to TransportClientSocketPool
621 bool connect_backup_jobs_enabled_;
623 // A unique id for the pool. It gets incremented every time we
624 // FlushWithError() the pool. This is so that when sockets get released back
625 // to the pool, we can make sure that they are discarded rather than reused.
626 int pool_generation_number_;
628 // Used to add |this| as a higher layer pool on top of lower layer pools. May
629 // be NULL if no lower layer pools will be added.
630 HigherLayeredPool* pool_;
632 // Pools that create connections through |this|. |this| will try to close
633 // their idle sockets when it stalls. Must be empty on destruction.
634 std::set<HigherLayeredPool*> higher_pools_;
636 // Pools that this goes through. Typically there's only one, but not always.
637 // |this| will check if they're stalled when it has a new idle socket. |this|
638 // will remove itself from all lower layered pools on destruction.
639 std::set<LowerLayeredPool*> lower_pools_;
641 base::WeakPtrFactory<ClientSocketPoolBaseHelper> weak_factory_;
643 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBaseHelper);
646 } // namespace internal
648 template <typename SocketParams>
649 class ClientSocketPoolBase {
650 public:
651 class Request : public internal::ClientSocketPoolBaseHelper::Request {
652 public:
653 Request(ClientSocketHandle* handle,
654 const CompletionCallback& callback,
655 RequestPriority priority,
656 internal::ClientSocketPoolBaseHelper::Flags flags,
657 bool ignore_limits,
658 const scoped_refptr<SocketParams>& params,
659 const BoundNetLog& net_log)
660 : internal::ClientSocketPoolBaseHelper::Request(
661 handle, callback, priority, ignore_limits, flags, net_log),
662 params_(params) {}
664 const scoped_refptr<SocketParams>& params() const { return params_; }
666 private:
667 const scoped_refptr<SocketParams> params_;
670 class ConnectJobFactory {
671 public:
672 ConnectJobFactory() {}
673 virtual ~ConnectJobFactory() {}
675 virtual scoped_ptr<ConnectJob> NewConnectJob(
676 const std::string& group_name,
677 const Request& request,
678 ConnectJob::Delegate* delegate) const = 0;
680 virtual base::TimeDelta ConnectionTimeout() const = 0;
682 private:
683 DISALLOW_COPY_AND_ASSIGN(ConnectJobFactory);
686 // |max_sockets| is the maximum number of sockets to be maintained by this
687 // ClientSocketPool. |max_sockets_per_group| specifies the maximum number of
688 // sockets a "group" can have. |unused_idle_socket_timeout| specifies how
689 // long to leave an unused idle socket open before closing it.
690 // |used_idle_socket_timeout| specifies how long to leave a previously used
691 // idle socket open before closing it.
692 ClientSocketPoolBase(
693 HigherLayeredPool* self,
694 int max_sockets,
695 int max_sockets_per_group,
696 ClientSocketPoolHistograms* histograms,
697 base::TimeDelta unused_idle_socket_timeout,
698 base::TimeDelta used_idle_socket_timeout,
699 ConnectJobFactory* connect_job_factory)
700 : histograms_(histograms),
701 helper_(self, max_sockets, max_sockets_per_group,
702 unused_idle_socket_timeout, used_idle_socket_timeout,
703 new ConnectJobFactoryAdaptor(connect_job_factory)) {}
705 virtual ~ClientSocketPoolBase() {}
707 // These member functions simply forward to ClientSocketPoolBaseHelper.
708 void AddLowerLayeredPool(LowerLayeredPool* lower_pool) {
709 helper_.AddLowerLayeredPool(lower_pool);
712 void AddHigherLayeredPool(HigherLayeredPool* higher_pool) {
713 helper_.AddHigherLayeredPool(higher_pool);
716 void RemoveHigherLayeredPool(HigherLayeredPool* higher_pool) {
717 helper_.RemoveHigherLayeredPool(higher_pool);
720 // RequestSocket bundles up the parameters into a Request and then forwards to
721 // ClientSocketPoolBaseHelper::RequestSocket().
722 int RequestSocket(const std::string& group_name,
723 const scoped_refptr<SocketParams>& params,
724 RequestPriority priority,
725 ClientSocketHandle* handle,
726 const CompletionCallback& callback,
727 const BoundNetLog& net_log) {
728 scoped_ptr<const Request> request(
729 new Request(handle, callback, priority,
730 internal::ClientSocketPoolBaseHelper::NORMAL,
731 params->ignore_limits(),
732 params, net_log));
733 return helper_.RequestSocket(
734 group_name,
735 request.template PassAs<
736 const internal::ClientSocketPoolBaseHelper::Request>());
739 // RequestSockets bundles up the parameters into a Request and then forwards
740 // to ClientSocketPoolBaseHelper::RequestSockets(). Note that it assigns the
741 // priority to DEFAULT_PRIORITY and specifies the NO_IDLE_SOCKETS flag.
742 void RequestSockets(const std::string& group_name,
743 const scoped_refptr<SocketParams>& params,
744 int num_sockets,
745 const BoundNetLog& net_log) {
746 const Request request(NULL /* no handle */,
747 CompletionCallback(),
748 DEFAULT_PRIORITY,
749 internal::ClientSocketPoolBaseHelper::NO_IDLE_SOCKETS,
750 params->ignore_limits(),
751 params,
752 net_log);
753 helper_.RequestSockets(group_name, request, num_sockets);
756 void CancelRequest(const std::string& group_name,
757 ClientSocketHandle* handle) {
758 return helper_.CancelRequest(group_name, handle);
761 void ReleaseSocket(const std::string& group_name,
762 scoped_ptr<StreamSocket> socket,
763 int id) {
764 return helper_.ReleaseSocket(group_name, socket.Pass(), id);
767 void FlushWithError(int error) { helper_.FlushWithError(error); }
769 bool IsStalled() const { return helper_.IsStalled(); }
771 void CloseIdleSockets() { return helper_.CloseIdleSockets(); }
773 int idle_socket_count() const { return helper_.idle_socket_count(); }
775 int IdleSocketCountInGroup(const std::string& group_name) const {
776 return helper_.IdleSocketCountInGroup(group_name);
779 LoadState GetLoadState(const std::string& group_name,
780 const ClientSocketHandle* handle) const {
781 return helper_.GetLoadState(group_name, handle);
784 virtual void OnConnectJobComplete(int result, ConnectJob* job) {
785 return helper_.OnConnectJobComplete(result, job);
788 int NumUnassignedConnectJobsInGroup(const std::string& group_name) const {
789 return helper_.NumUnassignedConnectJobsInGroup(group_name);
792 int NumConnectJobsInGroup(const std::string& group_name) const {
793 return helper_.NumConnectJobsInGroup(group_name);
796 int NumActiveSocketsInGroup(const std::string& group_name) const {
797 return helper_.NumActiveSocketsInGroup(group_name);
800 bool HasGroup(const std::string& group_name) const {
801 return helper_.HasGroup(group_name);
804 void CleanupIdleSockets(bool force) {
805 return helper_.CleanupIdleSockets(force);
808 base::DictionaryValue* GetInfoAsValue(const std::string& name,
809 const std::string& type) const {
810 return helper_.GetInfoAsValue(name, type);
813 base::TimeDelta ConnectionTimeout() const {
814 return helper_.ConnectionTimeout();
817 ClientSocketPoolHistograms* histograms() const {
818 return histograms_;
821 void EnableConnectBackupJobs() { helper_.EnableConnectBackupJobs(); }
823 bool CloseOneIdleSocket() { return helper_.CloseOneIdleSocket(); }
825 bool CloseOneIdleConnectionInHigherLayeredPool() {
826 return helper_.CloseOneIdleConnectionInHigherLayeredPool();
829 private:
830 // This adaptor class exists to bridge the
831 // internal::ClientSocketPoolBaseHelper::ConnectJobFactory and
832 // ClientSocketPoolBase::ConnectJobFactory types, allowing clients to use the
833 // typesafe ClientSocketPoolBase::ConnectJobFactory, rather than having to
834 // static_cast themselves.
835 class ConnectJobFactoryAdaptor
836 : public internal::ClientSocketPoolBaseHelper::ConnectJobFactory {
837 public:
838 typedef typename ClientSocketPoolBase<SocketParams>::ConnectJobFactory
839 ConnectJobFactory;
841 explicit ConnectJobFactoryAdaptor(ConnectJobFactory* connect_job_factory)
842 : connect_job_factory_(connect_job_factory) {}
843 virtual ~ConnectJobFactoryAdaptor() {}
845 virtual scoped_ptr<ConnectJob> NewConnectJob(
846 const std::string& group_name,
847 const internal::ClientSocketPoolBaseHelper::Request& request,
848 ConnectJob::Delegate* delegate) const OVERRIDE {
849 const Request& casted_request = static_cast<const Request&>(request);
850 return connect_job_factory_->NewConnectJob(
851 group_name, casted_request, delegate);
854 virtual base::TimeDelta ConnectionTimeout() const {
855 return connect_job_factory_->ConnectionTimeout();
858 const scoped_ptr<ConnectJobFactory> connect_job_factory_;
861 // Histograms for the pool
862 ClientSocketPoolHistograms* const histograms_;
863 internal::ClientSocketPoolBaseHelper helper_;
865 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolBase);
868 } // namespace net
870 #endif // NET_SOCKET_CLIENT_SOCKET_POOL_BASE_H_