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