@@ -34,12 +34,17 @@ class DataSyncController {
34
34
this . eventListeners = {
35
35
message : [ ] ,
36
36
close : [ ] ,
37
- reconnect : [ ]
37
+ reconnect : [ ] ,
38
+ open : [ ]
38
39
} ;
39
40
40
41
// We store messages here that cannot be send because the connection is not available
41
42
this . outbox = [ ] ;
42
43
this . reconnectTimeout = null ;
44
+
45
+ // Every message from the client expects a reply from the server
46
+ // If that doesn't arrive in time, we can expect the connection to be broken
47
+ this . pendingRequestTimeout = null ;
43
48
44
49
this . dataSubscriptions = [ ] ;
45
50
@@ -63,12 +68,16 @@ class DataSyncController {
63
68
const connect = ( ) => new Promise ( ( resolve , reject ) => {
64
69
const socket = new WebSocket ( DataSyncController . getWSUrl ( ) )
65
70
66
- socket . onopen = ( ) => {
71
+ socket . onopen = event => {
67
72
// These handlers should only be installed once the connection is established
68
73
socket . onclose = this . onClose . bind ( this ) ;
69
74
socket . onmessage = this . onMessage . bind ( this ) ;
70
75
71
76
resolve ( socket ) ;
77
+
78
+ for ( const listener of this . eventListeners . open ) {
79
+ listener ( event ) ;
80
+ }
72
81
}
73
82
74
83
socket . onerror = ( event ) => reject ( event ) ;
@@ -115,6 +124,11 @@ class DataSyncController {
115
124
116
125
this . receivedFirstResponse = true ;
117
126
127
+ if ( this . pendingRequestTimeout ) {
128
+ clearTimeout ( this . pendingRequestTimeout ) ;
129
+ this . pendingRequestTimeout = null ;
130
+ }
131
+
118
132
if ( request ) {
119
133
const { resolve, reject } = request ;
120
134
@@ -156,6 +170,10 @@ class DataSyncController {
156
170
}
157
171
} else {
158
172
this . connection . send ( JSON . stringify ( payload ) ) ;
173
+
174
+ if ( ! this . pendingRequestTimeout ) {
175
+ this . pendingRequestTimeout = setTimeout ( this . onPendingRequestTimeout . bind ( this ) , 5000 ) ;
176
+ }
159
177
}
160
178
} ) ;
161
179
}
@@ -198,6 +216,14 @@ class DataSyncController {
198
216
}
199
217
}
200
218
}
219
+
220
+ onPendingRequestTimeout ( ) {
221
+ if ( this . connection ) {
222
+ console . log ( 'Pending request timed out, closing WebSocket' ) ;
223
+ this . connection . close ( ) ;
224
+ this . onClose ( null ) ;
225
+ }
226
+ }
201
227
}
202
228
203
229
const APPEND_NEW_RECORD = 0 ;
0 commit comments