From 536ae7a91f73c9a9605a350ef2f35a4ba61acf6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Wo=CC=81jcik?= <3044353+pwojcikdev@users.noreply.github.com> Date: Wed, 11 Sep 2024 13:18:08 +0200 Subject: [PATCH] Move mutex to `rate_limiter` --- nano/lib/rate_limiting.cpp | 6 ++---- nano/lib/rate_limiting.hpp | 3 +-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/nano/lib/rate_limiting.cpp b/nano/lib/rate_limiting.cpp index 268e8b5e9..2a4715c9a 100644 --- a/nano/lib/rate_limiting.cpp +++ b/nano/lib/rate_limiting.cpp @@ -16,7 +16,6 @@ nano::rate::token_bucket::token_bucket (std::size_t max_token_count_a, std::size bool nano::rate::token_bucket::try_consume (unsigned tokens_required_a) { debug_assert (tokens_required_a <= 1e9); - nano::lock_guard guard{ mutex }; refill (); bool possible = current_size >= tokens_required_a; if (possible) @@ -48,14 +47,11 @@ void nano::rate::token_bucket::refill () std::size_t nano::rate::token_bucket::largest_burst () const { - nano::lock_guard guard{ mutex }; return max_token_count - smallest_size; } void nano::rate::token_bucket::reset (std::size_t max_token_count_a, std::size_t refill_rate_a) { - nano::lock_guard guard{ mutex }; - // A token count of 0 indicates unlimited capacity. We use 1e9 as // a sentinel, allowing largest burst to still be computed. if (max_token_count_a == 0 || refill_rate_a == 0) @@ -78,10 +74,12 @@ nano::rate_limiter::rate_limiter (std::size_t limit_a, double burst_ratio_a) : bool nano::rate_limiter::should_pass (std::size_t message_size_a) { + nano::lock_guard guard{ mutex }; return bucket.try_consume (nano::narrow_cast (message_size_a)); } void nano::rate_limiter::reset (std::size_t limit_a, double burst_ratio_a) { + nano::lock_guard guard{ mutex }; bucket.reset (static_cast (limit_a * burst_ratio_a), limit_a); } \ No newline at end of file diff --git a/nano/lib/rate_limiting.hpp b/nano/lib/rate_limiting.hpp index f027d7083..f67246787 100644 --- a/nano/lib/rate_limiting.hpp +++ b/nano/lib/rate_limiting.hpp @@ -54,8 +54,6 @@ private: std::size_t smallest_size{ 0 }; std::chrono::steady_clock::time_point last_refill; - mutable nano::mutex mutex; - static std::size_t constexpr unlimited_rate_sentinel{ static_cast (1e9) }; }; } @@ -73,5 +71,6 @@ public: private: nano::rate::token_bucket bucket; + mutable nano::mutex mutex; }; } \ No newline at end of file