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 "preact/debug";
|
||||||
|
import "./client.ts";
|
||||||
export * from "./main.ts";
|
export * from "./main.ts";
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { INTERNAL_PREFIX } from "../runtime/utils.ts";
|
import { INTERNAL_PREFIX } from "../runtime/utils.ts";
|
||||||
import { BUILD_ID } from "./build_id.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 ALIVE_URL = `${INTERNAL_PREFIX}/alive`;
|
||||||
export const JS_PREFIX = `/js`;
|
export const JS_PREFIX = `/js`;
|
||||||
export const DEBUG = !Deno.env.get("DENO_DEPLOYMENT_ID");
|
export const DEBUG = !Deno.env.get("DENO_DEPLOYMENT_ID");
|
||||||
|
|||||||
+21
-56
@@ -10,7 +10,7 @@ import {
|
|||||||
import { ComponentType, h } from "preact";
|
import { ComponentType, h } from "preact";
|
||||||
import * as router from "./router.ts";
|
import * as router from "./router.ts";
|
||||||
import { FreshConfig, Manifest } from "./mod.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 { BUILD_ID, setBuildId } from "./build_id.ts";
|
||||||
import DefaultErrorHandler from "./default_error_page.tsx";
|
import DefaultErrorHandler from "./default_error_page.tsx";
|
||||||
import {
|
import {
|
||||||
@@ -489,14 +489,33 @@ export class ServerContext {
|
|||||||
router.getParamsAndRoute<RouterState>(handlers),
|
router.getParamsAndRoute<RouterState>(handlers),
|
||||||
);
|
);
|
||||||
const trailingSlashEnabled = this.#routerOptions?.trailingSlash;
|
const trailingSlashEnabled = this.#routerOptions?.trailingSlash;
|
||||||
|
const isDev = this.#dev;
|
||||||
|
|
||||||
return async function handler(
|
return async function handler(
|
||||||
req: Request,
|
req: Request,
|
||||||
connInfo: ServeHandlerInfo = DEFAULT_CONN_INFO,
|
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
|
// Redirect requests that end with a trailing slash to their non-trailing
|
||||||
// slash counterpart.
|
// slash counterpart.
|
||||||
// Ex: /about/ -> /about
|
// Ex: /about/ -> /about
|
||||||
const url = new URL(req.url);
|
|
||||||
if (
|
if (
|
||||||
url.pathname.length > 1 && url.pathname.endsWith("/") &&
|
url.pathname.length > 1 && url.pathname.endsWith("/") &&
|
||||||
!trailingSlashEnabled
|
!trailingSlashEnabled
|
||||||
@@ -662,46 +681,6 @@ export class ServerContext {
|
|||||||
default: this.#bundleAssetRoute(),
|
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.
|
// Add the static file routes.
|
||||||
// each files has 2 static routes:
|
// each files has 2 static routes:
|
||||||
@@ -792,7 +771,6 @@ export class ServerContext {
|
|||||||
status: number,
|
status: number,
|
||||||
) => {
|
) => {
|
||||||
const imports: string[] = [];
|
const imports: string[] = [];
|
||||||
if (this.#dev) imports.push(REFRESH_JS_URL);
|
|
||||||
return (
|
return (
|
||||||
req: Request,
|
req: Request,
|
||||||
params: Record<string, string>,
|
params: Record<string, string>,
|
||||||
@@ -1307,19 +1285,6 @@ export function toBaseRoute(input: string): BaseRoute {
|
|||||||
return (suffix + input) as 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(
|
function collectEntrypoints(
|
||||||
dev: boolean,
|
dev: boolean,
|
||||||
islands: Island[],
|
islands: Island[],
|
||||||
|
|||||||
@@ -66,20 +66,6 @@ Deno.test({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("adds refresh script to html", async () => {
|
|
||||||
await withFakeServe("./tests/fixture/dev.ts", async (server) => {
|
|
||||||
const doc = await server.getHtml("/");
|
|
||||||
assertSelector(doc, `script[src="/_frsh/refresh.js"]`);
|
|
||||||
|
|
||||||
const res = await server.get(`/_frsh/refresh.js`);
|
|
||||||
assertEquals(
|
|
||||||
res.headers.get("content-type"),
|
|
||||||
"application/javascript; charset=utf-8",
|
|
||||||
);
|
|
||||||
await res.body?.cancel();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test("preact/debug is active in dev mode", async () => {
|
Deno.test("preact/debug is active in dev mode", async () => {
|
||||||
await withFakeServe(
|
await withFakeServe(
|
||||||
"./tests/fixture_render_error/dev.ts",
|
"./tests/fixture_render_error/dev.ts",
|
||||||
@@ -99,14 +85,6 @@ Deno.test("preact/debug is active in dev mode", async () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("middleware destination internal", async () => {
|
|
||||||
await withFakeServe("./tests/fixture/dev.ts", async (server) => {
|
|
||||||
const resp = await server.get(`/_frsh/refresh.js`);
|
|
||||||
assertEquals(resp.headers.get("destination"), "internal");
|
|
||||||
await resp.body?.cancel();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
Deno.test("warns when using hooks in server components", async (t) => {
|
Deno.test("warns when using hooks in server components", async (t) => {
|
||||||
await withFakeServe("./tests/fixture/main.ts", async (server) => {
|
await withFakeServe("./tests/fixture/main.ts", async (server) => {
|
||||||
await t.step("useState", async () => {
|
await t.step("useState", async () => {
|
||||||
|
|||||||
Reference in New Issue
Block a user