Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 13 additions & 12 deletions lib/src/command_runner.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import 'package:pub_updater/pub_updater.dart';
import 'package:webtrit_phone_tools/src/commands/commands.dart';
import 'package:webtrit_phone_tools/src/version.dart';

import 'commands/app_resources/interceptors/interceptors.dart';
import 'commands/constants.dart';
import 'utils/utils.dart';

Expand All @@ -32,18 +33,7 @@ class WebtritPhoneToolsCommandRunner extends CompletionCommandRunner<int> {
PubUpdater? pubUpdater,
}) : _logger = logger ?? Logger(),
_httpClient = httpClient ?? HttpClient(configuratorApiUrl, Logger()),
_datasource = datasource ??
ConfiguratorBackandDatasource(
Dio(BaseOptions(baseUrl: 'https://us-central1-webtrit-configurator.cloudfunctions.net/api/v1'))
..interceptors.add(
LogInterceptor(
requestBody: true,
responseBody: true,
logPrint: print,
),
),
UnauthorizedInterceptor(),
),
_datasource = datasource ?? _buildDefaultDatasource(),
_keystoreReadmeUpdater = keystoreReadmeUpdater ?? KeystoreReadmeUpdater(Logger()),
_pubUpdater = pubUpdater ?? PubUpdater(),
super(executableName, description) {
Expand Down Expand Up @@ -79,6 +69,17 @@ class WebtritPhoneToolsCommandRunner extends CompletionCommandRunner<int> {
addCommand(UpdateCommand(logger: _logger, pubUpdater: _pubUpdater));
}

static ConfiguratorBackandDatasource _buildDefaultDatasource() {
final dio = Dio(BaseOptions(baseUrl: 'https://us-central1-webtrit-configurator.cloudfunctions.net/api/v1'))
..interceptors.add(LogInterceptor(
requestBody: true,
responseBody: true,
logPrint: print,
));
dio.interceptors.add(RetryInterceptor(dio: dio));
return ConfiguratorBackandDatasource(dio, UnauthorizedInterceptor());
}

@override
void printUsage() => _logger.info(usage);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export 'retry_interceptor.dart';
64 changes: 64 additions & 0 deletions lib/src/commands/app_resources/interceptors/retry_interceptor.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import 'package:data/datasource/datasource.dart';

class RetryInterceptor extends Interceptor {
RetryInterceptor({
required Dio dio,
int maxRetries = 3,
List<int> retryDelaysMs = const [2000, 4000, 8000],
}) : assert(retryDelaysMs.length >= maxRetries, 'retryDelaysMs must contain at least maxRetries entries'),
_dio = dio,
_maxRetries = maxRetries,
_retryDelaysMs = retryDelaysMs;

static const _retryCountKey = 'retryCount';

final Dio _dio;
final int _maxRetries;
final List<int> _retryDelaysMs;

@override
void onError(DioException err, ErrorInterceptorHandler handler) => _handleError(err, handler);

Future<void> _handleError(DioException err, ErrorInterceptorHandler handler) async {
try {
if (_isUnauthorized(err)) {
handler.reject(_buildUnauthorizedException(err));
return;
}

final retryCount = (err.requestOptions.extra[_retryCountKey] as int?) ?? 0;

if (!_shouldRetry(err) || retryCount >= _maxRetries) {
handler.next(err);
return;
}

await Future<void>.delayed(Duration(milliseconds: _retryDelaysMs[retryCount]));
err.requestOptions.extra[_retryCountKey] = retryCount + 1;
handler.resolve(await _dio.fetch(err.requestOptions));
} on DioException catch (e) {
handler.next(e);
} catch (_) {
handler.next(err);
}
}

bool _isUnauthorized(DioException err) => err.response?.statusCode == 401;

bool _shouldRetry(DioException err) => _isServerError(err) || _isConnectionError(err);

bool _isServerError(DioException err) => (err.response?.statusCode ?? 0) >= 500;

bool _isConnectionError(DioException err) =>
err.type == DioExceptionType.connectionTimeout ||
err.type == DioExceptionType.sendTimeout ||
err.type == DioExceptionType.receiveTimeout ||
err.type == DioExceptionType.connectionError;

DioException _buildUnauthorizedException(DioException err) => DioException(
requestOptions: err.requestOptions,
response: err.response,
type: err.type,
error: Exception('Authentication token has expired.'),
);
}
Loading