vibe coding the reconnect logi
This commit is contained in:
30
src/main.ts
30
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...");
|
||||
|
Reference in New Issue
Block a user