@@ -24,8 +24,14 @@ const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
2424
2525// Keep alive message is sent every period
2626const KEEP_ALIVE_MS = 20_000 ;
27- // The ACK must be received in this period
28- const KEEP_ALIVE_LIFETIME_MS = 30_000 ;
27+
28+ // One message of any type must be received in this period.
29+ const SOCKET_TIMEOUT_MS = 30_000 ;
30+
31+ // One keepalive message must be received in this period.
32+ // If there is a backlog of messages (for example on slow connections), keepalive messages could be delayed
33+ // significantly. Therefore this is longer than the socket timeout.
34+ const KEEP_ALIVE_LIFETIME_MS = 90_000 ;
2935
3036export const DEFAULT_REMOTE_LOGGER = Logger . get ( 'PowerSyncRemote' ) ;
3137
@@ -304,12 +310,26 @@ export abstract class AbstractRemote {
304310 // automatically as a header.
305311 const userAgent = this . getUserAgent ( ) ;
306312
313+ let keepAliveTimeout : any ;
314+ const resetTimeout = ( ) => {
315+ clearTimeout ( keepAliveTimeout ) ;
316+ keepAliveTimeout = setTimeout ( ( ) => {
317+ this . logger . error ( `No data received on WebSocket in ${ SOCKET_TIMEOUT_MS } ms, closing connection.` ) ;
318+ stream . close ( ) ;
319+ } , SOCKET_TIMEOUT_MS ) ;
320+ } ;
321+ resetTimeout ( ) ;
322+
307323 const url = this . options . socketUrlTransformer ( request . url ) ;
308324 const connector = new RSocketConnector ( {
309325 transport : new WebsocketClientTransport ( {
310326 url,
311327 wsCreator : ( url ) => {
312- return this . createSocket ( url ) ;
328+ const socket = this . createSocket ( url ) ;
329+ socket . addEventListener ( 'message' , ( event ) => {
330+ resetTimeout ( ) ;
331+ } ) ;
332+ return socket ;
313333 }
314334 } ) ,
315335 setup : {
@@ -332,9 +352,12 @@ export abstract class AbstractRemote {
332352 rsocket = await connector . connect ( ) ;
333353 } catch ( ex ) {
334354 this . logger . error ( `Failed to connect WebSocket` , ex ) ;
355+ clearTimeout ( keepAliveTimeout ) ;
335356 throw ex ;
336357 }
337358
359+ resetTimeout ( ) ;
360+
338361 const stream = new DataStream ( {
339362 logger : this . logger ,
340363 pressure : {
@@ -344,6 +367,7 @@ export abstract class AbstractRemote {
344367
345368 let socketIsClosed = false ;
346369 const closeSocket = ( ) => {
370+ clearTimeout ( keepAliveTimeout ) ;
347371 if ( socketIsClosed ) {
348372 return ;
349373 }
0 commit comments