3 * Copyright 2016 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <grpc/support/port_platform.h>
21 #include "src/core/lib/backoff/backoff.h"
25 #include "src/core/lib/gpr/useful.h"
31 /* Generate a random number between 0 and 1. We roll our own RNG because seeding
32 * rand() modifies a global variable we have no control over. */
33 double generate_uniform_random_number(uint32_t* rng_state) {
34 constexpr uint32_t two_raise_31 = uint32_t(1) << 31;
35 *rng_state = (1103515245 * *rng_state + 12345) % two_raise_31;
36 return *rng_state / static_cast<double>(two_raise_31);
39 double generate_uniform_random_number_between(uint32_t* rng_state, double a,
42 if (a > b) GPR_SWAP(double, a, b); // make sure a < b
43 const double range = b - a;
44 return a + generate_uniform_random_number(rng_state) * range;
49 BackOff::BackOff(const Options& options)
51 rng_state_(static_cast<uint32_t>(gpr_now(GPR_CLOCK_REALTIME).tv_nsec)) {
55 grpc_millis BackOff::NextAttemptTime() {
58 return current_backoff_ + grpc_core::ExecCtx::Get()->Now();
60 current_backoff_ = static_cast<grpc_millis>(
61 std::min(current_backoff_ * options_.multiplier(),
62 static_cast<double>(options_.max_backoff())));
63 const double jitter = generate_uniform_random_number_between(
64 &rng_state_, -options_.jitter() * current_backoff_,
65 options_.jitter() * current_backoff_);
66 const grpc_millis next_timeout =
67 static_cast<grpc_millis>(current_backoff_ + jitter);
68 return next_timeout + grpc_core::ExecCtx::Get()->Now();
71 void BackOff::Reset() {
72 current_backoff_ = options_.initial_backoff();
76 void BackOff::SetRandomSeed(uint32_t seed) { rng_state_ = seed; }
78 } // namespace grpc_core