From 3759c5aa23420f1738cb762d93937961a7a372cb Mon Sep 17 00:00:00 2001 From: matty Date: Thu, 3 Jul 2025 17:46:52 -0400 Subject: [PATCH] vibe coding the reconnect logi --- src/main.ts | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/src/main.ts b/src/main.ts index 3a93db1..ea35b70 100644 --- a/src/main.ts +++ b/src/main.ts @@ -153,6 +153,9 @@ const postReplyToStatus = async ( }; let ws = createWebsocket(); +let reconnectAttempts = 0; +const maxReconnectAttempts = 10; +const baseDelay = 5000; const reconnect = (ws: WebSocket) => { if (ws) { @@ -162,12 +165,32 @@ const reconnect = (ws: WebSocket) => { }; ws.on("close", () => { - for (let i = 0; i < 5; i++) { - if (ws.readyState !== WebSocket.OPEN) { + try { + if (reconnectAttempts < maxReconnectAttempts) { + const delay = baseDelay * Math.pow(1.5, reconnectAttempts); + console.log( + `WebSocket closed. Attempting to reconnect in ${ + delay / 1000 + } seconds...` + ); + setTimeout(() => { + console.log( + `Reconnection attempt ${ + reconnectAttempts + 1 + }/${maxReconnectAttempts}` + ); ws = reconnect(ws); - }, 5000); + reconnectAttempts++; + }, delay); + } else { + console.error( + `Failed to reconnect after ${maxReconnectAttempts} attempts. Giving up.` + ); } + } catch (error: any) { + console.error(`Reconnection error: ${error.message}`); + throw new Error(error.message); } }); @@ -178,6 +201,7 @@ ws.on("upgrade", () => { }); ws.on("open", () => { + reconnectAttempts = 0; setInterval(() => { ws.send(JSON.stringify({ type: "ping" })); console.log("Sending ping to keep session alive...");