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>(std::chrono::steady_clock::now().time_since_epoch()) -
40 std::chrono::hours(1)};
41};
42
43class Controller final {
44public:
45 Controller(std::string name, dynamic_config::Source config_source);
46
47 void Feed(const Sensor::Data&);
48
49 Limit GetLimit() const;
50
51 Limit GetLimitRaw() const;
52
53 void SetEnabled(bool enabled);
54
55 bool IsEnabled() const;
56
57 const Stats& GetStats() const;
58
59private:
60 bool IsOverloadedNow(const Sensor::Data& data, const Policy& policy) const;
61
62 size_t CalcNewLimit(const Sensor::Data& data, const Policy& policy) const;
63
64 static bool IsThresholdReached(const Sensor::Data& data, int percent);
65
66 const std::string name_;
67 Limit limit_;
68 dynamic_config::Source config_source_;
69 PolicyState state_;
70 std::atomic<bool> is_enabled_;
71
72 Stats stats_;
73};
74
75struct ControllerInfo {
76 Sensor& sensor;
77 Limiter& limiter;
78 Controller& controller;
79};
80
81} // namespace congestion_control
82
83USERVER_NAMESPACE_END