xref: /aosp_15_r20/external/cronet/net/third_party/quiche/src/quiche/quic/test_tools/simulator/traffic_policer.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright (c) 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef QUICHE_QUIC_TEST_TOOLS_SIMULATOR_TRAFFIC_POLICER_H_
6 #define QUICHE_QUIC_TEST_TOOLS_SIMULATOR_TRAFFIC_POLICER_H_
7 
8 #include "absl/container/flat_hash_map.h"
9 #include "quiche/quic/test_tools/simulator/packet_filter.h"
10 #include "quiche/quic/test_tools/simulator/port.h"
11 
12 namespace quic {
13 namespace simulator {
14 
15 // Traffic policer uses a token bucket to limit the bandwidth of the traffic
16 // passing through.  It wraps around an input port and exposes an output port.
17 // Only the traffic from input to the output is policed, so in case when
18 // bidirectional policing is desired, two policers have to be used.  The flows
19 // are hashed by the destination only.
20 class TrafficPolicer : public PacketFilter {
21  public:
22   TrafficPolicer(Simulator* simulator, std::string name,
23                  QuicByteCount initial_bucket_size,
24                  QuicByteCount max_bucket_size, QuicBandwidth target_bandwidth,
25                  Endpoint* input);
26   TrafficPolicer(const TrafficPolicer&) = delete;
27   TrafficPolicer& operator=(const TrafficPolicer&) = delete;
28   ~TrafficPolicer() override;
29 
30  protected:
31   bool FilterPacket(const Packet& packet) override;
32 
33  private:
34   // Refill the token buckets with all the tokens that have been granted since
35   // |last_refill_time_|.
36   void Refill();
37 
38   QuicByteCount initial_bucket_size_;
39   QuicByteCount max_bucket_size_;
40   QuicBandwidth target_bandwidth_;
41 
42   // The time at which the token buckets were last refilled.
43   QuicTime last_refill_time_;
44 
45   // Maps each destination to the number of tokens it has left.
46   absl::flat_hash_map<std::string, QuicByteCount> token_buckets_;
47 };
48 
49 }  // namespace simulator
50 }  // namespace quic
51 
52 #endif  // QUICHE_QUIC_TEST_TOOLS_SIMULATOR_TRAFFIC_POLICER_H_
53