@@ -44,17 +44,35 @@ const openWebSocket = (currentLocation: Location) => {
44
44
// https://exponentialbackoffcalculator.com
45
45
const backoffMs = ( n : number ) => Math . min ( 100 * Math . pow ( 2 , n ) , 10000 ) ;
46
46
47
+ const idleTimeoutMs = 60 * 60 * 1000 ;
48
+
47
49
export const websocketMiddleware =
48
50
( window : Window ) : Middleware =>
49
51
( store ) => {
50
52
let socket : WebSocket | null = null ;
51
53
let wasConnected = false ;
52
54
let reconnectAttempt = 0 ;
53
55
56
+ let timeout : number | null = null ;
57
+ const resetTimeout = ( ) => {
58
+ if ( timeout ) {
59
+ window . clearTimeout ( timeout ) ;
60
+ }
61
+
62
+ timeout = window . setTimeout ( ( ) => {
63
+ if ( ! socket ) {
64
+ return ;
65
+ }
66
+
67
+ socket . close ( ) ;
68
+ } , idleTimeoutMs ) ;
69
+ } ;
70
+
54
71
const connect = ( ) => {
55
72
socket = openWebSocket ( window . location ) ;
56
-
57
73
if ( socket ) {
74
+ resetTimeout ( ) ;
75
+
58
76
socket . addEventListener ( 'open' , ( ) => {
59
77
store . dispatch ( websocketConnected ( ) ) ;
60
78
@@ -85,6 +103,7 @@ export const websocketMiddleware =
85
103
const rawMessage = JSON . parse ( event . data ) ;
86
104
const message = WSMessageResponse . parse ( rawMessage ) ;
87
105
store . dispatch ( message ) ;
106
+ resetTimeout ( ) ;
88
107
} catch ( e ) {
89
108
console . log ( 'Unable to parse WebSocket message' , event . data , e ) ;
90
109
}
@@ -110,6 +129,7 @@ export const websocketMiddleware =
110
129
if ( socket && socket . readyState == socket . OPEN && sendActionOnWebsocket ( action ) ) {
111
130
const message = JSON . stringify ( action ) ;
112
131
socket . send ( message ) ;
132
+ resetTimeout ( ) ;
113
133
}
114
134
115
135
next ( action ) ;
0 commit comments