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";
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { INTERNAL_PREFIX } from "../runtime/utils.ts";
|
||||
import { BUILD_ID } from "./build_id.ts";
|
||||
|
||||
export const REFRESH_JS_URL = `${INTERNAL_PREFIX}/refresh.js`;
|
||||
export const ALIVE_URL = `${INTERNAL_PREFIX}/alive`;
|
||||
export const JS_PREFIX = `/js`;
|
||||
export const DEBUG = !Deno.env.get("DENO_DEPLOYMENT_ID");
|
||||
|
||||
+21
-56
@@ -10,7 +10,7 @@ import {
|
||||
import { ComponentType, h } from "preact";
|
||||
import * as router from "./router.ts";
|
||||
import { FreshConfig, Manifest } from "./mod.ts";
|
||||
import { ALIVE_URL, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts";
|
||||
import { ALIVE_URL, JS_PREFIX } from "./constants.ts";
|
||||
import { BUILD_ID, setBuildId } from "./build_id.ts";
|
||||
import DefaultErrorHandler from "./default_error_page.tsx";
|
||||
import {
|
||||
@@ -489,14 +489,33 @@ export class ServerContext {
|
||||
router.getParamsAndRoute<RouterState>(handlers),
|
||||
);
|
||||
const trailingSlashEnabled = this.#routerOptions?.trailingSlash;
|
||||
const isDev = this.#dev;
|
||||
|
||||
return async function handler(
|
||||
req: Request,
|
||||
connInfo: ServeHandlerInfo = DEFAULT_CONN_INFO,
|
||||
) {
|
||||
const url = new URL(req.url);
|
||||
|
||||
// Live reload: Send updates to browser
|
||||
if (isDev && url.pathname === ALIVE_URL) {
|
||||
if (req.headers.get("upgrade") !== "websocket") {
|
||||
return new Response(null, { status: 501 });
|
||||
}
|
||||
|
||||
// TODO: When a change is made the Deno server restarts,
|
||||
// so for now the WebSocket connection is only used for
|
||||
// the client to know when the server is back up. Once we
|
||||
// have HMR we'll actively start sending messages back
|
||||
// and forth.
|
||||
const { response } = Deno.upgradeWebSocket(req);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// Redirect requests that end with a trailing slash to their non-trailing
|
||||
// slash counterpart.
|
||||
// Ex: /about/ -> /about
|
||||
const url = new URL(req.url);
|
||||
if (
|
||||
url.pathname.length > 1 && url.pathname.endsWith("/") &&
|
||||
!trailingSlashEnabled
|
||||
@@ -662,46 +681,6 @@ export class ServerContext {
|
||||
default: this.#bundleAssetRoute(),
|
||||
},
|
||||
};
|
||||
if (this.#dev) {
|
||||
internalRoutes[REFRESH_JS_URL] = {
|
||||
baseRoute: toBaseRoute(REFRESH_JS_URL),
|
||||
methods: {
|
||||
default: () => {
|
||||
return new Response(refreshJs(ALIVE_URL, BUILD_ID), {
|
||||
headers: {
|
||||
"content-type": "application/javascript; charset=utf-8",
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
internalRoutes[ALIVE_URL] = {
|
||||
baseRoute: toBaseRoute(ALIVE_URL),
|
||||
methods: {
|
||||
default: () => {
|
||||
let timerId: number | undefined = undefined;
|
||||
const body = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(`data: ${BUILD_ID}\nretry: 100\n\n`);
|
||||
timerId = setInterval(() => {
|
||||
controller.enqueue(`data: ${BUILD_ID}\n\n`);
|
||||
}, 1000);
|
||||
},
|
||||
cancel() {
|
||||
if (timerId !== undefined) {
|
||||
clearInterval(timerId);
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(body.pipeThrough(new TextEncoderStream()), {
|
||||
headers: {
|
||||
"content-type": "text/event-stream",
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Add the static file routes.
|
||||
// each files has 2 static routes:
|
||||
@@ -792,7 +771,6 @@ export class ServerContext {
|
||||
status: number,
|
||||
) => {
|
||||
const imports: string[] = [];
|
||||
if (this.#dev) imports.push(REFRESH_JS_URL);
|
||||
return (
|
||||
req: Request,
|
||||
params: Record<string, string>,
|
||||
@@ -1307,19 +1285,6 @@ export function toBaseRoute(input: string): BaseRoute {
|
||||
return (suffix + input) as BaseRoute;
|
||||
}
|
||||
|
||||
function refreshJs(aliveUrl: string, buildId: string) {
|
||||
return `let es = new EventSource("${aliveUrl}");
|
||||
window.addEventListener("beforeunload", (event) => {
|
||||
es.close();
|
||||
});
|
||||
es.addEventListener("message", function listener(e) {
|
||||
if (e.data !== "${buildId}") {
|
||||
this.removeEventListener("message", listener);
|
||||
location.reload();
|
||||
}
|
||||
});`;
|
||||
}
|
||||
|
||||
function collectEntrypoints(
|
||||
dev: boolean,
|
||||
islands: Island[],
|
||||
|
||||
Reference in New Issue
Block a user