diff --git a/lib/editor/tunnel.js b/lib/editor/tunnel.js index 3e48d48..1f96408 100644 --- a/lib/editor/tunnel.js +++ b/lib/editor/tunnel.js @@ -50,6 +50,7 @@ class EditorTunnel { async connect () { const thisTunnel = this + let unexpectedPacketMonitor = 0 if (this.socket) { this.close() } @@ -63,6 +64,7 @@ class EditorTunnel { } }) socket.onopen = (evt) => { + unexpectedPacketMonitor = 0 info('Editor tunnel connected') // Reset reconnectDelay this.reconnectDelay = 500 @@ -100,7 +102,9 @@ class EditorTunnel { body: data.toString('utf-8') } // console.log(`[${request.id}] R>E`, sendData.body) - this.socket?.send(JSON.stringify(sendData)) + if (this.socket?.readyState === WebSocket.OPEN) { + this.socket.send(JSON.stringify(sendData)) + } }) // Now the local comms is connected, send anything // that had got queued up whilst we were getting @@ -115,11 +119,13 @@ class EditorTunnel { // WS to local node-red has closed. Send a notification // to the platform so it can close the proxied editor // websocket to match - this.socket?.send(JSON.stringify({ - id: request.id, - ws: true, - closed: true - })) + if (this.socket?.readyState === WebSocket.OPEN) { + this.socket.send(JSON.stringify({ + id: request.id, + ws: true, + closed: true + })) + } thisTunnel.wsClients[request.id]?.removeAllListeners() thisTunnel.wsClients[request.id] = null }) @@ -152,8 +158,13 @@ class EditorTunnel { wsClient.sendOrQueue(body) } } else { - warn(`[${request.id}] Unexpected editor comms packet ${JSON.stringify(request, null, 4)}`) - this.close(1006, 'Non-connect packet received for unknown connection id') // 1006 = Abnormal closure + if (unexpectedPacketMonitor > 1) { + unexpectedPacketMonitor = 0 + warn(`[${request.id}] Unexpected editor comms packet ${JSON.stringify(request, null, 4)}`) + this.close(1006, 'Non-connect packet received for unknown connection id') // 1006 = Abnormal closure + } else { + unexpectedPacketMonitor++ + } } } else { // An http related event @@ -190,22 +201,26 @@ class EditorTunnel { got(fullUrl, options).then(response => { // debug(`proxy [${request.method}] ${fullUrl} : sending response: status ${response.statusCode}`) // send response back to the forge - this.socket?.send(JSON.stringify({ - id: request.id, - headers: response.headers, - body: response.rawBody, - status: response.statusCode - })) + if (this.socket?.readyState === WebSocket.OPEN) { + this.socket.send(JSON.stringify({ + id: request.id, + headers: response.headers, + body: response.rawBody, + status: response.statusCode + })) + } }).catch(_err => { // debug(`proxy [${request.method}] ${fullUrl} : error ${_err.toString()}`) // ↓ useful for debugging but noisy due to .map files // console.log(_err) // console.log(JSON.stringify(request)) - this.socket?.send(JSON.stringify({ - id: request.id, - body: undefined, - status: 404 - })) + if (this.socket?.readyState === WebSocket.OPEN) { + this.socket.send(JSON.stringify({ + id: request.id, + body: undefined, + status: 404 + })) + } }) } })