throttling_manager.h
Go to the documentation of this file.
1 /*
2  * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License").
5  * You may not use this file except in compliance with the License.
6  * A copy of the License is located at
7  *
8  * http://aws.amazon.com/apache2.0
9  *
10  * or in the "license" file accompanying this file. This file is distributed
11  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12  * express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */
15 #pragma once
16 #include <aws/core/client/AWSError.h>
17 
18 #include <chrono>
19 #include <functional>
20 #include <mutex>
21 #include <unordered_map>
22 
23 namespace Aws {
24 namespace Client {
25 
33 {
34 protected:
47  template <class T, class U, class E, typename... ErrorArgs>
48  T MakeCall(std::function<T(const U & request)> api, const U & api_param, std::string api_name,
49  ErrorArgs... error_on_throttling_args) const
50  {
51  if (0 == max_api_tps_.count(api_name)) {
52  return api(api_param);
53  }
54  /* Min delta is 1s / TPS, e.g. 5 TPS -> 200ms wait time between calls */
55  auto min_delta_allowed = std::chrono::duration_cast<std::chrono::milliseconds>(
56  std::chrono::seconds(1) / max_api_tps_.at(api_name))
57  .count();
58  std::lock_guard<std::mutex> lock(api_call_time_mutex_);
59  {
60  if (0 == last_call_time_per_api_.count(api_name)) {
61  last_call_time_per_api_.insert(std::make_pair(
62  api_name, std::chrono::time_point<std::chrono::steady_clock>(std::chrono::seconds(0))));
63  }
64  auto now = std::chrono::steady_clock::now();
65  auto delta_in_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
66  now - last_call_time_per_api_.at(api_name))
67  .count();
68  if (delta_in_ms >= min_delta_allowed) {
69  last_call_time_per_api_.at(api_name) = now;
70  return api(api_param);
71  } else {
72  T outcome(Aws::Client::AWSError<E>(error_on_throttling_args...));
73  return outcome;
74  }
75  }
76  }
82  void SetMaxApiTps(const std::string & api, double tps) { max_api_tps_[api] = tps; }
83 
84 private:
85  std::unordered_map<std::string, double> max_api_tps_;
86  mutable std::mutex api_call_time_mutex_;
87  mutable std::unordered_map<std::string, std::chrono::time_point<std::chrono::steady_clock>>
89 };
90 
91 } // namespace Client
92 } // namespace Aws
std::unordered_map< std::string, std::chrono::time_point< std::chrono::steady_clock > > last_call_time_per_api_
std::unordered_map< std::string, double > max_api_tps_
T MakeCall(std::function< T(const U &request)> api, const U &api_param, std::string api_name, ErrorArgs...error_on_throttling_args) const
void SetMaxApiTps(const std::string &api, double tps)


aws_common
Author(s): AWS RoboMaker
autogenerated on Sat Mar 6 2021 03:11:38