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_UTIL_RANDOM_EARLY_DETECTION_H 16 #define GRPC_SRC_CORE_UTIL_RANDOM_EARLY_DETECTION_H 17 18 #include <grpc/support/port_platform.h> 19 #include <limits.h> 20 21 #include <cstdint> 22 23 #include "absl/random/bit_gen_ref.h" 24 25 namespace grpc_core { 26 27 // Implements the random early detection algorithm - allows items to be rejected 28 // or accepted based upon their size. 29 class RandomEarlyDetection { 30 public: RandomEarlyDetection()31 RandomEarlyDetection() : soft_limit_(INT_MAX), hard_limit_(INT_MAX) {} RandomEarlyDetection(uint64_t soft_limit,uint64_t hard_limit)32 RandomEarlyDetection(uint64_t soft_limit, uint64_t hard_limit) 33 : soft_limit_(soft_limit), hard_limit_(hard_limit) {} 34 35 // Returns true if the size is greater than or equal to the hard limit - ie if 36 // this item must be rejected. MustReject(uint64_t size)37 bool MustReject(uint64_t size) { return size >= hard_limit_; } 38 39 // Returns true if the item should be rejected. 40 bool Reject(uint64_t size, absl::BitGenRef bitsrc) const; 41 soft_limit()42 uint64_t soft_limit() const { return soft_limit_; } hard_limit()43 uint64_t hard_limit() const { return hard_limit_; } 44 SetLimits(uint64_t soft_limit,uint64_t hard_limit)45 void SetLimits(uint64_t soft_limit, uint64_t hard_limit) { 46 soft_limit_ = soft_limit; 47 hard_limit_ = hard_limit; 48 } 49 50 private: 51 // The soft limit is the size at which we start rejecting items with a 52 // probability that increases linearly to 1 as the size approaches the hard 53 // limit. 54 uint64_t soft_limit_; 55 // The hard limit is the size at which we reject all items. 56 uint64_t hard_limit_; 57 }; 58 59 } // namespace grpc_core 60 61 #endif // GRPC_SRC_CORE_UTIL_RANDOM_EARLY_DETECTION_H 62