8000 fix(sync): eliminate error-flood, silent stalls, and lost-progress restarts in P2P sync by ahmet-cetinkaya · Pull Request #303 · ahmet-cetinkaya/whph · GitHub
[go: up one dir, main page]

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
8000
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ class DeviceHandshakeService {
final uri = Uri.parse('ws://$ipAddress:$port');
channel = WebSocketChannel.connect(uri);

// Await readiness explicitly and handle the error here. Otherwise
// channel.ready's error completion is never observed and Dart
// reports it as an unhandled async error to the global zone handler,
// on top of the expected onError callback below - doubling log noise
// for every unreachable IP during LAN device discovery.
try {
await channel.ready;
} catch (e) {
Logger.debug('WebSocket connection failed during handshake with $ipAddress:$port - $e');
return null;
}

// Set up a completer for the response
final completer = Completer<DeviceInfo?>();

Expand Down Expand Up @@ -80,7 +92,12 @@ class DeviceHandshakeService {
}
},
onError: (error) {
Logger.error('WebSocket error during handshake: $error');
// Expected during LAN device discovery: most scanned IPs are not
// running WHPH, so "No route to host" / "Connection refused" here
// is normal and not worth surfacing as an ERROR (or to the global
// zone error handler) - it would otherwise flood the log for every
// unreachable address in the scanned subnet.
Logger.debug('WebSocket error during handshake: $error');
if (!completer.isCompleted) {
completer.complete(null);
}
Expand Down
8000
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,29 @@ import 'package:whph/core/domain/shared/utils/logger.dart';
/// - [SyncDtoSerializer] for DTO-to-JSON conversion
/// - [SyncMessageSerializer] for WebSocket message handling
class SyncCommunicationService implements ISyncCommunicationService {
static const int _maxRetries = 3;
static const int _baseTimeoutSeconds = 15;
static const int _websocketPort = 44040;
static const int _defaultWebsocketPort = 44040;

final SyncDtoSerializer _dtoSerializer = SyncDtoSerializer();
final SyncMessageSerializer _messageSerializer = SyncMessageSerializer();

SyncCommunicationService() {
final int _maxRetries;
final Duration _baseTimeout;
final Duration Function(int attempt) _retryBackoff;
final int _websocketPort;

SyncCommunicationService({
int maxRetries = 3,
Duration baseTimeout = const Duration(seconds: 15),
Duration Function(int attempt)? retryBackoff,
int websocketPort = _defaultWebsocketPort,
}) : _maxRetries = maxRetries,
_baseTimeout = baseTimeout,
_retryBackoff = retryBackoff ?? _defaultRetryBackoff,
_websocketPort = websocketPort {
Logger.info('SyncCommunicationService initialized');
}

static Duration _defaultRetryBackoff(int attempt) => Duration(seconds: attempt * 2);

@override
Future<SyncCommunicationResponse> sendPaginatedDataToDevice(String ipAddress, PaginatedSyncDataDto dto) async {
final entityType = dto.entityType;
Expand All @@ -37,7 +49,7 @@ class SyncCommunicationService implements ISyncCommunicationService {
while (attempt < _maxRetries) {
WebSocket? socket;
try {
final timeout = Duration(seconds: _baseTimeoutSeconds * (attempt + 1));
final timeout = _baseTimeout * (attempt + 1);
socket = await WebSocket.connect(getWebSocketUrl(ipAddress)).timeout(timeout);

final response = await _executeSync(
Expand All @@ -49,13 +61,18 @@ class SyncCommunicationService implements ISyncCommunicationService {
startTime: startTime,
);

// Close our end explicitly. A sync of ~250 pages opens a connection
// per page; leaving the successful ones for the peer to tear down
// holds sockets open against the server's connection limits longer
// than necessary.
await socket.close();
return response;
} catch (e) {
attempt++;
final totalTime = DateTime.now().difference(startTime).inMilliseconds;
Logger.warning('WebSocket attempt $attempt failed after ${totalTime}ms: $e');

await socket?.close();
_closeSocket(socket);

if (attempt >= _maxRetries) {
Logger.error('All WebSocket attempts failed. Final error: $e');
Expand All @@ -66,7 +83,7 @@ class SyncCommunicationService implements ISyncCommunicationService {
);
}

final backoffDelay = Duration(seconds: attempt * 2);
final backoffDelay = _retryBackoff(attempt);
Logger.debug('Waiting ${backoffDelay.inSeconds}s before retry...');
await Future.delayed(backoffDelay);
}
Expand All @@ -89,18 +106,16 @@ class SyncCommunicationService implements ISyncCommunicationService {
required DateTime startTime,
}) async {
final completer = Completer<SyncCommunicationResponse>();
Timer? timeoutTimer;
unawaited(completer.future.then<void>((_) {}, onError: (_, __) {}));
late final Timer timeoutTimer;

timeoutTimer = Timer(timeout, () {
if (!completer.isCompleted) {
Logger.error('⏰ WebSocket timeout after ${timeout.inSeconds} seconds (attempt ${attempt + 1}/$_maxRetries)');
completer.complete(SyncCommunicationResponse(
success: false,
isComplete: true,
error: 'Operation failed',
));
socket.close();
}
timeoutTimer = Timer(timeout, () async {
if (completer.isCompleted) return;

final message = 'WebSocket timeout after ${timeout.inSeconds} seconds (attempt ${attempt + 1}/$_maxRetries)';
Logger.error('⏰ $message');
completer.completeError(TimeoutException(message, timeout));
_closeSocket(socket);
});

// Convert DTO to JSON
Expand Down Expand Up @@ -132,8 +147,9 @@ class SyncCommunicationService implements ISyncCommunicationService {
Logger.debug('Sending message via WebSocket (${serializedMessage.length} bytes)');
socket.add(serializedMessage);

// Listen for response
await for (final responseMessage in socket) {
socket.listen((responseMessage) async {
if (completer.isCompleted) return;

try {
final responseTime = DateTime.now().difference(transmissionStartTime).inMilliseconds;
Logger.debug(
Expand All @@ -142,21 +158,27 @@ class SyncCommunicationService implements ISyncCommunicationService {

final response = await _processResponse(responseMessage, timeoutTimer, startTime);
if (response != null) {
completer.complete(response);
break;
if (!completer.isCompleted) {
completer.complete(response);
}
}
} catch (e) {
Logger.error('Error processing WebSocket response: $e');
completer.complete(SyncCommunicationResponse(
success: false,
isComplete: true,
error: 'Operation failed',
));
break;
if (!completer.isCompleted) {
completer.complete(SyncCommunicationResponse(
success: false,
isComplete: true,
error: 'Operation failed',
));
}
}
}
}, onError: (Object error, StackTrace stackTrace) {
if (!completer.isCompleted) {
completer.completeError(error, stackTrace);
}
});

return await completer.future;
return completer.future;
}

/// Processes a WebSocket response message
Expand Down Expand Up @@ -292,4 +314,12 @@ class SyncCommunicationService implements ISyncCommunicationService {
Future<void> _yieldToUIThread() async {
await Future.delayed(Duration.zero);
}

void _closeSocket(WebSocket? socket) {
if (socket == null) return;

unawaited(socket.close().catchError((Object error, StackTrace stackTrace) {
Logger.warning('Failed to close WebSocket: $error');
}));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ class _BuildSendResult {
/// Implementation of sync pagination service
/// Orchestrates sync operations by delegating to specialized helpers
class SyncPaginationService implements ISyncPaginationService {
/// How many times a single page is attempted before the entity sync is
/// abandoned. The communication layer already retries the transport itself
/// (3 attempts with escalating timeouts), so this only covers a page that
/// failed even after those. Kept at 2 deliberately: the two layers multiply,
/// and a higher value would stall the sync for many minutes on a peer that
/// has genuinely gone away.
static const int _maxPageAttempts = 2;

/// Base delay between page re-attempts, multiplied by the attempt number.
static const Duration _pageRetryBackoff = Duration(seconds: 2);

final ISyncCommunicationService _communicationService;
final ISyncConfigurationService _configurationService;

Expand Down Expand Up @@ -101,7 +112,7 @@ class SyncPaginationService implements ISyncPaginationService {

while (hasMorePages && !_isSyncCancelled) {
try {
final pageResult = await _syncNextPage(
final pageResult = await _syncPageWithRetries(
config: config,
syncDevice: syncDevice,
targetIp: targetIp,
Expand Down Expand Up @@ -251,6 +262,54 @@ class SyncPaginationService implements ISyncPaginationService {
_serverPaginationHandler.validateAndCleanStalePendingData();
}

/// Syncs a single page, re-attempting the same page a few times before
/// giving up on the whole entity.
///
/// Without this, one transient page failure discards every page already
/// accepted by the peer: the entity fails, the device fails, lastSyncDate
/// is never written, and the next run restarts the entire initial sync from
/// page 0. Re-sending only the failed page keeps prior progress.
Future<_PageSyncResult> _syncPageWithRetries({
required PaginatedSyncConfig config,
required SyncDevice syncDevice,
required String targetIp,
required DateTime effectiveLastSyncDate,
required int pageIndex,
required int lastReceivedServerPage,
required int totalServerPages,
}) async {
for (int attempt = 1; attempt <= _maxPageAttempts; attempt++) {
final pageResult = await _syncNextPage(
config: config,
syncDevice: syncDevice,
targetIp: targetIp,
effectiveLastSyncDate: effectiveLastSyncDate,
pageIndex: pageIndex,
lastReceivedServerPage: lastReceivedServerPage,
totalServerPages: totalServerPages,
);

if (pageResult.success) return pageResult;

if (_isSyncCancelled) {
Logger.warning('Sync for ${config.name} was cancelled while retrying page $pageIndex');
return pageResult;
}

if (attempt == _maxPageAttempts) {
Logger.error('${config.name} page $pageIndex failed after $attempt attempts, aborting entity sync');
return pageResult;
}

final backoff = _pageRetryBackoff * attempt;
Logger.warning(
'${config.name} page $pageIndex failed (attempt $attempt/$_maxPageAttempts), retrying in ${backoff.inSeconds}s');
await Future.delayed(backoff);
}

throw StateError('Unreachable: page retry loop exited without a result');
}

/// Result of syncing a single page
Future<_PageSyncResult> _syncNextPage({
required PaginatedSyncConfig config,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class SyncService implements ISyncService {
Timer? _reconnectTimer;
int _reconnectAttempts = 0;
static const int _maxReconnectAttempts = 3;
bool _syncInProgress = false;

@override
Stream<bool> get _syncCompleteController.stream;
Expand Down Expand Up @@ -96,6 +97,12 @@ class SyncService implements ISyncService {
/// Runs paginated sync operation - this is now the primary sync method
@override
Future<void> runPaginatedSync({bool isManual = false}) async {
if (_syncInProgress) {
Logger.debug('Sync already in progress, ignoring duplicate runPaginatedSync call (manual: $isManual)');
return;
}
_syncInProgress = true;

try {
// Update sync status to syncing
updateSyncStatus(SyncStatus(
Expand Down Expand Up @@ -206,6 +213,8 @@ class SyncService implements ISyncService {

// Schedule reset to idle after error delay
_scheduleErrorReset();
} finally {
_syncInProgress = false;
}
}

Expand Down
1 change: 0 additions & 1 deletion src/lib/presentation/api/api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ void startWebSocketServer() async {

ws.listen(
(data) async {
Logger.debug('Received message: $data');
await _handleWebSocketMessage(data.toString(), ws);
},
onError: (e) {
Expand Down
Loading
Loading
0