|
| 1 | +// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import 'dart:async'; |
| 6 | +import 'dart:math' as math; |
| 7 | + |
| 8 | +import 'package:async/async.dart'; |
| 9 | + |
| 10 | +import 'http.dart'; |
| 11 | + |
| 12 | +/// An HTTP client wrapper that automatically retries failing requests. |
| 13 | +class RetryClient extends BaseClient { |
| 14 | + /// The wrapped client. |
| 15 | + final Client _inner; |
| 16 | + |
| 17 | + /// The number of times a request should be retried. |
| 18 | + final int _retries; |
| 19 | + |
| 20 | + /// The callback that determines whether a request should be retried. |
| 21 | + final bool Function(BaseResponse) _when; |
| 22 | + |
| 23 | + /// The callback that determines whether a request when an error is thrown. |
| 24 | + final bool Function(Object, StackTrace) _whenError; |
| 25 | + |
| 26 | + /// The callback that determines how long to wait before retrying a request. |
| 27 | + final Duration Function(int) _delay; |
| 28 | + |
| 29 | + /// The callback to call to indicate that a request is being retried. |
| 30 | + final void Function(BaseRequest, BaseResponse?, int)? _onRetry; |
| 31 | + |
| 32 | + /// Creates a client wrapping [_inner] that retries HTTP requests. |
| 33 | + /// |
| 34 | + /// This retries a failing request [retries] times (3 by default). Note that |
| 35 | + /// `n` retries means that the request will be sent at most `n + 1` times. |
| 36 | + /// |
| 37 | + /// By default, this retries requests whose responses have status code 503 |
| 38 | + /// Temporary Failure. If [when] is passed, it retries any request for whose |
| 39 | + /// response [when] returns `true`. If [whenError] is passed, it also retries |
| 40 | + /// any request that throws an error for which [whenError] returns `true`. |
| 41 | + /// |
| 42 | + /// By default, this waits 500ms between the original request and the first |
| 43 | + /// retry, then increases the delay by 1.5x for each subsequent retry. If |
| 44 | + /// [delay] is passed, it's used to determine the time to wait before the |
| 45 | + /// given (zero-based) retry. |
| 46 | + /// |
| 47 | + /// If [onRetry] is passed, it's called immediately before each retry so that |
| 48 | + /// the client has a chance to perform side effects like logging. The |
| 49 | + /// `response` parameter will be null if the request was retried due to an |
| 50 | + /// error for which [whenError] returned `true`. |
| 51 | + RetryClient( |
| 52 | + this._inner, { |
| 53 | + int retries = 3, |
| 54 | + bool Function(BaseResponse) when = _defaultWhen, |
| 55 | + bool Function(Object, StackTrace) whenError = _defaultWhenError, |
| 56 | + Duration Function(int retryCount) delay = _defaultDelay, |
| 57 | + void Function(BaseRequest, BaseResponse?, int retryCount)? onRetry, |
| 58 | + }) : _retries = retries, |
| 59 | + _when = when, |
| 60 | + _whenError = whenError, |
| 61 | + _delay = delay, |
| 62 | + _onRetry = onRetry { |
| 63 | + RangeError.checkNotNegative(_retries, 'retries'); |
| 64 | + } |
| 65 | + |
| 66 | + /// Like [new RetryClient], but with a pre-computed list of [delays] |
| 67 | + /// between each retry. |
| 68 | + /// |
| 69 | + /// This will retry a request at most `delays.length` times, using each delay |
| 70 | + /// in order. It will wait for `delays[0]` after the initial request, |
| 71 | + /// `delays[1]` after the first retry, and so on. |
| 72 | + RetryClient.withDelays( |
| 73 | + Client inner, |
| 74 | + Iterable<Duration> delays, { |
| 75 | + bool Function(BaseResponse) when = _defaultWhen, |
| 76 | + bool Function(Object, StackTrace) whenError = _defaultWhenError, |
| 77 | + void Function(BaseRequest, BaseResponse?, int retryCount)? onRetry, |
| 78 | + }) : this._withDelays( |
| 79 | + inner, |
| 80 | + delays.toList(), |
| 81 | + when: when, |
| 82 | + whenError: whenError, |
| 83 | + onRetry: onRetry, |
| 84 | + ); |
| 85 | + |
| 86 | + RetryClient._withDelays( |
| 87 | + Client inner, |
| 88 | + List<Duration> delays, { |
| 89 | + required bool Function(BaseResponse) when, |
| 90 | + required bool Function(Object, StackTrace) whenError, |
| 91 | + required void Function(BaseRequest, BaseResponse?, int)? onRetry, |
| 92 | + }) : this( |
| 93 | + inner, |
| 94 | + retries: delays.length, |
| 95 | + delay: (retryCount) => delays[retryCount], |
| 96 | + when: when, |
| 97 | + whenError: whenError, |
| 98 | + onRetry: onRetry, |
| 99 | + ); |
| 100 | + |
| 101 | + @override |
| 102 | + Future<StreamedResponse> send(BaseRequest request) async { |
| 103 | + final splitter = StreamSplitter(request.finalize()); |
| 104 | + |
| 105 | + var i = 0; |
| 106 | + for (;;) { |
| 107 | + StreamedResponse? response; |
| 108 | + try { |
| 109 | + response = await _inner.send(_copyRequest(request, splitter.split())); |
| 110 | + } catch (error, stackTrace) { |
| 111 | + if (i == _retries || !_whenError(error, stackTrace)) rethrow; |
| 112 | + } |
| 113 | + |
| 114 | + if (response != null) { |
| 115 | + if (i == _retries || !_when(response)) return response; |
| 116 | + |
| 117 | + // Make sure the response stream is listened to so that we don't leave |
| 118 | + // dangling connections. |
| 119 | + _unawaited(response.stream.listen((_) {}).cancel().catchError((_) {})); |
| 120 | + } |
| 121 | + |
| 122 | + await Future.delayed(_delay(i)); |
| 123 | + _onRetry?.call(request, response, i); |
| 124 | + i++; |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + /// Returns a copy of [original] with the given [body]. |
| 129 | + StreamedRequest _copyRequest(BaseRequest original, Stream<List<int>> body) { |
| 130 | + final request = StreamedRequest(original.method, original.url) |
| 131 | + ..contentLength = original.contentLength |
| 132 | + ..followRedirects = original.followRedirects |
| 133 | + ..headers.addAll(original.headers) |
| 134 | + ..maxRedirects = original.maxRedirects |
| 135 | + ..persistentConnection = original.persistentConnection; |
| 136 | + |
| 137 | + body.listen(request.sink.add, |
| 138 | + onError: request.sink.addError, |
| 139 | + onDone: request.sink.close, |
| 140 | + cancelOnError: true); |
| 141 | + |
| 142 | + return request; |
| 143 | + } |
| 144 | + |
| 145 | + @override |
| 146 | + void close() => _inner.close(); |
| 147 | +} |
| 148 | + |
| 149 | +bool _defaultWhen(BaseResponse response) => response.statusCode == 503; |
| 150 | + |
| 151 | +bool _defaultWhenError(Object error, StackTrace stackTrace) => false; |
| 152 | + |
| 153 | +Duration _defaultDelay(int retryCount) => |
| 154 | + const Duration(milliseconds: 500) * math.pow(1.5, retryCount); |
| 155 | + |
| 156 | +void _unawaited(Future<void>? f) {} |
0 commit comments