gcs_utils.h
1 // Copyright 2019, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 
5 #pragma once
6 
7 #include <boost/beast/http/buffer_body.hpp>
8 #include <boost/beast/http/dynamic_body.hpp>
9 #include <boost/beast/http/parser.hpp>
10 
11 #include "absl/strings/str_cat.h"
12 #include "absl/types/optional.h"
13 
14 #include "util/gce/gce.h"
15 #include "util/http/https_client_pool.h"
16 #include "util/stats/varz_stats.h"
17 #include "util/status.h"
18 
19 namespace util {
20 namespace detail {
21 
22 namespace h2 = ::boost::beast::http;
23 
24 using bb_str_view = ::boost::beast::string_view;
25 
26 inline absl::string_view absl_sv(const bb_str_view s) {
27  return absl::string_view{s.data(), s.size()};
28 }
29 
30 h2::request<h2::dynamic_body> PrepareGenericRequest(h2::verb req_verb, const bb_str_view url,
31  const bb_str_view token);
32 
33 inline Status ToStatus(const ::boost::system::error_code& ec) {
34  return ec ? Status(StatusCode::IO_ERROR, absl::StrCat(ec.value(), ": ", ec.message()))
35  : Status::OK;
36 }
37 
38 inline bool DoesServerPushback(h2::status st) {
39  return st == h2::status::too_many_requests ||
40  h2::to_status_class(st) == h2::status_class::server_error;
41 }
42 
43 inline bool IsUnauthorized(const h2::header<false, h2::fields>& header) {
44  if (header.result() != h2::status::unauthorized) {
45  return false;
46  }
47  auto it = header.find("WWW-Authenticate");
48 
49  return it != header.end();
50 }
51 
52 inline void AddBearer(absl::string_view token, h2::header<true, h2::fields>* req) {
53  std::string token_header = absl::StrCat("Bearer ", token);
54  req->set(h2::field::authorization, token_header);
55 }
56 
58  public:
59  using Request = h2::request<h2::dynamic_body>;
60  using ClientHandle = http::HttpsClientPool::ClientHandle;
61 
62  ApiSenderBase(const char* name, const GCE& gce, http::HttpsClientPool* pool);
63 
64  virtual ~ApiSenderBase();
65 
66  StatusObject<ClientHandle> SendGeneric(unsigned num_iterations, Request req);
67 
68  protected:
69  using error_code = ::boost::system::error_code;
70 
71  virtual error_code SendRequestIterative(const Request& req, http::HttpsClient* client) = 0;
72 
73  const char* name_;
74  const GCE& gce_;
75  http::HttpsClientPool* const pool_;
76 };
77 
79  public:
80  using Parser = h2::response_parser<h2::buffer_body>;
81 
82  using ApiSenderBase::ApiSenderBase;
83 
85  Parser* parser() { return parser_.has_value() ? &parser_.value() : nullptr; }
86 
87  private:
88  error_code SendRequestIterative(const Request& req, http::HttpsClient* client) final;
89  absl::optional<Parser> parser_;
90 };
91 
92 
93 extern ::std::unique_ptr<VarzQps> gcs_writes;
94 extern ::std::unique_ptr<VarzMapAverage5m> gcs_latency;
95 
96 void InitVarzStats();
97 
98 } // namespace detail
99 } // namespace util
Definition: gce.h:16
Parser * parser()
Can be called only SendGeneric returned success.
Definition: gcs_utils.h:85