|
| 1 | +import 'dart:async'; |
| 2 | +import 'dart:convert'; |
| 3 | +import 'dart:io'; |
| 4 | + |
1 | 5 | import 'package:http/http.dart' as http; |
2 | 6 | import 'package:meta/meta.dart'; |
3 | 7 |
|
| 8 | +import '../logging.dart'; |
| 9 | +import 'retry_backoff.dart'; |
| 10 | +import 'retry_notice.dart'; |
| 11 | + |
4 | 12 | @visibleForTesting |
5 | 13 | http.Client internalHttpClient = http.Client(); |
6 | 14 |
|
7 | 15 | http.Client get httpClient => internalHttpClient; |
| 16 | + |
| 17 | +/// Callback invoked before a retry attempt is scheduled. |
| 18 | +typedef RetryNoticeCallback = FutureOr<void> Function(RetryNotice notice); |
| 19 | + |
| 20 | +/// Issue a GET request with retry/backoff applied for transient errors. |
| 21 | +Future<http.Response> getWithRetry( |
| 22 | + Uri url, { |
| 23 | + Map<String, String>? headers, |
| 24 | + http.Client? client, |
| 25 | + Duration? timeout, |
| 26 | + RetryNoticeCallback? onRetry, |
| 27 | + RetryBackoff backoff = const RetryBackoff(), |
| 28 | + MelosLogger? logger, |
| 29 | +}) { |
| 30 | + return _withRetry( |
| 31 | + method: 'GET', |
| 32 | + url: url, |
| 33 | + timeout: timeout, |
| 34 | + onRetry: onRetry, |
| 35 | + backoff: backoff, |
| 36 | + logger: logger, |
| 37 | + request: () => (client ?? httpClient).get(url, headers: headers), |
| 38 | + ); |
| 39 | +} |
| 40 | + |
| 41 | +/// Issue a POST request with retry/backoff applied for transient errors. |
| 42 | +Future<http.Response> postWithRetry( |
| 43 | + Uri url, { |
| 44 | + Map<String, String>? headers, |
| 45 | + Object? body, |
| 46 | + Encoding? encoding, |
| 47 | + http.Client? client, |
| 48 | + Duration? timeout, |
| 49 | + RetryNoticeCallback? onRetry, |
| 50 | + RetryBackoff backoff = const RetryBackoff(), |
| 51 | + MelosLogger? logger, |
| 52 | +}) { |
| 53 | + return _withRetry( |
| 54 | + method: 'POST', |
| 55 | + url: url, |
| 56 | + timeout: timeout, |
| 57 | + onRetry: onRetry, |
| 58 | + backoff: backoff, |
| 59 | + logger: logger, |
| 60 | + request: () => (client ?? httpClient).post( |
| 61 | + url, |
| 62 | + headers: headers, |
| 63 | + body: body, |
| 64 | + encoding: encoding, |
| 65 | + ), |
| 66 | + ); |
| 67 | +} |
| 68 | + |
| 69 | +Future<http.Response> _withRetry({ |
| 70 | + required String method, |
| 71 | + required Uri url, |
| 72 | + required Future<http.Response> Function() request, |
| 73 | + Duration? timeout, |
| 74 | + RetryNoticeCallback? onRetry, |
| 75 | + RetryBackoff backoff = const RetryBackoff(), |
| 76 | + MelosLogger? logger, |
| 77 | +}) async { |
| 78 | + var attempt = 1; |
| 79 | + |
| 80 | + while (true) { |
| 81 | + try { |
| 82 | + final pendingResponse = request(); |
| 83 | + final response = timeout == null |
| 84 | + ? await pendingResponse |
| 85 | + : await pendingResponse.timeout( |
| 86 | + timeout, |
| 87 | + onTimeout: () => throw TimeoutException( |
| 88 | + '$method $url timed out after ${timeout.inSeconds}s', |
| 89 | + ), |
| 90 | + ); |
| 91 | + |
| 92 | + if (!_shouldRetryResponse(response) || attempt >= backoff.maxAttempts) { |
| 93 | + return response; |
| 94 | + } |
| 95 | + |
| 96 | + final notice = _noticeFromResponse( |
| 97 | + method: method, |
| 98 | + url: url, |
| 99 | + attempt: attempt, |
| 100 | + backoff: backoff, |
| 101 | + response: response, |
| 102 | + ); |
| 103 | + await _handleRetryNotice(notice, onRetry, logger); |
| 104 | + await Future.delayed(notice.delay, () {}); |
| 105 | + } catch (error, stackTrace) { |
| 106 | + if (!_shouldRetryError(error) || attempt >= backoff.maxAttempts) { |
| 107 | + Error.throwWithStackTrace(error, stackTrace); |
| 108 | + } |
| 109 | + |
| 110 | + final notice = _noticeFromError( |
| 111 | + method: method, |
| 112 | + url: url, |
| 113 | + attempt: attempt, |
| 114 | + backoff: backoff, |
| 115 | + error: error, |
| 116 | + ); |
| 117 | + await _handleRetryNotice(notice, onRetry, logger); |
| 118 | + await Future.delayed(notice.delay, () {}); |
| 119 | + } |
| 120 | + |
| 121 | + attempt += 1; |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +Future<void> _handleRetryNotice( |
| 126 | + RetryNotice notice, |
| 127 | + RetryNoticeCallback? onRetry, |
| 128 | + MelosLogger? logger, |
| 129 | +) async { |
| 130 | + await Future.sync(() => onRetry?.call(notice)); |
| 131 | + |
| 132 | + if (logger != null && logger.isVerbose) { |
| 133 | + final delayDescription = _formatDelay(notice.delay); |
| 134 | + logger.trace( |
| 135 | + '[HTTP] Retrying ${notice.method} ${notice.url} ' |
| 136 | + '(${notice.attempt}/${notice.maxAttempts}) in $delayDescription ' |
| 137 | + 'because ${notice.reason}.', |
| 138 | + ); |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +RetryNotice _noticeFromResponse({ |
| 143 | + required String method, |
| 144 | + required Uri url, |
| 145 | + required int attempt, |
| 146 | + required RetryBackoff backoff, |
| 147 | + required http.Response response, |
| 148 | +}) { |
| 149 | + return RetryNotice( |
| 150 | + url: url, |
| 151 | + method: method, |
| 152 | + attempt: attempt + 1, |
| 153 | + maxAttempts: backoff.maxAttempts, |
| 154 | + delay: backoff.delay(attempt), |
| 155 | + reason: _reasonForStatusCode(response.statusCode), |
| 156 | + statusCode: response.statusCode, |
| 157 | + ); |
| 158 | +} |
| 159 | + |
| 160 | +RetryNotice _noticeFromError({ |
| 161 | + required String method, |
| 162 | + required Uri url, |
| 163 | + required int attempt, |
| 164 | + required RetryBackoff backoff, |
| 165 | + required Object error, |
| 166 | +}) { |
| 167 | + return RetryNotice( |
| 168 | + url: url, |
| 169 | + method: method, |
| 170 | + attempt: attempt + 1, |
| 171 | + maxAttempts: backoff.maxAttempts, |
| 172 | + delay: backoff.delay(attempt), |
| 173 | + reason: _reasonForError(error), |
| 174 | + error: error, |
| 175 | + ); |
| 176 | +} |
| 177 | + |
| 178 | +bool _shouldRetryResponse(http.Response response) { |
| 179 | + final status = response.statusCode; |
| 180 | + if (status == 408 || status == 429) { |
| 181 | + return true; |
| 182 | + } |
| 183 | + |
| 184 | + return status >= 500 && status < 600; |
| 185 | +} |
| 186 | + |
| 187 | +bool _shouldRetryError(Object error) { |
| 188 | + return error is TimeoutException || |
| 189 | + error is SocketException || |
| 190 | + error is HttpException || |
| 191 | + error is TlsException || |
| 192 | + error is http.ClientException || |
| 193 | + error is IOException; |
| 194 | +} |
| 195 | + |
| 196 | +String _reasonForStatusCode(int statusCode) { |
| 197 | + return switch (statusCode) { |
| 198 | + 408 => 'request timed out (HTTP 408)', |
| 199 | + 429 => 'rate limited (HTTP 429)', |
| 200 | + _ when statusCode >= 500 && statusCode < 600 => |
| 201 | + 'server error (HTTP $statusCode)', |
| 202 | + _ => 'HTTP $statusCode', |
| 203 | + }; |
| 204 | +} |
| 205 | + |
| 206 | +String _reasonForError(Object error) { |
| 207 | + if (error is TimeoutException) { |
| 208 | + return 'request timeout'; |
| 209 | + } |
| 210 | + |
| 211 | + return error.toString(); |
| 212 | +} |
| 213 | + |
| 214 | +String _formatDelay(Duration delay) { |
| 215 | + if (delay.inSeconds >= 1) { |
| 216 | + return '${delay.inSeconds}s'; |
| 217 | + } |
| 218 | + |
| 219 | + return '${delay.inMilliseconds}ms'; |
| 220 | +} |
0 commit comments