3737import io .grpc .Context ;
3838import io .opentelemetry .api .common .Attributes ;
3939import java .io .IOException ;
40+ import java .time .Duration ;
4041import java .util .ArrayDeque ;
4142import java .util .Set ;
4243import java .util .concurrent .CountDownLatch ;
6263 * token that differs from the last seen resume token) resets both, so a long-running stream that
6364 * regularly makes progress is not terminated by an occasional transient error. The default settings
6465 * have no maximum number of attempts or total timeout. Setting maxAttempts to 1 disables streaming
65- * retries.
66+ * retries. Positive server-supplied retry delays are capped at {@link
67+ * RetrySettings#getMaxRetryDelayDuration()} (defaulting to 32s when unset or non-positive), and
68+ * missing or non-positive server retry delays fall back to exponential backoff.
6669 *
6770 * <p>These limits bound the number of streams that this iterator starts. Each (re)started stream is
6871 * a call through the underlying GAX callable, and GAX applies the same {@link RetrySettings} to
@@ -89,6 +92,7 @@ abstract class ResumableStreamIterator extends AbstractIterator<PartialResultSet
8992 @ Nullable private volatile StreamMessageListener streamMessageListener ;
9093 private final RetrySettings streamingRetrySettings ;
9194 private final Set <Code > retryableCodes ;
95+ private static final long DEFAULT_MAX_RETRY_DELAY_MILLIS = 32_000L ;
9296 private static final Logger logger = Logger .getLogger (ResumableStreamIterator .class .getName ());
9397 @ Nullable private BackOff backOff ;
9498 private final ArrayDeque <PartialResultSet > buffer = new ArrayDeque <>();
@@ -200,8 +204,9 @@ private boolean maxAttemptsExhausted() {
200204 * zero means that no total timeout has been set, and that only maxAttempts (if set) limits the
201205 * retries. This mirrors the interpretation of these values in GAX.
202206 */
203- private boolean totalTimeoutExceeded (long proposedDelayMillis ) {
204- long totalTimeoutMillis = streamingRetrySettings .getTotalTimeout ().toMillis ();
207+ @ VisibleForTesting
208+ boolean totalTimeoutExceeded (long proposedDelayMillis ) {
209+ long totalTimeoutMillis = streamingRetrySettings .getTotalTimeoutDuration ().toMillis ();
205210 if (totalTimeoutMillis <= 0L ) {
206211 return false ;
207212 }
@@ -215,23 +220,45 @@ private boolean totalTimeoutExceeded(long proposedDelayMillis) {
215220 return Math .max (proposedDelayMillis , 0L ) >= totalTimeoutMillis - elapsedMillis ;
216221 }
217222
218- private ExponentialBackOff newBackOff () {
223+ /**
224+ * Converts {@code duration} to positive milliseconds (floored at 1ms for positive sub-millisecond
225+ * durations and saturated at {@code maxMillis} on overflow), or returns {@code
226+ * nonPositiveDefaultMillis} when {@code duration} is zero or negative.
227+ */
228+ private static long saturatedDurationMillis (
229+ Duration duration , long nonPositiveDefaultMillis , long maxMillis ) {
230+ if (duration .isZero () || duration .isNegative ()) {
231+ return nonPositiveDefaultMillis ;
232+ }
233+ try {
234+ return Math .max (1L , Math .min (duration .toMillis (), maxMillis ));
235+ } catch (ArithmeticException overflow ) {
236+ return maxMillis ;
237+ }
238+ }
239+
240+ private long effectiveMaxRetryDelayMillis () {
241+ return saturatedDurationMillis (
242+ streamingRetrySettings .getMaxRetryDelayDuration (),
243+ DEFAULT_MAX_RETRY_DELAY_MILLIS ,
244+ Long .MAX_VALUE );
245+ }
246+
247+ @ VisibleForTesting
248+ BackOff newBackOff () {
249+ int initialIntervalMillis =
250+ (int )
251+ saturatedDurationMillis (
252+ streamingRetrySettings .getInitialRetryDelayDuration (), 1L , Integer .MAX_VALUE );
253+ int maxIntervalMillis =
254+ Math .max (
255+ initialIntervalMillis ,
256+ (int ) Math .min (effectiveMaxRetryDelayMillis (), Integer .MAX_VALUE ));
219257 return new ExponentialBackOff .Builder ()
220258 .setMultiplier (streamingRetrySettings .getRetryDelayMultiplier ())
221259 // All of these values must be > 0.
222- .setInitialIntervalMillis (
223- Math .max (
224- 1 ,
225- (int )
226- Math .min (
227- streamingRetrySettings .getInitialRetryDelay ().toMillis (),
228- Integer .MAX_VALUE )))
229- .setMaxIntervalMillis (
230- Math .max (
231- 1 ,
232- (int )
233- Math .min (
234- streamingRetrySettings .getMaxRetryDelay ().toMillis (), Integer .MAX_VALUE )))
260+ .setInitialIntervalMillis (initialIntervalMillis )
261+ .setMaxIntervalMillis (maxIntervalMillis )
235262 // The total timeout is enforced explicitly in computeNext(), based on the elapsed time
236263 // since the first failure of the current retry sequence. Prevent the backoff from
237264 // returning BackOff.STOP, as that would misinterpret a total timeout of zero (that is, no
@@ -248,7 +275,8 @@ private static long nextBackOffMillis(BackOff backoff) throws SpannerException {
248275 }
249276 }
250277
251- private void backoffSleep (Context context , long backoffMillis ) throws SpannerException {
278+ @ VisibleForTesting
279+ void backoffSleep (Context context , long backoffMillis ) throws SpannerException {
252280 tracer .getCurrentSpan ().addAnnotation ("Backing off" , "Delay" , backoffMillis );
253281 final CountDownLatch latch = new CountDownLatch (1 );
254282 final Context .CancellationListener listener =
@@ -261,7 +289,7 @@ private void backoffSleep(Context context, long backoffMillis) throws SpannerExc
261289 try {
262290 if (backoffMillis == BackOff .STOP ) {
263291 // Highly unlikely but we handle it just in case.
264- backoffMillis = streamingRetrySettings . getMaxRetryDelay (). toMillis ();
292+ backoffMillis = effectiveMaxRetryDelayMillis ();
265293 }
266294 if (latch .await (backoffMillis , TimeUnit .MILLISECONDS )) {
267295 // Woken by context cancellation.
@@ -478,14 +506,19 @@ long checkRetryBudgetAndGetDelay(SpannerException spannerException) {
478506 spannerException );
479507 throw spannerException ;
480508 }
481- // Determine the retry delay: either the delay that the server included in the error, or
482- // otherwise a delay determined by the exponential backoff.
509+ // Determine the retry delay: use a positive server-supplied retry delay (clamped to the
510+ // effective max retry delay), or fall back to exponential backoff when absent or non-positive .
483511 long delayMillis = spannerException .getRetryDelayInMillis ();
484- if (delayMillis == -1L ) {
512+ long maxRetryDelayMillis = effectiveMaxRetryDelayMillis ();
513+ if (delayMillis <= 0L ) {
485514 if (this .backOff == null ) {
486515 this .backOff = newBackOff ();
487516 }
488- delayMillis = nextBackOffMillis (this .backOff );
517+ long backOffMillis = nextBackOffMillis (this .backOff );
518+ delayMillis =
519+ backOffMillis == BackOff .STOP ? maxRetryDelayMillis : Math .max (1L , backOffMillis );
520+ } else {
521+ delayMillis = Math .min (delayMillis , maxRetryDelayMillis );
489522 }
490523 // The total timeout budget applies regardless of whether the delay came from the server
491524 // or from the backoff.
0 commit comments