1
1
'use strict'
2
+ const { setTimeout : wait } = require ( 'node:timers/promises' )
2
3
const From = require ( '@fastify/reply-from' )
3
4
const { ServerResponse } = require ( 'node:http' )
4
5
const WebSocket = require ( 'ws' )
@@ -77,10 +78,32 @@ function proxyWebSockets (source, target) {
77
78
/* c8 ignore stop */
78
79
}
79
80
80
- function reconnect ( logger , source , options , targetParams ) {
81
+ async function reconnect ( logger , source , options , targetParams ) {
82
+ // TODO retry, maxReconnectionRetries
81
83
const { url, subprotocols, optionsWs } = targetParams
82
- const target = new WebSocket ( url , subprotocols , optionsWs )
83
- logger . info ( { target : targetParams . url } , 'proxy ws reconnected on broken connection' )
84
+
85
+ let attempts = 0
86
+ let target
87
+ do {
88
+ const reconnectWait = options . wsReconnect . reconnectInterval * options . wsReconnect . reconnectDecay
89
+ logger . info ( { target : targetParams . url , attempts } , `proxy ws reconnecting in ${ reconnectWait } ms` )
90
+ await wait ( reconnectWait )
91
+ target = new WebSocket ( url , subprotocols , optionsWs )
92
+ // TODO connectionTimeout
93
+ if ( ! target ) {
94
+ attempts ++
95
+ continue
96
+ }
97
+ break
98
+ } while ( attempts < options . wsReconnect . maxReconnectAttempts )
99
+
100
+ if ( ! target ) {
101
+ logger . error ( { target : targetParams . url } , 'proxy ws failed to reconnect' )
102
+ // TODO onError hook?
103
+ return
104
+ }
105
+
106
+ logger . info ( { target : targetParams . url } , 'proxy ws reconnected' )
84
107
proxyWebSocketsWithReconnection ( logger , source , target , options , targetParams )
85
108
}
86
109
@@ -96,6 +119,8 @@ function proxyWebSocketsWithReconnection (logger, source, target, options, targe
96
119
return
97
120
}
98
121
122
+ // TODO if reconnectOnClose
123
+
99
124
logger . info ( { msg : 'proxy ws close link' } )
100
125
closeWebSocket ( source , code , reason )
101
126
closeWebSocket ( target , code , reason )
0 commit comments