1 // Copyright 2023 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef GRPC_SRC_CORE_LIB_BACKOFF_RANDOM_EARLY_DETECTION_H
16 #define GRPC_SRC_CORE_LIB_BACKOFF_RANDOM_EARLY_DETECTION_H
17 
18 #include <grpc/support/port_platform.h>
19 
20 #include <limits.h>
21 
22 #include <cstdint>
23 
24 #include "absl/random/random.h"
25 
26 namespace grpc_core {
27 
28 // Implements the random early detection algorithm - allows items to be rejected
29 // or accepted based upon their size.
30 class RandomEarlyDetection {
31  public:
RandomEarlyDetection()32   RandomEarlyDetection() : soft_limit_(INT_MAX), hard_limit_(INT_MAX) {}
RandomEarlyDetection(uint64_t soft_limit,uint64_t hard_limit)33   RandomEarlyDetection(uint64_t soft_limit, uint64_t hard_limit)
34       : soft_limit_(soft_limit), hard_limit_(hard_limit) {}
35 
36   // Returns true if the size is greater than or equal to the hard limit - ie if
37   // this item must be rejected.
MustReject(uint64_t size)38   bool MustReject(uint64_t size) { return size >= hard_limit_; }
39 
40   // Returns true if the item should be rejected.
41   bool Reject(uint64_t size);
42 
soft_limit()43   uint64_t soft_limit() const { return soft_limit_; }
hard_limit()44   uint64_t hard_limit() const { return hard_limit_; }
45 
SetLimits(uint64_t soft_limit,uint64_t hard_limit)46   void SetLimits(uint64_t soft_limit, uint64_t hard_limit) {
47     soft_limit_ = soft_limit;
48     hard_limit_ = hard_limit;
49   }
50 
51  private:
52   // The soft limit is the size at which we start rejecting items with a
53   // probability that increases linearly to 1 as the size approaches the hard
54   // limit.
55   uint64_t soft_limit_;
56   // The hard limit is the size at which we reject all items.
57   uint64_t hard_limit_;
58   // The bit generator used to generate random numbers.
59   absl::InsecureBitGen bitgen_;
60 };
61 
62 }  // namespace grpc_core
63 
64 #endif  // GRPC_SRC_CORE_LIB_BACKOFF_RANDOM_EARLY_DETECTION_H
65