xref: /aosp_15_r20/external/grpc-grpc/src/core/ext/transport/chttp2/transport/write_size_policy.h (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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_EXT_TRANSPORT_CHTTP2_TRANSPORT_WRITE_SIZE_POLICY_H
16 #define GRPC_SRC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_WRITE_SIZE_POLICY_H
17 
18 #include <grpc/support/port_platform.h>
19 
20 #include <stddef.h>
21 #include <stdint.h>
22 
23 #include "src/core/lib/gprpp/time.h"
24 
25 namespace grpc_core {
26 
27 class Chttp2WriteSizePolicy {
28  public:
29   // Smallest possible WriteTargetSize
MinTarget()30   static constexpr size_t MinTarget() { return 32 * 1024; }
31   // Largest possible WriteTargetSize
MaxTarget()32   static constexpr size_t MaxTarget() { return 16 * 1024 * 1024; }
33   // How long should a write take to be considered "fast"
FastWrite()34   static constexpr Duration FastWrite() { return Duration::Milliseconds(100); }
35   // How long should a write take to be considered "slow"
SlowWrite()36   static constexpr Duration SlowWrite() { return Duration::Seconds(1); }
37   // If a read is slow, what target time should we use to try and adjust back
38   // to?
TargetWriteTime()39   static constexpr Duration TargetWriteTime() {
40     return Duration::Milliseconds(300);
41   }
42 
43   // What size should be targetted for the next write.
44   size_t WriteTargetSize();
45   // Notify the policy that a write of some size has begun.
46   // EndWrite must be called when the write completes.
47   void BeginWrite(size_t size);
48   // Notify the policy that a write of some size has ended.
49   void EndWrite(bool success);
50 
51  private:
52   size_t current_target_ = 128 * 1024;
53   Timestamp experiment_start_time_ = Timestamp::InfFuture();
54   // State varies from -2...2
55   // Every time we do a write faster than kFastWrite, we decrement
56   // Every time we do a write slower than kSlowWrite, we increment
57   // If we hit -2, we increase the target size and reset state to 0
58   // If we hit 2, we decrease the target size and reset state to 0
59   // In this way, we need two consecutive fast/slow operations to adjust,
60   // denoising the signal significantly
61   int8_t state_ = 0;
62 };
63 
64 }  // namespace grpc_core
65 
66 #endif  // GRPC_SRC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_WRITE_SIZE_POLICY_H
67