• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "src/core/lib/resource_quota/memory_quota.h"
25 #include "src/core/util/ref_counted.h"
26 #include "src/core/util/ref_counted_ptr.h"
27 #include "src/core/util/sync.h"
28 
29 namespace grpc_core {
30 
31 // Tracks the amount of threads in a resource quota.
32 class ConnectionQuota : public RefCounted<ConnectionQuota> {
33  public:
34   ConnectionQuota();
35   ~ConnectionQuota() override = default;
36 
37   ConnectionQuota(const ConnectionQuota&) = delete;
38   ConnectionQuota& operator=(const ConnectionQuota&) = delete;
39 
40   // Set the maximum number of allowed incoming connections on the server.
41   void SetMaxIncomingConnections(int max_incoming_connections);
42 
43   // Returns true if the incoming connection is allowed to be accepted on the
44   // server.
45   bool AllowIncomingConnection(MemoryQuotaRefPtr mem_quota,
46                                absl::string_view peer);
47 
48   // Mark connections as closed.
49   void ReleaseConnections(int num_connections);
50 
TestOnlyActiveIncomingConnections()51   int TestOnlyActiveIncomingConnections() const {
52     return active_incoming_connections_;
53   }
54 
55  private:
56   std::atomic<int> active_incoming_connections_{0};
57   std::atomic<int> max_incoming_connections_{std::numeric_limits<int>::max()};
58 };
59 
60 using ConnectionQuotaRefPtr = RefCountedPtr<ConnectionQuota>;
61 
62 }  // namespace grpc_core
63 
64 #endif  // GRPC_SRC_CORE_LIB_RESOURCE_QUOTA_CONNECTION_QUOTA_H
65