Skip to content
This repository has been archived by the owner on Jul 24, 2024. It is now read-only.

Commit

Permalink
fix: Error if closing the socket while it's being opened
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmartos96 committed Jun 20, 2024
1 parent 2692f73 commit a46caed
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion packages/electricsql/lib/src/sockets/sockets.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ abstract class WebSocketBase implements Socket {
void Function(CloseEvent)? _closeListener;
void Function(Data data)? _messageListener;

// A way to signal an error when the socket is being opened
Completer<void>? _openingSocketErrorCompleter;

WebSocketBase(this.protocolVsn);

// event doesn't provide much
Expand Down Expand Up @@ -112,9 +115,13 @@ abstract class WebSocketBase implements Socket {
);
}

_openingSocketErrorCompleter = Completer<void>();
try {
_channel = createSocketChannel(opts.url);
await _channel!.ready;
await Future.any([
_channel!.ready,
_openingSocketErrorCompleter!.future,
]);
} catch (e) {
_notifyErrorAndCloseSocket(
error: SatelliteException(
Expand All @@ -124,6 +131,8 @@ abstract class WebSocketBase implements Socket {
stackTrace: StackTrace.current,
);
return;
} finally {
_openingSocketErrorCompleter = null;
}

// Notify connected
Expand Down Expand Up @@ -231,6 +240,15 @@ abstract class WebSocketBase implements Socket {
}

void _socketClose() {
// Check if the socket is in the process of opening
if (_openingSocketErrorCompleter != null) {
if (!_openingSocketErrorCompleter!.isCompleted) {
_openingSocketErrorCompleter!.completeError(
Exception('socket closed before it was opened'),
);
}
}

for (final subscription in _subscriptions) {
subscription.cancel();
}
Expand Down

0 comments on commit a46caed

Please sign in to comment.