1 // Copyright 2024 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_RESOURCE_QUOTA_CONNECTION_QUOTA_H 16 #define GRPC_SRC_CORE_LIB_RESOURCE_QUOTA_CONNECTION_QUOTA_H 17 18 #include <grpc/support/port_platform.h> 19 20 #include <cstddef> 21 #include <limits> 22 23 #include "absl/base/thread_annotations.h" 24 25 #include "src/core/lib/gprpp/ref_counted.h" 26 #include "src/core/lib/gprpp/ref_counted_ptr.h" 27 #include "src/core/lib/gprpp/sync.h" 28 #include "src/core/lib/resource_quota/memory_quota.h" 29 30 namespace grpc_core { 31 32 // Tracks the amount of threads in a resource quota. 33 class ConnectionQuota : public RefCounted<ConnectionQuota> { 34 public: 35 ConnectionQuota(); 36 ~ConnectionQuota() override = default; 37 38 ConnectionQuota(const ConnectionQuota&) = delete; 39 ConnectionQuota& operator=(const ConnectionQuota&) = delete; 40 41 // Set the maximum number of allowed incoming connections on the server. 42 void SetMaxIncomingConnections(int max_incoming_connections); 43 44 // Returns true if the incoming connection is allowed to be accepted on the 45 // server. 46 bool AllowIncomingConnection(MemoryQuotaRefPtr mem_quota, 47 absl::string_view peer); 48 49 // Mark connections as closed. 50 void ReleaseConnections(int num_connections); 51 52 private: 53 std::atomic<int> active_incoming_connections_{0}; 54 std::atomic<int> max_incoming_connections_{std::numeric_limits<int>::max()}; 55 }; 56 57 using ConnectionQuotaRefPtr = RefCountedPtr<ConnectionQuota>; 58 59 } // namespace grpc_core 60 61 #endif // GRPC_SRC_CORE_LIB_RESOURCE_QUOTA_CONNECTION_QUOTA_H 62