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 ws = createWebsocket();
|
||||||
|
let reconnectAttempts = 0;
|
||||||
|
const maxReconnectAttempts = 10;
|
||||||
|
const baseDelay = 5000;
|
||||||
|
|
||||||
const reconnect = (ws: WebSocket) => {
|
const reconnect = (ws: WebSocket) => {
|
||||||
if (ws) {
|
if (ws) {
|
||||||
@ -162,12 +165,32 @@ const reconnect = (ws: WebSocket) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
ws.on("close", () => {
|
ws.on("close", () => {
|
||||||
for (let i = 0; i < 5; i++) {
|
try {
|
||||||
if (ws.readyState !== WebSocket.OPEN) {
|
if (reconnectAttempts < maxReconnectAttempts) {
|
||||||
|
const delay = baseDelay * Math.pow(1.5, reconnectAttempts);
|
||||||
|
console.log(
|
||||||
|
`WebSocket closed. Attempting to reconnect in ${
|
||||||
|
delay / 1000
|
||||||
|
} seconds...`
|
||||||
|
);
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
console.log(
|
||||||
|
`Reconnection attempt ${
|
||||||
|
reconnectAttempts + 1
|
||||||
|
}/${maxReconnectAttempts}`
|
||||||
|
);
|
||||||
ws = reconnect(ws);
|
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", () => {
|
ws.on("open", () => {
|
||||||
|
reconnectAttempts = 0;
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
ws.send(JSON.stringify({ type: "ping" }));
|
ws.send(JSON.stringify({ type: "ping" }));
|
||||||
console.log("Sending ping to keep session alive...");
|
console.log("Sending ping to keep session alive...");
|
||||||
|
Reference in New Issue
Block a user