calculateRetryDelay function

Duration calculateRetryDelay({
  1. required int attempt,
  2. required RetryConfig config,
  3. String? retryAfterHeader,
})

Calculate delay for the next retry attempt.

Implementation

Duration calculateRetryDelay({
  required int attempt,
  required RetryConfig config,
  String? retryAfterHeader,
}) {
  // Respect server's Retry-After header
  if (retryAfterHeader != null) {
    final seconds = int.tryParse(retryAfterHeader);
    if (seconds != null && seconds > 0) {
      return Duration(seconds: seconds);
    }
    // Try parsing as HTTP date
    final date = DateTime.tryParse(retryAfterHeader);
    if (date != null) {
      final diff = date.difference(DateTime.now());
      if (diff > Duration.zero) return diff;
    }
  }

  // Exponential backoff with jitter
  final random = Random();
  final exponentialMs = (pow(2, attempt) * config.baseDelayMs).toInt();
  final jitterMs = (random.nextDouble() * 0.25 * exponentialMs).toInt();
  final totalMs = exponentialMs + jitterMs;
  final clampedMs = totalMs.clamp(config.baseDelayMs, config.maxDelayMs);

  return Duration(milliseconds: clampedMs);
}