userver: userver/congestion_control/controller.hpp Source File
Loading...
Searching...
No Matches
controller.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/congestion_control/controller.hpp
4/// @brief Congestion control controller and policy state
5
6#include <atomic>
7#include <chrono>
8#include <cstddef>
9#include <optional>
10#include <string>
11
12#include <userver/congestion_control/limiter.hpp>
13#include <userver/congestion_control/sensor.hpp>
14#include <userver/dynamic_config/source.hpp>
15#include <userver/formats/json_fwd.hpp>
16
17#include <dynamic_config/variables/USERVER_RPS_CCONTROL.hpp>
18
19USERVER_NAMESPACE_BEGIN
20
21/// Congestion Control
22namespace congestion_control {
23
25 size_t times_with_overload{0};
26 size_t times_wo_overload{0};
27
28 bool is_overloaded{false};
29 std::optional<size_t> current_limit;
30
31 size_t max_up_delta{1};
32};
33
34struct Stats final {
35 std::atomic<size_t> no_limit{0};
36 std::atomic<size_t> not_overload_no_pressure{0};
37 std::atomic<size_t> not_overload_pressure{0};
38 std::atomic<size_t> overload_no_pressure{0};
39 std::atomic<size_t> overload_pressure{0};
40
41 std::atomic<size_t> current_state{0};
42 std::atomic<std::chrono::seconds> last_overload_pressure{
43 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()) -
44 std::chrono::hours(1)
45 };
46};
47
48using Policy = ::dynamic_config::userver_rps_ccontrol::VariableType;
49
50class Controller final {
51public:
52 Controller(std::string name, dynamic_config::Source config_source);
53
54 void Feed(const Sensor::Data&);
55
56 Limit GetLimit() const;
57
58 Limit GetLimitRaw() const;
59
60 void SetEnabled(bool enabled);
61
62 bool IsEnabled() const;
63
64 const Stats& GetStats() const;
65
66private:
67 bool IsOverloadedNow(const Sensor::Data& data, const Policy& policy) const;
68
69 size_t CalcNewLimit(const Sensor::Data& data, const Policy& policy) const;
70
71 static bool IsThresholdReached(const Sensor::Data& data, int percent);
72
73 const std::string name_;
74 Limit limit_;
75 dynamic_config::Source config_source_;
76 PolicyState state_;
77 std::atomic<bool> is_enabled_;
78
79 Stats stats_;
80};
81
83 Sensor& sensor;
84 Limiter& limiter;
85 Controller& controller;
86};
87
88} // namespace congestion_control
89
90USERVER_NAMESPACE_END