From 36d56a98780d7675082c72abe9440bd3f22b13c8 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Mon, 12 Jun 2023 13:18:52 +0200 Subject: [PATCH] feat(server): pick free port if none specified (#1274) --- src/server/deps.ts | 5 +++- src/server/mod.ts | 52 +++++++++++++++++++++++++++++++++----- tests/cli_test.ts | 12 ++++----- tests/islands_test.ts | 41 ++++++++++++++++-------------- tests/islands_wasm_test.ts | 4 +-- tests/main_test.ts | 25 +++++++++--------- tests/plugin_test.ts | 4 +-- tests/test_utils.ts | 11 ++++---- tests/twind_test.ts | 10 ++++---- www/main_test.ts | 4 +-- 10 files changed, 107 insertions(+), 61 deletions(-) diff --git a/src/server/deps.ts b/src/server/deps.ts index f26516d2..9a2bbd3e 100644 --- a/src/server/deps.ts +++ b/src/server/deps.ts @@ -7,7 +7,10 @@ export { toFileUrl, } from "https://deno.land/std@0.190.0/path/mod.ts"; export { walk } from "https://deno.land/std@0.190.0/fs/walk.ts"; -export { serve } from "https://deno.land/std@0.190.0/http/server.ts"; +export { + type Handler as ServeHandler, + serve, +} from "https://deno.land/std@0.190.0/http/server.ts"; export type { ConnInfo, Handler as RequestHandler, diff --git a/src/server/mod.ts b/src/server/mod.ts index 65f437df..f5730e8e 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -1,6 +1,6 @@ import { ServerContext } from "./context.ts"; import * as colors from "https://deno.land/std@0.190.0/fmt/colors.ts"; -import { serve } from "./deps.ts"; +import { serve, ServeHandler } from "./deps.ts"; export { Status } from "./deps.ts"; import { AppModule, @@ -71,7 +71,6 @@ export async function createHandler( export async function start(routes: Manifest, opts: StartOptions = {}) { const ctx = await ServerContext.fromManifest(routes, opts); - opts.port ??= parseInt(Deno.env.get("PORT") || "8000"); if (!opts.onListen) { opts.onListen = (params) => { @@ -86,10 +85,51 @@ export async function start(routes: Manifest, opts: StartOptions = {}) { }; } - if (opts.experimentalDenoServe === true) { - // @ts-ignore as `Deno.serve` is still unstable. - await Deno.serve({ ...opts, handler: ctx.handler() }); + const portEnv = Deno.env.get("PORT"); + if (portEnv !== undefined) { + opts.port ??= parseInt(portEnv, 10); + } + + const handler = ctx.handler(); + + if (opts.port) { + await bootServer(handler, opts); } else { - await serve(ctx.handler(), opts); + // No port specified, check for a free port. Instead of picking just + // any port we'll check if the next one is free for UX reasons. + // That way the user only needs to increment a number when running + // multiple apps vs having to remember completely different ports. + let firstError; + for (let port = 8000; port < 8020; port++) { + try { + await bootServer(handler, { ...opts, port }); + firstError = undefined; + break; + } catch (err) { + if (err instanceof Deno.errors.AddrInUse) { + // Throw first EADDRINUSE error + // if no port is free + if (!firstError) { + firstError = err; + } + continue; + } + + throw err; + } + } + + if (firstError) { + throw firstError; + } + } +} + +async function bootServer(handler: ServeHandler, opts: StartOptions) { + if (opts.experimentalDenoServe === true) { + // @ts-ignore as `Deno.serve` is still unstable. + await Deno.serve({ ...opts, handler }); + } else { + await serve(handler, opts); } } diff --git a/tests/cli_test.ts b/tests/cli_test.ts index 815b7ee5..9c9b67ad 100644 --- a/tests/cli_test.ts +++ b/tests/cli_test.ts @@ -112,7 +112,7 @@ Deno.test({ }); await t.step("start up the server and access the root page", async () => { - const { serverProcess, lines } = await startFreshServer({ + const { serverProcess, lines, address } = await startFreshServer({ args: ["run", "-A", "--check", "main.ts"], cwd: tmpDirName, }); @@ -120,7 +120,7 @@ Deno.test({ await delay(100); // Access the root page - const res = await fetch("http://localhost:8000"); + const res = await fetch(address); await res.body?.cancel(); assertEquals(res.status, Status.OK); @@ -129,7 +129,7 @@ Deno.test({ args: ["--no-sandbox"], }); const page = await browser.newPage(); - await page.goto("http://localhost:8000", { waitUntil: "networkidle2" }); + await page.goto(address, { waitUntil: "networkidle2" }); const counter = await page.$("body > div > div > p"); let counterValue = await counter?.evaluate((el) => el.textContent); assert(counterValue === "3"); @@ -241,7 +241,7 @@ Deno.test({ }); await t.step("start up the server and access the root page", async () => { - const { serverProcess, lines } = await startFreshServer({ + const { serverProcess, lines, address } = await startFreshServer({ args: ["run", "-A", "--check", "main.ts"], cwd: tmpDirName, }); @@ -249,14 +249,14 @@ Deno.test({ await delay(100); // Access the root page - const res = await fetch("http://localhost:8000"); + const res = await fetch(address); await res.body?.cancel(); assertEquals(res.status, Status.OK); // verify the island is revived. const browser = await puppeteer.launch({ args: ["--no-sandbox"] }); const page = await browser.newPage(); - await page.goto("http://localhost:8000", { waitUntil: "networkidle2" }); + await page.goto(address, { waitUntil: "networkidle2" }); const counter = await page.$("body > div > div > p"); let counterValue = await counter?.evaluate((el) => el.textContent); diff --git a/tests/islands_test.ts b/tests/islands_test.ts index 5aa85d51..45f52ade 100644 --- a/tests/islands_test.ts +++ b/tests/islands_test.ts @@ -11,7 +11,7 @@ import { startFreshServer } from "./test_utils.ts"; Deno.test({ name: "island tests", async fn(t) { - await withPage(async (page) => { + await withPage(async (page, address) => { async function counterTest(counterId: string, originalValue: number) { const pElem = await page.waitForSelector(`#${counterId} > p`); @@ -27,7 +27,7 @@ Deno.test({ assert(value === `${originalValue + 1}`, `${counterId} click`); } - await page.goto("http://localhost:8000/islands", { + await page.goto(`${address}/islands`, { waitUntil: "networkidle2", }); @@ -45,7 +45,7 @@ Deno.test({ assertStringIncludes(srcString, "image.png?__frsh_c="); // Ensure src path is the same as server rendered - const resp = await fetch(new Request("http://localhost:8000/islands")); + const resp = await fetch(new Request(`${address}/islands`)); const body = await resp.text(); const imgFilePath = body.match(/img id="img-in-island" src="(.*?)"/) @@ -59,12 +59,15 @@ Deno.test({ sanitizeResources: false, }); -function withPage(fn: (page: Page) => Promise) { +function withPage(fn: (page: Page, address: string) => Promise) { return withPageName("./tests/fixture/main.ts", fn); } -async function withPageName(name: string, fn: (page: Page) => Promise) { - const { lines, serverProcess } = await startFreshServer({ +async function withPageName( + name: string, + fn: (page: Page, address: string) => Promise, +) { + const { lines, serverProcess, address } = await startFreshServer({ args: ["run", "-A", name], }); @@ -74,7 +77,7 @@ async function withPageName(name: string, fn: (page: Page) => Promise) { try { const page = await browser.newPage(); - await fn(page); + await fn(page, address); } finally { await browser.close(); } @@ -92,12 +95,12 @@ Deno.test({ name: "island tests with ", async fn(t) { - await withPage(async (page) => { + await withPage(async (page, address) => { page.on("dialog", () => { assert(false, "There is XSS"); }); - await page.goto("http://localhost:8000/evil", { + await page.goto(`${address}/evil`, { waitUntil: "networkidle2", }); @@ -122,8 +125,8 @@ Deno.test({ name: "island with fragment as root", async fn(_t) { - await withPage(async (page) => { - await page.goto("http://localhost:8000/islands/root_fragment", { + await withPage(async (page, address) => { + await page.goto(`${address}/islands/root_fragment`, { waitUntil: "networkidle2", }); @@ -157,9 +160,9 @@ Deno.test({ name: "island with fragment as root and conditional child first", async fn(_t) { - await withPage(async (page) => { + await withPage(async (page, address) => { await page.goto( - "http://localhost:8000/islands/root_fragment_conditional_first", + `${address}/islands/root_fragment_conditional_first`, { waitUntil: "networkidle2", }, @@ -191,8 +194,8 @@ Deno.test({ name: "island that returns `null`", async fn(_t) { - await withPage(async (page) => { - await page.goto("http://localhost:8000/islands/returning_null", { + await withPage(async (page, address) => { + await page.goto(`${address}/islands/returning_null`, { waitUntil: "networkidle2", }); @@ -208,9 +211,9 @@ Deno.test({ name: "island using `npm:` specifiers", async fn(_t) { - await withPageName("./tests/fixture_npm/main.ts", async (page) => { + await withPageName("./tests/fixture_npm/main.ts", async (page, address) => { await page.setJavaScriptEnabled(false); - await page.goto("http://localhost:8000/", { waitUntil: "networkidle2" }); + await page.goto(address, { waitUntil: "networkidle2" }); assert(await page.waitForSelector("#server-true")); await page.setJavaScriptEnabled(true); @@ -229,8 +232,8 @@ Deno.test({ async fn(_t) { await withPageName( "./tests/fixture_preact_rts_v5/main.ts", - async (page) => { - await page.goto("http://localhost:8000/", { + async (page, address) => { + await page.goto(address, { waitUntil: "networkidle2", }); await page.waitForSelector("#foo"); diff --git a/tests/islands_wasm_test.ts b/tests/islands_wasm_test.ts index 0b4adc81..0204e886 100644 --- a/tests/islands_wasm_test.ts +++ b/tests/islands_wasm_test.ts @@ -6,7 +6,7 @@ Deno.test({ ignore: Deno.build.os === "windows", async fn(t) { // Preparation - const { lines, serverProcess } = await startFreshServer({ + const { lines, serverProcess, address } = await startFreshServer({ args: ["run", "-A", "./tests/fixture/main_wasm.ts"], }); @@ -27,7 +27,7 @@ Deno.test({ assert(value === `${originalValue + 1}`, `${counterId} click`); } - await page.goto("http://localhost:8000/islands", { + await page.goto(`${address}/islands`, { waitUntil: "networkidle2", }); diff --git a/tests/main_test.ts b/tests/main_test.ts index a1d3c786..dc0ee2f1 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -606,7 +606,7 @@ Deno.test("experimental Deno.serve", { ignore: Deno.build.os === "windows", // TODO: Deno.serve hang on Windows? }, async (t) => { // Preparation - const { serverProcess, lines } = await startFreshServer({ + const { serverProcess, lines, address } = await startFreshServer({ args: [ "run", "-A", @@ -619,7 +619,7 @@ Deno.test("experimental Deno.serve", { await delay(100); await t.step("ssr", async () => { - const resp = await fetch("http://localhost:8000"); + const resp = await fetch(address); assert(resp); assertEquals(resp.status, Status.OK); assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8"); @@ -637,7 +637,7 @@ Deno.test("experimental Deno.serve", { }); await t.step("static file", async () => { - const resp = await fetch("http://localhost:8000/foo.txt"); + const resp = await fetch(`${address}/foo.txt`); assertEquals(resp.status, Status.OK); const body = await resp.text(); assert(body.startsWith("bar")); @@ -658,14 +658,14 @@ Deno.test("jsx pragma works", { sanitizeResources: false, }, async (t) => { // Preparation - const { serverProcess, lines } = await startFreshServer({ + const { serverProcess, lines, address } = await startFreshServer({ args: ["run", "-A", "./tests/fixture_jsx_pragma/main.ts"], }); await delay(100); await t.step("ssr", async () => { - const resp = await fetch("http://localhost:8000"); + const resp = await fetch(address); assertEquals(resp.status, Status.OK); const text = await resp.text(); assertStringIncludes(text, "Hello World"); @@ -675,7 +675,7 @@ Deno.test("jsx pragma works", { const browser = await puppeteer.launch({ args: ["--no-sandbox"] }); const page = await browser.newPage(); - await page.goto("http://localhost:8000", { + await page.goto(address, { waitUntil: "networkidle2", }); @@ -694,15 +694,14 @@ Deno.test("preact/debug is active in dev mode", { sanitizeResources: false, }, async (t) => { // Preparation - const { serverProcess, lines } = await startFreshServer({ + const { serverProcess, lines, address } = await startFreshServer({ args: ["run", "-A", "./tests/fixture_render_error/main.ts"], }); await delay(100); - const url = "http://localhost:8000"; await t.step("SSR error is shown", async () => { - const resp = await fetch(url); + const resp = await fetch(address); assertEquals(resp.status, Status.InternalServerError); const text = await resp.text(); assertStringIncludes(text, "Objects are not valid as a child"); @@ -711,7 +710,7 @@ Deno.test("preact/debug is active in dev mode", { const browser = await puppeteer.launch({ args: ["--no-sandbox"] }); const page = await browser.newPage(); - await page.goto(url, { + await page.goto(address, { waitUntil: "networkidle2", }); @@ -732,7 +731,7 @@ Deno.test("preloading javascript files", { sanitizeResources: false, }, async () => { // Preparation - const { serverProcess, lines } = await startFreshServer({ + const { serverProcess, lines, address } = await startFreshServer({ args: ["run", "-A", "./tests/fixture/main.ts"], }); @@ -741,13 +740,13 @@ Deno.test("preloading javascript files", { try { // request js file to start esbuild execution - await page.goto("http://localhost:8000", { + await page.goto(address, { waitUntil: "networkidle2", }); await delay(5000); // wait running esbuild - await page.goto("http://localhost:8000", { + await page.goto(address, { waitUntil: "networkidle2", }); diff --git a/tests/plugin_test.ts b/tests/plugin_test.ts index 1ec9bbac..320ff307 100644 --- a/tests/plugin_test.ts +++ b/tests/plugin_test.ts @@ -62,7 +62,7 @@ Deno.test({ name: "/with-island hydration", async fn(t) { // Preparation - const { lines, serverProcess } = await startFreshServer({ + const { lines, serverProcess, address } = await startFreshServer({ args: ["run", "-A", "./tests/fixture_plugin/main.ts"], }); @@ -71,7 +71,7 @@ Deno.test({ const browser = await puppeteer.launch({ args: ["--no-sandbox"] }); const page = await browser.newPage(); - await page.goto("http://localhost:8000/with-island", { + await page.goto(`${address}/with-island`, { waitUntil: "networkidle2", }); diff --git a/tests/test_utils.ts b/tests/test_utils.ts index ac0bc8f8..53ebac13 100644 --- a/tests/test_utils.ts +++ b/tests/test_utils.ts @@ -15,16 +15,17 @@ export async function startFreshServer(options: Deno.CommandOptions) { preventCancel: true, }); - let started = false; + let address = ""; for await (const line of lines) { - if (line.includes("Fresh ready")) { - started = true; + const match = line.match(/https?:\/\/localhost:\d+/g); + if (match) { + address = match[0]; break; } } - if (!started) { + if (!address) { throw new Error("Server didn't start up"); } - return { serverProcess, lines }; + return { serverProcess, lines, address }; } diff --git a/tests/twind_test.ts b/tests/twind_test.ts index 66077d9f..2507c3d7 100644 --- a/tests/twind_test.ts +++ b/tests/twind_test.ts @@ -9,7 +9,7 @@ import { startFreshServer } from "./test_utils.ts"; * Returns a page instance and a method to terminate the server. */ async function setUpServer(path: string) { - const { lines, serverProcess } = await startFreshServer({ + const { lines, serverProcess, address } = await startFreshServer({ args: ["run", "-A", path], }); @@ -40,7 +40,7 @@ async function setUpServer(path: string) { } }; - return { page: page, terminate: terminate }; + return { page: page, terminate: terminate, address }; } /** @@ -96,7 +96,7 @@ Deno.test({ } } - await page.goto("http://localhost:8000/static", { + await page.goto(`${server.address}/static`, { waitUntil: "networkidle2", }); @@ -167,7 +167,7 @@ Deno.test({ assert(false, `${numDuplicates} cssrules are duplicated`); } - await page.goto("http://localhost:8000/check-duplication", { + await page.goto(`${server.address}/check-duplication`, { waitUntil: "networkidle2", }); @@ -275,7 +275,7 @@ Deno.test({ ); } - await page.goto("http://localhost:8000/insert-cssrules", { + await page.goto(`${server.address}/insert-cssrules`, { waitUntil: "networkidle2", }); diff --git a/www/main_test.ts b/www/main_test.ts index 49b0eec2..383d7c97 100644 --- a/www/main_test.ts +++ b/www/main_test.ts @@ -5,11 +5,11 @@ import { startFreshServer } from "../tests/test_utils.ts"; Deno.test("CORS should not set on GET /fresh-badge.svg", { sanitizeResources: false, }, async () => { - const { serverProcess, lines } = await startFreshServer({ + const { serverProcess, lines, address } = await startFreshServer({ args: ["run", "-A", "./main.ts"], }); - const res = await fetch("http://localhost:8000/fresh-badge.svg"); + const res = await fetch(`${address}/fresh-badge.svg`); await res.body?.cancel(); assertEquals(res.headers.get("cross-origin-resource-policy"), null);