Implements exponential-backoff strategy. This strategy is based on the GRPC Connection Backoff Protocol: https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md
| 22 | |
| 23 | |
| 24 | class _BackoffTimer: |
| 25 | """Implements exponential-backoff strategy. |
| 26 | This strategy is based on the GRPC Connection Backoff Protocol: |
| 27 | https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md""" |
| 28 | |
| 29 | BACKOFF_INITIAL = 1.0 |
| 30 | BACKOFF_MAX = 120.0 |
| 31 | BACKOFF_JITTER = 0.23 |
| 32 | BACKOFF_MULTIPLIER = 1.6 |
| 33 | |
| 34 | def __init__(self): |
| 35 | self._num_retries = 0 |
| 36 | self._backoff = self.BACKOFF_INITIAL |
| 37 | self._deadline = time.time() + self._backoff |
| 38 | |
| 39 | def get_num_retries(self): |
| 40 | return self._num_retries |
| 41 | |
| 42 | def get_timeout(self): |
| 43 | return max(self.get_time_until_deadline(), min_connection_timeout) |
| 44 | |
| 45 | def get_time_until_deadline(self): |
| 46 | return max(self._deadline - time.time(), 0.0) |
| 47 | |
| 48 | def sleep_until_deadline(self): |
| 49 | time.sleep(self.get_time_until_deadline()) |
| 50 | |
| 51 | # Apply multiplier to current backoff time |
| 52 | self._backoff = min( |
| 53 | self._backoff * self.BACKOFF_MULTIPLIER, self.BACKOFF_MAX |
| 54 | ) |
| 55 | |
| 56 | # Get deadline by applying jitter as a proportion of backoff: |
| 57 | # if jitter is 0.1, then multiply backoff by random value in [0.9, 1.1] |
| 58 | self._deadline = time.time() + self._backoff * ( |
| 59 | 1 + self.BACKOFF_JITTER * random.uniform(-1, 1) |
| 60 | ) |
| 61 | self._num_retries += 1 |
| 62 | |
| 63 | |
| 64 | class HttpClient: |
no outgoing calls
no test coverage detected