-
Notifications
You must be signed in to change notification settings - Fork 250
fix(system-health-check): add additional time providers and update URLs of existing providers #2611
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
6b12fd6
feat(system-health): add NTP and HTTP header time providers
takenagain 9d60199
test(system-health): add unit tests for system clock providers
takenagain cde2662
chore(deps): add ntp package dependency and reorder imports
takenagain dd49c34
refactor(system-health): rename events & move logging init to bootstrap
takenagain dada2cd
fix(system-health): add binance time provider for web
takenagain c630f86
refactor: change method return type and implement ai review suggestions
takenagain 3d66ca6
fix(system-health): show banner if clock invalid even if peers >= 2
takenagain 8b3d95c
refactor: simplify datetime parsing and revert exception regression
takenagain 3b6196e
refactor: remove shared http client to avoid issues with multiple closes
takenagain File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
101 changes: 101 additions & 0 deletions
101
lib/bloc/system_health/providers/binance_time_provider.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import 'dart:async' show TimeoutException; | ||
| import 'dart:convert'; | ||
| import 'dart:io'; | ||
|
|
||
| import 'package:http/http.dart' as http; | ||
| import 'package:logging/logging.dart'; | ||
| import 'package:web_dex/bloc/system_health/providers/time_provider.dart'; | ||
|
|
||
| /// A time provider that fetches time from the Binance API | ||
| class BinanceTimeProvider extends TimeProvider { | ||
| BinanceTimeProvider({ | ||
| this.url = 'https://api.binance.com/api/v3/time', | ||
| http.Client? httpClient, | ||
| this.timeout = const Duration(seconds: 2), | ||
| this.maxRetries = 3, | ||
| Logger? logger, | ||
| }) : _httpClient = httpClient ?? http.Client(), | ||
| _logger = logger ?? Logger('BinanceTimeProvider'); | ||
|
|
||
| /// The URL of the Binance time API | ||
| final String url; | ||
|
|
||
| /// Timeout for HTTP requests | ||
| final Duration timeout; | ||
|
|
||
| /// Maximum retries | ||
| final int maxRetries; | ||
|
|
||
| /// Logger instance | ||
| final Logger _logger; | ||
|
|
||
| /// HTTP client for making requests | ||
| final http.Client _httpClient; | ||
|
|
||
| @override | ||
| String get name => 'Binance'; | ||
|
|
||
| @override | ||
| Future<DateTime> getCurrentUtcTime() async { | ||
| int retries = 0; | ||
|
|
||
| while (retries < maxRetries) { | ||
| try { | ||
| final serverTime = await _fetchServerTime(); | ||
| _logger.fine('Successfully retrieved time from Binance API'); | ||
| return serverTime; | ||
| } on SocketException catch (e, s) { | ||
| _logger.warning('Socket error with Binance API', e, s); | ||
| } on TimeoutException catch (e, s) { | ||
| _logger.warning('Timeout with Binance API', e, s); | ||
| } on FormatException catch (e, s) { | ||
| _logger.severe('Failed to parse response from Binance API', e, s); | ||
| } on Exception catch (e, s) { | ||
| _logger.severe('Error fetching time from Binance API', e, s); | ||
| } | ||
| retries++; | ||
|
|
||
| // Calculate exponential backoff: 100ms, 200ms, 400ms, 800ms... | ||
| if (retries < maxRetries) { | ||
| final delayDuration = Duration(milliseconds: 100 * (1 << retries)); | ||
| await Future<void>.delayed(delayDuration); | ||
| } | ||
| } | ||
|
|
||
| _logger.severe( | ||
| 'Failed to get time from Binance API after $maxRetries retries', | ||
| ); | ||
| throw TimeoutException( | ||
| 'Failed to get time from Binance API after $maxRetries retries', | ||
| ); | ||
| } | ||
|
|
||
| /// Fetches server time from the Binance API | ||
| Future<DateTime> _fetchServerTime() async { | ||
| final response = await _httpClient.get(Uri.parse(url)).timeout(timeout); | ||
|
|
||
| if (response.statusCode != 200) { | ||
| _logger.warning('HTTP error from $url: ${response.statusCode}'); | ||
| throw HttpException( | ||
| 'HTTP error from $url: ${response.statusCode}', | ||
| uri: Uri.parse(url), | ||
| ); | ||
| } | ||
|
|
||
| final jsonData = jsonDecode(response.body) as Map<String, dynamic>; | ||
| final serverTime = jsonData['serverTime'] as int?; | ||
|
|
||
| if (serverTime == null) { | ||
| throw const FormatException( | ||
| 'No serverTime field in Binance API response', | ||
| ); | ||
| } | ||
|
|
||
| return DateTime.fromMillisecondsSinceEpoch(serverTime, isUtc: true); | ||
| } | ||
|
|
||
| @override | ||
| void dispose() { | ||
| _httpClient.close(); | ||
| } | ||
| } |
107 changes: 107 additions & 0 deletions
107
lib/bloc/system_health/providers/http_head_time_provider.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| import 'dart:async' show TimeoutException; | ||
| import 'dart:io'; | ||
| import 'dart:math' show Random; | ||
|
|
||
| import 'package:http/http.dart' as http; | ||
| import 'package:logging/logging.dart'; | ||
| import 'package:web_dex/bloc/system_health/providers/time_provider.dart'; | ||
|
|
||
| /// A time provider that fetches time from server 'Date' headers via HEAD requests | ||
| class HttpHeadTimeProvider extends TimeProvider { | ||
| HttpHeadTimeProvider({ | ||
| this.servers = const [ | ||
| 'https://alibaba.com/', | ||
| 'https://google.com/', | ||
| 'https://cloudflare.com/', | ||
| 'https://microsoft.com/', | ||
| 'https://github.com/', | ||
| ], | ||
| http.Client? httpClient, | ||
| this.timeout = const Duration(seconds: 2), | ||
| this.maxRetries = 3, | ||
| Logger? logger, | ||
| }) : _httpClient = httpClient ?? http.Client(), | ||
| _logger = logger ?? Logger('HttpHeadTimeProvider'); | ||
|
|
||
| /// The name of the provider (for logging and identification) | ||
| final Logger _logger; | ||
|
|
||
| /// List of servers to query via HEAD requests | ||
| final List<String> servers; | ||
|
|
||
| /// Timeout for HTTP requests | ||
| final Duration timeout; | ||
|
|
||
| /// Maximum retries per server | ||
| final int maxRetries; | ||
|
|
||
| final http.Client _httpClient; | ||
|
|
||
| @override | ||
| String get name => 'HttpHead'; | ||
|
|
||
| @override | ||
| Future<DateTime> getCurrentUtcTime() async { | ||
| // Randomize the order of servers to avoid overloading any single server | ||
| // and to provide a more even distribution of requests. | ||
| // This also avoid a single server being a single point of failure. | ||
| final shuffledServers = List<String>.from(servers)..shuffle(Random()); | ||
| _logger.fine('Randomized server order for time retrieval'); | ||
|
|
||
| for (final serverUrl in shuffledServers) { | ||
| int retries = 0; | ||
|
|
||
| while (retries < maxRetries) { | ||
| try { | ||
| final serverTime = await _fetchServerTime(serverUrl); | ||
| _logger.fine('Successfully retrieved time from $serverUrl'); | ||
| return serverTime; | ||
| } on SocketException catch (e, s) { | ||
| _logger.warning('Socket error with $serverUrl', e, s); | ||
| } on TimeoutException catch (e, s) { | ||
| _logger.warning('Timeout with $serverUrl', e, s); | ||
| } on HttpException catch (e, s) { | ||
| _logger.warning('HTTP error with $serverUrl', e, s); | ||
| } on FormatException catch (e, s) { | ||
| _logger.warning('Date header parse error with $serverUrl', e, s); | ||
| } | ||
| retries++; | ||
| } | ||
| } | ||
|
|
||
| _logger | ||
| .severe('Failed to get time from any server after $maxRetries retries'); | ||
| throw TimeoutException( | ||
| 'Failed to get time from any server after $maxRetries retries', | ||
| ); | ||
| } | ||
|
|
||
| /// Fetches server time from the 'date' header of an HTTP HEAD response | ||
| Future<DateTime> _fetchServerTime(String url) async { | ||
| final response = await _httpClient.head(Uri.parse(url)).timeout(timeout); | ||
|
|
||
| // Treat any successful or redirect status as acceptable. | ||
| if (response.statusCode < 200 || response.statusCode >= 400) { | ||
| _logger.warning('HTTP error from $url: ${response.statusCode}'); | ||
| throw HttpException( | ||
| 'HTTP error from $url: ${response.statusCode}', | ||
| uri: Uri.parse(url), | ||
| ); | ||
| } | ||
|
|
||
| final dateHeader = response.headers['date']; | ||
| if (dateHeader == null) { | ||
| _logger.warning('No Date header in response from $url'); | ||
| throw FormatException('No Date header in response from $url'); | ||
| } | ||
|
|
||
| final parsed = HttpDate.parse(dateHeader); | ||
| return parsed.toUtc(); | ||
| } | ||
|
|
||
| /// Disposes the HTTP client when done | ||
| @override | ||
| void dispose() { | ||
| _httpClient.close(); | ||
| } | ||
| } |
115 changes: 115 additions & 0 deletions
115
lib/bloc/system_health/providers/http_time_provider.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import 'dart:convert'; | ||
| import 'dart:io'; | ||
|
|
||
| import 'package:http/http.dart' as http; | ||
| import 'package:logging/logging.dart'; | ||
| import 'package:web_dex/bloc/system_health/providers/time_provider.dart'; | ||
|
|
||
| /// A time provider that fetches time from an HTTP API | ||
| class HttpTimeProvider extends TimeProvider { | ||
| HttpTimeProvider({ | ||
| required this.url, | ||
| required this.timeFieldPath, | ||
| required this.timeFormat, | ||
| required String providerName, | ||
| http.Client? httpClient, | ||
| Duration? apiTimeout, | ||
| Logger? logger, | ||
| }) : _httpClient = httpClient ?? http.Client(), | ||
| _apiTimeout = apiTimeout ?? const Duration(seconds: 2), | ||
| name = providerName, | ||
| _logger = logger ?? Logger(providerName); | ||
|
|
||
| /// The URL of the time API | ||
| final String url; | ||
|
|
||
| /// The field path in the JSON response that contains the time. | ||
| /// | ||
| /// Separate nested fields with dots (e.g., "time.current") | ||
| final String timeFieldPath; | ||
|
|
||
| /// The format of the time string in the response | ||
| final TimeFormat timeFormat; | ||
|
|
||
| /// The name of the provider (for logging and identification) | ||
| @override | ||
| final String name; | ||
|
|
||
| final Logger _logger; | ||
|
|
||
| final http.Client _httpClient; | ||
| final Duration _apiTimeout; | ||
|
|
||
| @override | ||
| Future<DateTime> getCurrentUtcTime() async { | ||
| final response = await _httpClient.get(Uri.parse(url)).timeout(_apiTimeout); | ||
|
|
||
| if (response.statusCode != 200) { | ||
| _logger.warning('API request failed with status ${response.statusCode}'); | ||
| throw HttpException( | ||
| 'API request failed with status ${response.statusCode}', | ||
| uri: Uri.parse(url), | ||
| ); | ||
| } | ||
|
|
||
| final dynamic decoded = json.decode(response.body); | ||
| if (decoded is! Map<String, dynamic>) { | ||
| _logger.warning( | ||
| 'Expected top-level JSON object, got ${decoded.runtimeType}', | ||
| ); | ||
| throw const FormatException('Invalid JSON structure – object expected'); | ||
| } | ||
| final Map<String, dynamic> jsonResponse = decoded; | ||
| final parsedTime = await _parseTimeFromJson(jsonResponse); | ||
|
|
||
| return parsedTime; | ||
| } | ||
|
|
||
| Future<DateTime> _parseTimeFromJson(Map<String, dynamic> jsonResponse) async { | ||
| final fieldParts = timeFieldPath.split('.'); | ||
| dynamic value = jsonResponse; | ||
|
|
||
| for (final part in fieldParts) { | ||
| if (value is! Map<String, dynamic>) { | ||
| _logger.warning('JSON path error: expected Map at $part'); | ||
| throw FormatException('JSON path error: expected Map at $part'); | ||
| } | ||
| value = value[part]; | ||
| if (value == null) { | ||
| _logger.warning('JSON path error: null value at $part'); | ||
| throw FormatException('JSON path error: null value at $part'); | ||
| } | ||
| } | ||
|
|
||
| final timeStr = value.toString(); | ||
| if (timeStr.isEmpty) { | ||
| _logger.warning('Empty time string'); | ||
| throw const FormatException('Empty time string'); | ||
| } | ||
|
|
||
| return _parseDateTime(timeStr); | ||
| } | ||
|
|
||
| DateTime _parseDateTime(String timeStr) { | ||
| switch (timeFormat) { | ||
| case TimeFormat.iso8601: | ||
| return DateTime.parse(timeStr).toUtc(); | ||
| case TimeFormat.custom: | ||
| throw const FormatException('Custom time format not supported'); | ||
| } | ||
| } | ||
|
|
||
| @override | ||
| void dispose() { | ||
| _httpClient.close(); | ||
| } | ||
| } | ||
|
|
||
| /// Enum representing the format of time returned by the API | ||
| enum TimeFormat { | ||
| /// ISO8601 format (e.g. "2023-05-07T12:34:56Z") | ||
| iso8601, | ||
|
|
||
| /// Custom format that may require special parsing | ||
| custom | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.