Debian Codegraph @

src/core/lib/backoff/backoff.h

raw
1 /*
2 *
3 * Copyright 2016 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #ifndef GRPC_CORE_LIB_BACKOFF_BACKOFF_H
20 #define GRPC_CORE_LIB_BACKOFF_BACKOFF_H
21
22 #include <grpc/support/port_platform.h>
23
24 #include "absl/random/random.h"
25
26 #include "src/core/lib/gprpp/time.h"
27
28 namespace grpc_core {
29
30 /// Implementation of the backoff mechanism described in
31 /// doc/connection-backoff.md
32 class BackOff {
33 public:
34 class Options;
35
36 /// Initialize backoff machinery - does not need to be destroyed
37 explicit BackOff(const Options& options);
38
39 /// Returns the time at which the next attempt should start.
40 Timestamp NextAttemptTime();
41
42 /// Reset the backoff, so the next value returned by NextAttemptTime()
43 /// will be the time of the second attempt (rather than the Nth).
44 void Reset();
45
46 class Options {
47 public:
48 Options& set_initial_backoff(Duration initial_backoff) {
49 initial_backoff_ = initial_backoff;
50 return *this;
51 }
52 Options& set_multiplier(double multiplier) {
53 multiplier_ = multiplier;
54 return *this;
55 }
56 Options& set_jitter(double jitter) {
57 jitter_ = jitter;
58 return *this;
59 }
60 Options& set_max_backoff(Duration max_backoff) {
61 max_backoff_ = max_backoff;
62 return *this;
63 }
64 /// how long to wait after the first failure before retrying
65 Duration initial_backoff() const { return initial_backoff_; }
66 /// factor with which to multiply backoff after a failed retry
67 double multiplier() const { return multiplier_; }
68 /// amount to randomize backoffs
69 double jitter() const { return jitter_; }
70 /// maximum time between retries
71 Duration max_backoff() const { return max_backoff_; }
72
73 private:
74 Duration initial_backoff_;
75 double multiplier_;
76 double jitter_;
77 Duration max_backoff_;
78 }; // class Options
79
80 private:
81 const Options options_;
82 absl::BitGen rand_gen_;
83 bool initial_;
84 /// current delay before retries
85 Duration current_backoff_;
86 };
87
88 } // namespace grpc_core
89 #endif /* GRPC_CORE_LIB_BACKOFF_BACKOFF_H */