|
2 | 2 | // for details. All rights reserved. Use of this source code is governed by a |
3 | 3 | // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
|
| 5 | +import 'dart:async'; |
5 | 6 | import 'dart:io'; |
6 | 7 |
|
7 | 8 | import 'package:http/http.dart' as http; |
8 | 9 | import 'package:http/retry.dart'; |
| 10 | +import 'package:retry/retry.dart'; |
9 | 11 |
|
10 | 12 | final _transientStatusCodes = { |
11 | 13 | // See: https://cloud.google.com/storage/docs/xml-api/reference-status |
@@ -35,3 +37,45 @@ http.Client httpRetryClient({ |
35 | 37 | whenError: (e, st) => lenient || e is SocketException, |
36 | 38 | ); |
37 | 39 | } |
| 40 | + |
| 41 | +/// Creates a HTTP client and executes a GET request to the specified [uri], |
| 42 | +/// making sure that the HTTP resources are freed after the [responseFn] |
| 43 | +/// callback finishes. |
| 44 | +/// The HTTP GET and the [responseFn] callback is retried on the transient |
| 45 | +/// network errors. |
| 46 | +Future<K> httpGetWithRetry<K>( |
| 47 | + Uri uri, { |
| 48 | + required FutureOr<K> Function(http.Response response) responseFn, |
| 49 | + int maxAttempts = 3, |
| 50 | +}) async { |
| 51 | + return await retry( |
| 52 | + () async { |
| 53 | + final client = http.Client(); |
| 54 | + try { |
| 55 | + final rs = await client.get(uri); |
| 56 | + if (rs.statusCode == 200) { |
| 57 | + return responseFn(rs); |
| 58 | + } |
| 59 | + throw http.ClientException( |
| 60 | + 'Unexpected status code for $uri: ${rs.statusCode}.'); |
| 61 | + } finally { |
| 62 | + client.close(); |
| 63 | + } |
| 64 | + }, |
| 65 | + maxAttempts: maxAttempts, |
| 66 | + retryIf: _retryIf, |
| 67 | + ); |
| 68 | +} |
| 69 | + |
| 70 | +bool _retryIf(Exception e) { |
| 71 | + if (e is TimeoutException) { |
| 72 | + return true; // Timeouts we can retry |
| 73 | + } |
| 74 | + if (e is IOException) { |
| 75 | + return true; // I/O issues are worth retrying |
| 76 | + } |
| 77 | + if (e is http.ClientException) { |
| 78 | + return true; // HTTP issues are worth retrying |
| 79 | + } |
| 80 | + return false; |
| 81 | +} |
0 commit comments