summaryrefslogtreecommitdiffstats
path: root/net/base
diff options
context:
space:
mode:
authordarin@google.com <darin@google.com@0039d316-1c4b-4281-b951-d872f2087c98>2008-08-06 23:57:07 +0000
committerdarin@google.com <darin@google.com@0039d316-1c4b-4281-b951-d872f2087c98>2008-08-06 23:57:07 +0000
commite1e0626250c6accd6e72168636630ce2aedf4953 (patch)
tree0b6206aac9e8140eba48f6bb1e261926d448f1eb /net/base
parent78b02d540d5d4ee753b319b4811842273be9d509 (diff)
downloadchromium_src-e1e0626250c6accd6e72168636630ce2aedf4953.zip
chromium_src-e1e0626250c6accd6e72168636630ce2aedf4953.tar.gz
chromium_src-e1e0626250c6accd6e72168636630ce2aedf4953.tar.bz2
Rename HttpConnection to ClientSocketHandle, and rename HttpConnectionManager to ClientSocketPool.
The max number of sockets per group is now a constructor argument to ClientSocketPool. I also changed the API on the pool to take ClientSocketHandle pointers. The former SocketHandle typedef is now a private ClientSocketPtr typedef for use within the implementation of ClientSocketPool. git-svn-id: svn://svn.chromium.org/chrome/trunk/src@471 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'net/base')
-rw-r--r--net/base/client_socket_handle.cc64
-rw-r--r--net/base/client_socket_handle.h102
-rw-r--r--net/base/client_socket_pool.cc209
-rw-r--r--net/base/client_socket_pool.h148
-rw-r--r--net/base/client_socket_pool_unittest.cc272
5 files changed, 795 insertions, 0 deletions
diff --git a/net/base/client_socket_handle.cc b/net/base/client_socket_handle.cc
new file mode 100644
index 0000000..a7b668e
--- /dev/null
+++ b/net/base/client_socket_handle.cc
@@ -0,0 +1,64 @@
+// Copyright 2008, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include "net/base/client_socket_handle.h"
+
+#include "net/base/client_socket.h"
+#include "net/base/client_socket_pool.h"
+
+namespace net {
+
+ClientSocketHandle::ClientSocketHandle(ClientSocketPool* pool)
+ : pool_(pool), socket_(NULL) {
+}
+
+ClientSocketHandle::~ClientSocketHandle() {
+ Reset();
+}
+
+int ClientSocketHandle::Init(const std::string& group_name,
+ CompletionCallback* callback) {
+ Reset();
+ group_name_ = group_name;
+ return pool_->RequestSocket(this, callback);
+}
+
+void ClientSocketHandle::Reset() {
+ if (group_name_.empty()) // Was Init called?
+ return;
+ if (socket_) {
+ pool_->ReleaseSocket(this);
+ socket_ = NULL;
+ } else {
+ pool_->CancelRequest(this);
+ }
+ group_name_.clear();
+}
+
+} // namespace net
diff --git a/net/base/client_socket_handle.h b/net/base/client_socket_handle.h
new file mode 100644
index 0000000..f5cab7f
--- /dev/null
+++ b/net/base/client_socket_handle.h
@@ -0,0 +1,102 @@
+// Copyright 2008, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef NET_BASE_CLIENT_SOCKET_HANDLE_H_
+#define NET_BASE_CLIENT_SOCKET_HANDLE_H_
+
+#include <string>
+
+#include "base/ref_counted.h"
+#include "base/scoped_ptr.h"
+#include "net/base/client_socket.h"
+#include "net/base/completion_callback.h"
+
+namespace net {
+
+class ClientSocketPool;
+
+// A container for a connected ClientSocket.
+//
+// The handle's |group_name| uniquely identifies the origin and type of the
+// connection. It is used by the ClientSocketPool to group similar connected
+// client socket objects.
+//
+// A handle is initialized with a null socket. It is the consumer's job to
+// initialize a ClientSocket object and set it on the handle.
+//
+class ClientSocketHandle {
+ public:
+ explicit ClientSocketHandle(ClientSocketPool* pool);
+ ~ClientSocketHandle();
+
+ // Initializes a ClientSocketHandle object, which involves talking to the
+ // ClientSocketPool to locate a socket to possibly reuse. This method
+ // returns either OK or ERR_IO_PENDING.
+ //
+ // If this method succeeds, then the socket member will be set to an existing
+ // socket if an existing socket was available to reuse. Otherwise, the
+ // consumer should set the socket member of this handle.
+ //
+ // This method returns ERR_IO_PENDING if it cannot complete synchronously, in
+ // which case the consumer should wait for the completion callback to run.
+ //
+ // Init may be called multiple times.
+ //
+ int Init(const std::string& group_name, CompletionCallback* callback);
+
+ // An initialized handle can be reset, which causes it to return to the
+ // un-initialized state. This releases the underlying socket, which in the
+ // case of a socket that still has an established connection, indicates that
+ // the socket may be kept alive for use by a subsequent ClientSocketHandle.
+ //
+ // NOTE: To prevent the socket from being kept alive, be sure to call its
+ // Disconnect method.
+ //
+ void Reset();
+
+ // Returns true when Init has completed successfully.
+ bool is_initialized() const { return socket_ != NULL; }
+
+ // These may only be used if is_initialized() is true.
+ ClientSocket* socket() { return socket_->get(); }
+ void set_socket(ClientSocket* s) { socket_->reset(s); }
+
+ private:
+ friend class ClientSocketPool;
+
+ scoped_refptr<ClientSocketPool> pool_;
+ scoped_ptr<ClientSocket>* socket_;
+ std::string group_name_;
+
+ DISALLOW_COPY_AND_ASSIGN(ClientSocketHandle);
+};
+
+} // namespace net
+
+#endif // NET_BASE_CLIENT_SOCKET_HANDLE_H_
diff --git a/net/base/client_socket_pool.cc b/net/base/client_socket_pool.cc
new file mode 100644
index 0000000..fb81dce
--- /dev/null
+++ b/net/base/client_socket_pool.cc
@@ -0,0 +1,209 @@
+// Copyright 2008, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include "net/base/client_socket_pool.h"
+
+#include "base/message_loop.h"
+#include "net/base/client_socket.h"
+#include "net/base/client_socket_handle.h"
+#include "net/base/net_errors.h"
+
+namespace {
+
+// The timeout value, in seconds, used to clean up disconnected idle sockets.
+const int kCleanupInterval = 5;
+
+} // namespace
+
+namespace net {
+
+ClientSocketPool::ClientSocketPool(int max_sockets_per_group)
+ : timer_(TimeDelta::FromSeconds(kCleanupInterval)),
+ idle_socket_count_(0),
+ max_sockets_per_group_(max_sockets_per_group) {
+ timer_.set_task(this);
+}
+
+ClientSocketPool::~ClientSocketPool() {
+ timer_.set_task(NULL);
+
+ // Clean up any idle sockets. Assert that we have no remaining active sockets
+ // or pending requests. They should have all been cleaned up prior to the
+ // manager being destroyed.
+
+ CloseIdleSockets();
+ DCHECK(group_map_.empty());
+}
+
+int ClientSocketPool::RequestSocket(ClientSocketHandle* handle,
+ CompletionCallback* callback) {
+ Group& group = group_map_[handle->group_name_];
+
+ // Can we make another active socket now?
+ if (group.active_socket_count == max_sockets_per_group_) {
+ Request r;
+ r.handle = handle;
+ DCHECK(callback);
+ r.callback = callback;
+ group.pending_requests.push_back(r);
+ return ERR_IO_PENDING;
+ }
+
+ // OK, we are going to activate one.
+ group.active_socket_count++;
+
+ // Use idle sockets in LIFO order because they're more likely to be
+ // still connected.
+ while (!group.idle_sockets.empty()) {
+ ClientSocketPtr* ptr = group.idle_sockets.back();
+ group.idle_sockets.pop_back();
+ DecrementIdleCount();
+ if ((*ptr)->IsConnected()) {
+ // We found one we can reuse!
+ handle->socket_ = ptr;
+ return OK;
+ }
+ delete ptr;
+ }
+
+ handle->socket_ = new ClientSocketPtr();
+ return OK;
+}
+
+void ClientSocketPool::CancelRequest(ClientSocketHandle* handle) {
+ Group& group = group_map_[handle->group_name_];
+
+ // In order for us to be canceling a pending request, we must have active
+ // sockets equaling the limit. NOTE: The correctness of the code doesn't
+ // require this assertion.
+ DCHECK(group.active_socket_count == max_sockets_per_group_);
+
+ // Search pending_requests for matching handle.
+ std::deque<Request>::iterator it = group.pending_requests.begin();
+ for (; it != group.pending_requests.end(); ++it) {
+ if (it->handle == handle) {
+ group.pending_requests.erase(it);
+ break;
+ }
+ }
+}
+
+void ClientSocketPool::ReleaseSocket(ClientSocketHandle* handle) {
+ // Run this asynchronously to allow the caller to finish before we let
+ // another to begin doing work. This also avoids nasty recursion issues.
+ // NOTE: We cannot refer to the handle argument after this method returns.
+ MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
+ this, &ClientSocketPool::DoReleaseSocket, handle->group_name_,
+ handle->socket_));
+}
+
+void ClientSocketPool::CloseIdleSockets() {
+ MaybeCloseIdleSockets(false);
+}
+
+void ClientSocketPool::MaybeCloseIdleSockets(
+ bool only_if_disconnected) {
+ if (idle_socket_count_ == 0)
+ return;
+
+ GroupMap::iterator i = group_map_.begin();
+ while (i != group_map_.end()) {
+ Group& group = i->second;
+
+ std::deque<ClientSocketPtr*>::iterator j = group.idle_sockets.begin();
+ while (j != group.idle_sockets.end()) {
+ if (!only_if_disconnected || !(*j)->get()->IsConnected()) {
+ delete *j;
+ j = group.idle_sockets.erase(j);
+ DecrementIdleCount();
+ } else {
+ ++j;
+ }
+ }
+
+ // Delete group if no longer needed.
+ if (group.active_socket_count == 0 && group.idle_sockets.empty()) {
+ DCHECK(group.pending_requests.empty());
+ group_map_.erase(i++);
+ } else {
+ ++i;
+ }
+ }
+}
+
+void ClientSocketPool::IncrementIdleCount() {
+ if (++idle_socket_count_ == 1)
+ timer_.Start();
+}
+
+void ClientSocketPool::DecrementIdleCount() {
+ if (--idle_socket_count_ == 0)
+ timer_.Stop();
+}
+
+void ClientSocketPool::DoReleaseSocket(const std::string& group_name,
+ ClientSocketPtr* ptr) {
+ GroupMap::iterator i = group_map_.find(group_name);
+ DCHECK(i != group_map_.end());
+
+ Group& group = i->second;
+
+ DCHECK(group.active_socket_count > 0);
+ group.active_socket_count--;
+
+ bool can_reuse = ptr->get() && (*ptr)->IsConnected();
+ if (can_reuse) {
+ group.idle_sockets.push_back(ptr);
+ IncrementIdleCount();
+ } else {
+ delete ptr;
+ }
+
+ // Process one pending request.
+ if (!group.pending_requests.empty()) {
+ Request r = group.pending_requests.front();
+ group.pending_requests.pop_front();
+ int rv = RequestSocket(r.handle, NULL);
+ DCHECK(rv == OK);
+ r.callback->Run(rv);
+ return;
+ }
+
+ // Delete group if no longer needed.
+ if (group.active_socket_count == 0 && group.idle_sockets.empty()) {
+ DCHECK(group.pending_requests.empty());
+ group_map_.erase(i);
+ }
+}
+
+void ClientSocketPool::Run() {
+ MaybeCloseIdleSockets(true);
+}
+
+} // namespace net
diff --git a/net/base/client_socket_pool.h b/net/base/client_socket_pool.h
new file mode 100644
index 0000000..1f43166
--- /dev/null
+++ b/net/base/client_socket_pool.h
@@ -0,0 +1,148 @@
+// Copyright 2008, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef NET_BASE_CLIENT_SOCKET_POOL_H_
+#define NET_BASE_CLIENT_SOCKET_POOL_H_
+
+#include <deque>
+#include <map>
+#include <string>
+
+#include "base/ref_counted.h"
+#include "base/timer.h"
+#include "net/base/completion_callback.h"
+
+namespace net {
+
+class ClientSocket;
+class ClientSocketHandle;
+
+// A ClientSocketPool is used to restrict the number of sockets open at a time.
+// It also maintains a list of idle persistent sockets.
+//
+// The ClientSocketPool allocates scoped_ptr<ClientSocket> objects, but it is
+// not responsible for allocating the associated ClientSocket objects. The
+// consumer must do so if it gets a scoped_ptr<ClientSocket> with a null value.
+//
+class ClientSocketPool : public base::RefCounted<ClientSocketPool>,
+ public Task {
+ public:
+ explicit ClientSocketPool(int max_sockets_per_group);
+
+ // Called to request a socket for the given handle. There are three possible
+ // results: 1) the handle will be initialized with a socket to reuse, 2) the
+ // handle will be initialized without a socket such that the consumer needs
+ // to supply a socket, or 3) the handle will be added to a wait list until a
+ // socket is available to reuse or the opportunity to create a new socket
+ // arises. The completion callback is notified in the 3rd case.
+ //
+ // If this function returns OK, then |handle| is initialized upon return.
+ // The |handle|'s is_initialized method will return true in this case. If a
+ // ClientSocket was reused, then |handle|'s socket member will be non-NULL.
+ // Otherwise, the consumer will need to supply |handle| with a socket by
+ // allocating a new ClientSocket object and calling the |handle|'s set_socket
+ // method.
+ //
+ // If ERR_IO_PENDING is returned, then the completion callback will be called
+ // when |handle| has been initialized.
+ //
+ int RequestSocket(ClientSocketHandle* handle, CompletionCallback* callback);
+
+ // Called to cancel a RequestSocket call that returned ERR_IO_PENDING. The
+ // same handle parameter must be passed to this method as was passed to the
+ // RequestSocket call being cancelled. The associated CompletionCallback is
+ // not run.
+ void CancelRequest(ClientSocketHandle* handle);
+
+ // Called to release the socket member of an initialized ClientSocketHandle
+ // once the socket is no longer needed. If the socket member is non-null and
+ // still has an established connection, then it will be added to the idle set
+ // of sockets to be used to satisfy future RequestSocket calls. Otherwise,
+ // the ClientSocket is destroyed.
+ void ReleaseSocket(ClientSocketHandle* handle);
+
+ // Called to close any idle connections held by the connection manager.
+ void CloseIdleSockets();
+
+ private:
+ friend class base::RefCounted<ClientSocketPool>;
+
+ typedef scoped_ptr<ClientSocket> ClientSocketPtr;
+
+ ~ClientSocketPool();
+
+ // Closes all idle sockets if |only_if_disconnected| is false. Else, only
+ // idle sockets that are disconnected get closed. "Maybe" refers to the
+ // fact that it doesn't close all idle sockets if |only_if_disconnected| is
+ // true.
+ void MaybeCloseIdleSockets(bool only_if_disconnected);
+
+ // Called when the number of idle sockets changes.
+ void IncrementIdleCount();
+ void DecrementIdleCount();
+
+ // Called via PostTask by ReleaseSocket.
+ void DoReleaseSocket(const std::string& group_name, ClientSocketPtr* ptr);
+
+ // Task implementation. This method scans the idle sockets checking to see
+ // if any have been disconnected.
+ virtual void Run();
+
+ // A Request is allocated per call to RequestSocket that results in
+ // ERR_IO_PENDING.
+ struct Request {
+ ClientSocketHandle* handle;
+ CompletionCallback* callback;
+ };
+
+ // A Group is allocated per group_name when there are idle sockets or pending
+ // requests. Otherwise, the Group object is removed from the map.
+ struct Group {
+ Group() : active_socket_count(0) {}
+ std::deque<ClientSocketPtr*> idle_sockets;
+ std::deque<Request> pending_requests;
+ int active_socket_count;
+ };
+
+ typedef std::map<std::string, Group> GroupMap;
+ GroupMap group_map_;
+
+ // Timer used to periodically prune sockets that have been disconnected.
+ RepeatingTimer timer_;
+
+ // The total number of idle sockets in the system.
+ int idle_socket_count_;
+
+ // The maximum number of sockets kept per group.
+ int max_sockets_per_group_;
+};
+
+} // namespace net
+
+#endif // NET_BASE_CLIENT_SOCKET_POOL_H_
diff --git a/net/base/client_socket_pool_unittest.cc b/net/base/client_socket_pool_unittest.cc
new file mode 100644
index 0000000..8a89e6d
--- /dev/null
+++ b/net/base/client_socket_pool_unittest.cc
@@ -0,0 +1,272 @@
+// Copyright 2008, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include "base/message_loop.h"
+#include "net/base/client_socket.h"
+#include "net/base/client_socket_handle.h"
+#include "net/base/client_socket_pool.h"
+#include "net/base/net_errors.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace {
+
+typedef testing::Test ClientSocketPoolTest;
+
+const int kMaxSocketsPerGroup = 6;
+
+class MockClientSocket : public net::ClientSocket {
+ public:
+ MockClientSocket() : connected_(false) {
+ allocation_count++;
+ }
+
+ // ClientSocket methods:
+ virtual int Connect(net::CompletionCallback* callback) {
+ connected_ = true;
+ return net::OK;
+ }
+ virtual int ReconnectIgnoringLastError(net::CompletionCallback* callback) {
+ return net::ERR_FAILED;
+ }
+ virtual void Disconnect() {
+ connected_ = false;
+ }
+ virtual bool IsConnected() const {
+ return connected_;
+ }
+
+ // Socket methods:
+ virtual int Read(char* buf, int buf_len,
+ net::CompletionCallback* callback) {
+ return net::ERR_FAILED;
+ }
+ virtual int Write(const char* buf, int buf_len,
+ net::CompletionCallback* callback) {
+ return net::ERR_FAILED;
+ }
+
+ static int allocation_count;
+
+ private:
+ bool connected_;
+};
+
+int MockClientSocket::allocation_count = 0;
+
+class TestSocketRequest : public CallbackRunner< Tuple1<int> > {
+ public:
+ TestSocketRequest(net::ClientSocketPool* pool) : handle(pool) {}
+
+ net::ClientSocketHandle handle;
+
+ void EnsureSocket() {
+ DCHECK(handle.is_initialized());
+ if (!handle.socket()) {
+ handle.set_socket(new MockClientSocket());
+ handle.socket()->Connect(NULL);
+ }
+ }
+
+ virtual void RunWithParams(const Tuple1<int>& params) {
+ DCHECK(params.a == net::OK);
+ completion_count++;
+ EnsureSocket();
+ }
+
+ static int completion_count;
+};
+
+int TestSocketRequest::completion_count = 0;
+
+} // namespace
+
+TEST(ClientSocketPoolTest, Basic) {
+ scoped_refptr<net::ClientSocketPool> pool =
+ new net::ClientSocketPool(kMaxSocketsPerGroup);
+
+ TestSocketRequest r(pool);
+ int rv;
+
+ rv = r.handle.Init("a", &r);
+ EXPECT_EQ(net::OK, rv);
+ EXPECT_TRUE(r.handle.is_initialized());
+
+ r.handle.Reset();
+
+ // The handle's Reset method may have posted a task.
+ MessageLoop::current()->RunAllPending();
+}
+
+TEST(ClientSocketPoolTest, WithIdleConnection) {
+ scoped_refptr<net::ClientSocketPool> pool =
+ new net::ClientSocketPool(kMaxSocketsPerGroup);
+
+ TestSocketRequest r(pool);
+ int rv;
+
+ rv = r.handle.Init("a", &r);
+ EXPECT_EQ(net::OK, rv);
+ EXPECT_TRUE(r.handle.is_initialized());
+
+ // Create a socket.
+ r.EnsureSocket();
+
+ // Release the socket. It should find its way into the idle list. We're
+ // testing that this does not trigger a crash.
+ r.handle.Reset();
+
+ // The handle's Reset method may have posted a task.
+ MessageLoop::current()->RunAllPending();
+}
+
+TEST(ClientSocketPoolTest, PendingRequests) {
+ scoped_refptr<net::ClientSocketPool> pool =
+ new net::ClientSocketPool(kMaxSocketsPerGroup);
+
+ int rv;
+
+ scoped_ptr<TestSocketRequest> reqs[kMaxSocketsPerGroup + 10];
+ for (size_t i = 0; i < arraysize(reqs); ++i)
+ reqs[i].reset(new TestSocketRequest(pool));
+
+ // Reset
+ MockClientSocket::allocation_count = 0;
+ TestSocketRequest::completion_count = 0;
+
+ // Create connections or queue up requests.
+ for (size_t i = 0; i < arraysize(reqs); ++i) {
+ rv = reqs[i]->handle.Init("a", reqs[i].get());
+ if (rv != net::ERR_IO_PENDING) {
+ EXPECT_EQ(net::OK, rv);
+ reqs[i]->EnsureSocket();
+ }
+ }
+
+ // Release any connections until we have no connections.
+ bool released_one;
+ do {
+ released_one = false;
+ for (size_t i = 0; i < arraysize(reqs); ++i) {
+ if (reqs[i]->handle.is_initialized()) {
+ reqs[i]->handle.Reset();
+ MessageLoop::current()->RunAllPending();
+ released_one = true;
+ }
+ }
+ } while (released_one);
+
+ EXPECT_EQ(kMaxSocketsPerGroup, MockClientSocket::allocation_count);
+ EXPECT_EQ(10, TestSocketRequest::completion_count);
+}
+
+TEST(ClientSocketPoolTest, PendingRequests_NoKeepAlive) {
+ scoped_refptr<net::ClientSocketPool> pool =
+ new net::ClientSocketPool(kMaxSocketsPerGroup);
+
+ int rv;
+
+ scoped_ptr<TestSocketRequest> reqs[kMaxSocketsPerGroup + 10];
+ for (size_t i = 0; i < arraysize(reqs); ++i)
+ reqs[i].reset(new TestSocketRequest(pool));
+
+ // Reset
+ MockClientSocket::allocation_count = 0;
+ TestSocketRequest::completion_count = 0;
+
+ // Create connections or queue up requests.
+ for (size_t i = 0; i < arraysize(reqs); ++i) {
+ rv = reqs[i]->handle.Init("a", reqs[i].get());
+ if (rv != net::ERR_IO_PENDING) {
+ EXPECT_EQ(net::OK, rv);
+ reqs[i]->EnsureSocket();
+ }
+ }
+
+ // Release any connections until we have no connections.
+ bool released_one;
+ do {
+ released_one = false;
+ for (size_t i = 0; i < arraysize(reqs); ++i) {
+ if (reqs[i]->handle.is_initialized()) {
+ reqs[i]->handle.socket()->Disconnect();
+ reqs[i]->handle.Reset();
+ MessageLoop::current()->RunAllPending();
+ released_one = true;
+ }
+ }
+ } while (released_one);
+
+ EXPECT_EQ(kMaxSocketsPerGroup + 10, MockClientSocket::allocation_count);
+ EXPECT_EQ(10, TestSocketRequest::completion_count);
+}
+
+TEST(ClientSocketPoolTest, CancelRequest) {
+ scoped_refptr<net::ClientSocketPool> pool =
+ new net::ClientSocketPool(kMaxSocketsPerGroup);
+
+ int rv;
+
+ scoped_ptr<TestSocketRequest> reqs[kMaxSocketsPerGroup + 10];
+ for (size_t i = 0; i < arraysize(reqs); ++i)
+ reqs[i].reset(new TestSocketRequest(pool));
+
+ // Reset
+ MockClientSocket::allocation_count = 0;
+ TestSocketRequest::completion_count = 0;
+
+ // Create connections or queue up requests.
+ for (size_t i = 0; i < arraysize(reqs); ++i) {
+ rv = reqs[i]->handle.Init("a", reqs[i].get());
+ if (rv != net::ERR_IO_PENDING) {
+ EXPECT_EQ(net::OK, rv);
+ reqs[i]->EnsureSocket();
+ }
+ }
+
+ // Cancel a request.
+ size_t index_to_cancel = kMaxSocketsPerGroup + 2;
+ EXPECT_TRUE(!reqs[index_to_cancel]->handle.is_initialized());
+ reqs[index_to_cancel]->handle.Reset();
+
+ // Release any connections until we have no connections.
+ bool released_one;
+ do {
+ released_one = false;
+ for (size_t i = 0; i < arraysize(reqs); ++i) {
+ if (reqs[i]->handle.is_initialized()) {
+ reqs[i]->handle.Reset();
+ MessageLoop::current()->RunAllPending();
+ released_one = true;
+ }
+ }
+ } while (released_one);
+
+ EXPECT_EQ(kMaxSocketsPerGroup, MockClientSocket::allocation_count);
+ EXPECT_EQ(9, TestSocketRequest::completion_count);
+}