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
6 changes: 4 additions & 2 deletions lib/bloc/app_bloc_root.dart
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,8 @@ class AppBlocRoot extends StatelessWidget {
),
),
BlocProvider<SystemHealthBloc>(
create: (_) => SystemHealthBloc(SystemClockRepository(), mm2Api),
create: (_) => SystemHealthBloc(SystemClockRepository(), mm2Api)
..add(SystemHealthPeriodicCheckStarted()),
),
BlocProvider<TrezorInitBloc>(
create: (context) => TrezorInitBloc(
Expand All @@ -300,7 +301,8 @@ class AppBlocRoot extends StatelessWidget {
),
),
BlocProvider<FaucetBloc>(
create: (context) => FaucetBloc(kdfSdk: context.read<KomodoDefiSdk>()),
create: (context) =>
FaucetBloc(kdfSdk: context.read<KomodoDefiSdk>()),
)
],
child: _MyAppView(),
Expand Down
101 changes: 101 additions & 0 deletions lib/bloc/system_health/providers/binance_time_provider.dart
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 lib/bloc/system_health/providers/http_head_time_provider.dart
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 lib/bloc/system_health/providers/http_time_provider.dart
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),
);
}
Comment thread
takenagain marked this conversation as resolved.

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
}
Loading
Loading