Files
Library/tests/standalone/Resilience/KeyedRateLimiter.cpp

103 lines
3.1 KiB
C++

#include <Void/Resilience/KeyedRateLimiter.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>
namespace
{
using Void::Resilience::KeyedRateLimiter;
using Void::Testing::Test;
using namespace std::chrono_literals;
using TP = std::chrono::steady_clock::time_point;
struct ManualClock {
std::shared_ptr<TP> now =
std::make_shared<TP>(std::chrono::steady_clock::now());
auto fn() const
{
auto p = now;
return [p] { return *p; };
}
void advance(std::chrono::nanoseconds d) const { *now += d; }
};
struct KeyedRateLimiterTests : Void::Testing::Suite<KeyedRateLimiterTests> {
// Each key drains its own bucket independently.
Test keys_are_independent()
{
ManualClock clk;
KeyedRateLimiter<std::uint64_t> rl{3.0, 1.0, clk.fn()};
Void::Testing::expect(rl.allow(1));
Void::Testing::expect(rl.allow(1));
Void::Testing::expect(rl.allow(1));
Void::Testing::expect(!rl.allow(1)); // key 1 exhausted
Void::Testing::expect(rl.allow(2)); // key 2 still full
}
Test refills_per_key_over_time()
{
ManualClock clk;
KeyedRateLimiter<std::string> rl{2.0, 2.0, clk.fn()};
Void::Testing::expect(rl.allow("a", 2.0));
Void::Testing::expect(!rl.allow("a"));
clk.advance(1s); // +2 tokens
Void::Testing::expect(rl.allow("a"));
}
Test reset_forgets_a_key()
{
ManualClock clk;
KeyedRateLimiter<int> rl{1.0, 0.0, clk.fn()};
Void::Testing::expect(rl.allow(7));
Void::Testing::expect(!rl.allow(7));
rl.reset(7); // next use starts full again
Void::Testing::expect(rl.allow(7));
}
Test cleanup_drops_stale_keys()
{
ManualClock clk;
KeyedRateLimiter<int> rl{1.0, 1.0, clk.fn()};
(void)rl.allow(1);
(void)rl.allow(2);
Void::Testing::expect_eq(rl.tracked(), std::size_t{2});
// Nothing is older than an hour yet.
Void::Testing::expect_eq(rl.cleanup(1h), std::size_t{0});
Void::Testing::expect_eq(rl.tracked(), std::size_t{2});
clk.advance(2h);
Void::Testing::expect_eq(rl.cleanup(1h), std::size_t{2});
Void::Testing::expect_eq(rl.tracked(), std::size_t{0});
}
Test bounds_untrusted_key_cardinality()
{
ManualClock clk;
KeyedRateLimiter<std::string> rl{2.0, 0.0, clk.fn(),
std::size_t{2}};
Void::Testing::expect(rl.allow("a"));
Void::Testing::expect(rl.allow("b"));
Void::Testing::expect(!rl.allow("c"));
Void::Testing::expect_eq(rl.tracked(), std::size_t{2});
clk.advance(2min);
Void::Testing::expect_eq(rl.cleanup(1min), std::size_t{2});
Void::Testing::expect(rl.allow("c"));
}
Test explicit_time_is_shared_by_tracking_and_refill()
{
ManualClock clk;
KeyedRateLimiter<int> rl{1.0, 1.0, clk.fn(), std::size_t{1}};
const TP start = *clk.now;
Void::Testing::expect(rl.allow_at(1, start));
Void::Testing::expect(!rl.allow_at(1, start));
Void::Testing::expect(rl.allow_at(1, start + 1s));
Void::Testing::expect_eq(rl.cleanup_at(start + 3s, 1s),
std::size_t{1});
}
};
} // namespace