Skip to content

Commit

Permalink
fix: reconnecting websocket checks connection state on each request (#…
Browse files Browse the repository at this point in the history
…1553)

* fix: reconnecting websocket checks connection state on each request

* [substrate_api] `ReconnectingWebsocketProvider` fix things for good.

* [send_tx_dart] fix channel check in disconnect method
  • Loading branch information
clangenb authored Nov 20, 2023
1 parent 1069aba commit af5b538
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions app/lib/service/substrate_api/api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,13 @@ class Api {
}

class ReconnectingWsProvider extends Provider {
ReconnectingWsProvider(Uri url, {bool autoConnect = true}) : provider = WsProvider(url, autoConnect: autoConnect);
ReconnectingWsProvider(this.url, {bool autoConnect = true})
: provider = WsProvider(
url,
autoConnect: autoConnect,
);

final Uri url;
WsProvider provider;

Future<void> connectToNewEndpoint(Uri url) async {
Expand All @@ -256,26 +261,37 @@ class ReconnectingWsProvider extends Provider {
if (isConnected()) {
return Future.value();
} else {
return connect();
// We want to use a new channel even if the channel exists but it was closed.
provider.channel = null;
provider = WsProvider(url, autoConnect: false);
return provider.connect();
}
}

@override
Future disconnect() {
if (!isConnected()) {
// We only care if the channel is not equal to null.
// Because we still want the internal cleanup if
// the connection was closed from the other end.
if (provider.channel == null) {
return Future.value();
} else {
return disconnect();
return provider.disconnect();
}
}

@override
bool isConnected() {
return provider.isConnected();
// the `provider.isConnected()` check is wrong upstream.
// Hence, we implement it ourselves.
final channel = provider.channel;
return channel != null && channel.closeCode == null;
}

@override
Future<RpcResponse> send(String method, List<dynamic> params) {
Future<RpcResponse> send(String method, List<dynamic> params) async {
// Connect if disconnected
await connect();
return provider.send(method, params);
}

Expand All @@ -284,7 +300,9 @@ class ReconnectingWsProvider extends Provider {
String method,
List<dynamic> params, {
FutureOr<void> Function(String subscription)? onCancel,
}) {
}) async {
// Connect if disconnected
await connect();
return provider.subscribe(method, params, onCancel: onCancel);
}
}

0 comments on commit af5b538

Please sign in to comment.