https_client_pool.cc
1 // Copyright 2019, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 #include "util/http/https_client_pool.h"
5 
6 #include "base/logging.h"
7 #include "util/http/https_client.h"
8 
9 namespace util {
10 
11 namespace http {
12 
13 void HttpsClientPool::HandleGuard::operator()(HttpsClient* client) {
14  CHECK(client);
15 
16  CHECK_GT(pool_->existing_handles_, 0);
17 
18  if (client->status()) {
19  VLOG(1) << "Deleting client " << client->native_handle() << " due to " << client->status();
20  --pool_->existing_handles_;
21  delete client;
22  } else {
23  CHECK(pool_);
24  pool_->available_handles_.emplace_back(client);
25  }
26 }
27 
28 HttpsClientPool::HttpsClientPool(const std::string& domain, ::boost::asio::ssl::context* ssl_ctx,
29  IoContext* io_cntx)
30  : ssl_cntx_(*ssl_ctx), io_cntx_(*io_cntx), domain_(domain) {}
31 
32 HttpsClientPool::~HttpsClientPool() {
33  for (auto* ptr : available_handles_) {
34  delete ptr;
35  }
36 }
37 
38 auto HttpsClientPool::GetHandle() -> ClientHandle {
39  while (!available_handles_.empty()) {
40  // Pulling the oldest handles first.
41  std::unique_ptr<HttpsClient> ptr{std::move(available_handles_.front())};
42 
43  available_handles_.pop_front();
44 
45  if (ptr->status()) {
46  continue; // we just throw a connection with error status.
47  }
48 
49  VLOG(1) << "Reusing https client " << ptr->native_handle();
50 
51  // pass it further with custom deleter.
52  return ClientHandle(ptr.release(), HandleGuard{this});
53  }
54 
55  // available_handles_ are empty - create a new connection.
56  VLOG(1) << "Creating a new https client";
57 
58  std::unique_ptr<HttpsClient> client(new HttpsClient{domain_, &io_cntx_, &ssl_cntx_});
59  client->set_retry_count(retry_cnt_);
60 
61  auto ec = client->Connect(connect_msec_);
62 
63  LOG_IF(WARNING, ec) << "HttpsClientPool: Could not connect " << ec;
64  ++existing_handles_;
65 
66  return ClientHandle{client.release(), HandleGuard{this}};
67 }
68 
69 } // namespace http
70 } // namespace util
ClientHandle GetHandle()
Returns https client connection from the pool.