Skip to content

Commit 8bae795

Browse files
committed
add timeout on ws connection
1 parent 0945062 commit 8bae795

3 files changed

Lines changed: 38 additions & 4 deletions

File tree

lib/src/http/client_link.dart

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -227,10 +227,14 @@ class HttpClientLink extends ClientLink {
227227
wsUrl = '$wsUrl$tokenHash';
228228
}
229229

230-
var socket = await HttpHelper.connectToWebSocket(
231-
wsUrl,
232-
useStandardWebSocket: useStandardWebSocket
233-
);
230+
var socket = await awaitWithTimeout(
231+
HttpHelper.connectToWebSocket(wsUrl,
232+
useStandardWebSocket: useStandardWebSocket),
233+
// websocket initialization should take no more than 60 seconds
234+
60000,
235+
(WebSocket socket){socket.close();},
236+
(err){}
237+
);
234238

235239
_wsConnection = new WebSocketConnection(
236240
socket,

lib/src/utils/promise_timeout.dart

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
part of dslink.utils;
2+
3+
Future<T> awaitWithTimeout<T>(Future<T> future, int timeoutMs,
4+
Function onSuccessAfterTimeout, Function onErrorAfterTimeout) {
5+
Completer<T> completer = new Completer();
6+
7+
Timer timer = new Timer(new Duration(milliseconds: timeoutMs), () {
8+
if (!completer.isCompleted) {
9+
completer.completeError(new Exception('Future timeout before complete'));
10+
}
11+
});
12+
future.then((T t) {
13+
if (completer.isCompleted) {
14+
onSuccessAfterTimeout(t);
15+
} else {
16+
timer.cancel();
17+
completer.complete(t);
18+
}
19+
}).catchError((err) {
20+
if (completer.isCompleted) {
21+
onErrorAfterTimeout(err);
22+
} else {
23+
timer.cancel();
24+
completer.completeError(err);
25+
}
26+
});
27+
28+
return completer.future;
29+
}

lib/utils.dart

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ part "src/utils/codec.dart";
1717
part "src/utils/dslink_json.dart";
1818
part "src/utils/list.dart";
1919
part "src/utils/uri_component.dart";
20+
part "src/utils/promise_timeout.dart";
2021

2122
typedef ExecutableFunction();
2223
typedef T Producer<T>();

0 commit comments

Comments
 (0)