From 86a96eeee455d0e0d5d4bbb95a4f0b6cab693a86 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Mon, 16 Oct 2023 07:44:27 +0200 Subject: [PATCH] fix: switch to websockets for development server (#1943) --- src/runtime/entrypoints/client.ts | 89 +++++++++++++++++++++++++++++ src/runtime/entrypoints/main_dev.ts | 1 + src/server/constants.ts | 1 - src/server/context.ts | 77 +++++++------------------ tests/dev_command_test.ts | 22 ------- 5 files changed, 111 insertions(+), 79 deletions(-) create mode 100644 src/runtime/entrypoints/client.ts diff --git a/src/runtime/entrypoints/client.ts b/src/runtime/entrypoints/client.ts new file mode 100644 index 00000000..34b7fd31 --- /dev/null +++ b/src/runtime/entrypoints/client.ts @@ -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); + } +} diff --git a/src/runtime/entrypoints/main_dev.ts b/src/runtime/entrypoints/main_dev.ts index 4e4f0c56..02188411 100644 --- a/src/runtime/entrypoints/main_dev.ts +++ b/src/runtime/entrypoints/main_dev.ts @@ -1,2 +1,3 @@ import "preact/debug"; +import "./client.ts"; export * from "./main.ts"; diff --git a/src/server/constants.ts b/src/server/constants.ts index 2567ed90..648594de 100644 --- a/src/server/constants.ts +++ b/src/server/constants.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"); diff --git a/src/server/context.ts b/src/server/context.ts index b8700d4c..25206b5b 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -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(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, @@ -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[], diff --git a/tests/dev_command_test.ts b/tests/dev_command_test.ts index 3896a4a2..81cac993 100644 --- a/tests/dev_command_test.ts +++ b/tests/dev_command_test.ts @@ -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 () => { await withFakeServe( "./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) => { await withFakeServe("./tests/fixture/main.ts", async (server) => { await t.step("useState", async () => {