@@ -98,23 +98,32 @@ def _attempt_timeout_generator(
9898 yield max (0 , min (per_request_timeout , deadline - time .monotonic ()))
9999
100100
101- def backoff_generator ( initial = 0.01 , multiplier = 2 , maximum = 60 ) :
101+ class BackoffGenerator :
102102 """
103- Build a generator for exponential backoff sleep times.
103+ Generator class for exponential backoff sleep times.
104104
105105 This implementation builds on top of api_core.retries.exponential_sleep_generator,
106- adding the ability to retrieve previous values using the send (idx) method. This is
107- used by the Metrics class to track the sleep times used for each attempt.
106+ adding the ability to retrieve previous values using get_attempt_backoff (idx).
107+ This is used by the Metrics class to track the sleep times used for each attempt.
108108 """
109- history = []
110- subgenerator = exponential_sleep_generator (initial , multiplier , maximum )
111- while True :
112- next_backoff = next (subgenerator )
113- history .append (next_backoff )
114- sent_idx = yield next_backoff
115- while sent_idx is not None :
116- # requesting from history
117- sent_idx = yield history [sent_idx ]
109+
110+ def __init__ (self , initial = 0.01 , multiplier = 2 , maximum = 60 ):
111+ self .history = []
112+ self .subgenerator = exponential_sleep_generator (initial , multiplier , maximum )
113+
114+ def __iter__ (self ):
115+ return self
116+
117+ def __next__ (self ) -> float :
118+ next_backoff = next (self .subgenerator )
119+ self .history .append (next_backoff )
120+ return next_backoff
121+
122+ def get_attempt_backoff (self , attempt_idx ) -> float :
123+ """
124+ returns the backoff time for a specific attempt index, starting at 0.
125+ """
126+ return self .history [attempt_idx ]
118127
119128
120129def _retry_exception_factory (
0 commit comments