fix: switch to websockets for development server (#1943)
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
let ws: WebSocket;
|
||||
|
||||
let closed = false;
|
||||
|
||||
let reconnectTimer: number;
|
||||
const backoff = [
|
||||
0,
|
||||
100,
|
||||
150,
|
||||
200,
|
||||
250,
|
||||
300,
|
||||
350,
|
||||
400,
|
||||
450,
|
||||
500,
|
||||
500,
|
||||
605,
|
||||
750,
|
||||
1000,
|
||||
1250,
|
||||
1500,
|
||||
1750,
|
||||
2000,
|
||||
];
|
||||
let backoffIdx = 0;
|
||||
function reconnect() {
|
||||
if (!closed) return;
|
||||
|
||||
reconnectTimer = setTimeout(() => {
|
||||
if (backoffIdx === 0) {
|
||||
console.log(
|
||||
`%c Fresh %c Connection closed. Trying to reconnect...`,
|
||||
"background-color: #86efac; color: black",
|
||||
"color: inherit",
|
||||
);
|
||||
}
|
||||
backoffIdx++;
|
||||
|
||||
try {
|
||||
connect(true);
|
||||
closed = false;
|
||||
clearTimeout(reconnectTimer);
|
||||
} catch (_err) {
|
||||
reconnect();
|
||||
}
|
||||
}, backoff[Math.min(backoffIdx, backoff.length - 1)]);
|
||||
}
|
||||
|
||||
function connect(forceReload?: boolean) {
|
||||
const url = new URL("/_frsh/alive", location.origin.replace("http", "ws"));
|
||||
ws = new WebSocket(
|
||||
url,
|
||||
);
|
||||
|
||||
ws.addEventListener("open", () => {
|
||||
console.log(
|
||||
`%c Fresh %c Connected to development server.`,
|
||||
"background-color: #86efac; color: black",
|
||||
"color: inherit",
|
||||
);
|
||||
if (forceReload) {
|
||||
location.reload();
|
||||
}
|
||||
});
|
||||
|
||||
ws.addEventListener("close", () => {
|
||||
closed = true;
|
||||
reconnect();
|
||||
});
|
||||
|
||||
ws.addEventListener("message", handleMessage);
|
||||
ws.addEventListener("error", handleError);
|
||||
}
|
||||
|
||||
connect();
|
||||
|
||||
function handleMessage(e: MessageEvent) {
|
||||
const data = JSON.parse(e.data);
|
||||
console.log(data);
|
||||
}
|
||||
|
||||
function handleError(e: Event) {
|
||||
// TODO
|
||||
// deno-lint-ignore no-explicit-any
|
||||
if (e && (e as any).code === "ECONNREFUSED") {
|
||||
setTimeout(connect, 1000);
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
import "preact/debug";
|
||||
import "./client.ts";
|
||||
export * from "./main.ts";
|
||||
|
||||
Reference in New Issue
Block a user