feat: move to Deno.serve (#1427)

Co-authored-by: Marvin Hagemeister <marvin@deno.com>
This commit is contained in:
Lino Le Van
2023-07-12 14:37:53 +02:00
committed by GitHub
co-authored by Marvin Hagemeister
parent 46ae49d654
commit e2a1bf8643
24 changed files with 67 additions and 151 deletions
+1 -1
View File
@@ -25,7 +25,7 @@ The [documentation](https://fresh.deno.dev/docs/) is available on
## 🚀 Getting started ## 🚀 Getting started
Install [Deno CLI](https://deno.land/) version 1.31.0 or higher. Install [Deno CLI](https://deno.land/) version 1.35.0 or higher.
You can scaffold a new project by running the Fresh init script. To scaffold a You can scaffold a new project by running the Fresh init script. To scaffold a
project run the following: project run the following:
+6 -2
View File
@@ -120,11 +120,15 @@ the value of `acme` in your middleware.
To set the stage for this section, `MiddlewareHandlerContext` looks like this: To set the stage for this section, `MiddlewareHandlerContext` looks like this:
```ts ```ts
export interface MiddlewareHandlerContext<State = Record<string, unknown>> export interface MiddlewareHandlerContext<State = Record<string, unknown>> {
extends ConnInfo {
next: () => Promise<Response>; next: () => Promise<Response>;
state: State; state: State;
destination: router.DestinationKind; destination: router.DestinationKind;
remoteAddr: {
transport: "tcp" | "udp";
hostname: string;
port: number;
};
} }
``` ```
+1 -1
View File
@@ -36,7 +36,7 @@ caching **will** cause your project to not function correctly.
Here is an example `Dockerfile` for a Fresh project: Here is an example `Dockerfile` for a Fresh project:
```dockerfile ```dockerfile
FROM denoland/deno:1.33.2 FROM denoland/deno:1.35.0
ARG GIT_REVISION ARG GIT_REVISION
ENV DENO_DEPLOYMENT_ID=${GIT_REVISION} ENV DENO_DEPLOYMENT_ID=${GIT_REVISION}
+6 -2
View File
@@ -100,11 +100,15 @@ export const handler = [
To set the stage for this section, `MiddlewareHandlerContext` looks like this: To set the stage for this section, `MiddlewareHandlerContext` looks like this:
```ts ```ts
export interface MiddlewareHandlerContext<State = Record<string, unknown>> export interface MiddlewareHandlerContext<State = Record<string, unknown>> {
extends ConnInfo {
next: () => Promise<Response>; next: () => Promise<Response>;
state: State; state: State;
destination: router.DestinationKind; destination: router.DestinationKind;
remoteAddr: {
transport: "tcp" | "udp";
hostname: string;
port: number;
};
} }
``` ```
+2 -11
View File
@@ -17,19 +17,10 @@ export async function start(routes: Manifest, opts: StartOptions = {});
things get interesting. `StartOptions` looks like this: things get interesting. `StartOptions` looks like this:
``` ```
export type StartOptions = ServeInit & FreshOptions & { export type StartOptions = ServeInit & FreshOptions;
/**
* UNSTABLE: use the `Deno.serve` API as the underlying HTTP server instead of
* the `std/http` API. Do not use this in production.
*
* This option is experimental and may be removed in a future Fresh release.
*/
experimentalDenoServe?: boolean;
};
``` ```
You can play around with `Deno.serve` if you'd like, but heed the warning. The The good stuff is really in...
good stuff is really in...
```ts ```ts
export interface FreshOptions { export interface FreshOptions {
+1
View File
@@ -23,6 +23,7 @@ below.
| 1.0.0-1.0.2 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.23.0 | | 1.0.0-1.0.2 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.23.0 |
| 1.1.0-1.1.5 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.25.0 | | 1.1.0-1.1.5 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.25.0 |
| 1.2.0 | >=10.15.0 <11.0.0 | >=6.1.0 | >= 1.25.0 | | 1.2.0 | >=10.15.0 <11.0.0 | >=6.1.0 | >= 1.25.0 |
| 1.3.0 | >=10.15.0 <11.0.0 | >=6.1.0 | >= 1.35.0 |
## Updating dependencies ## Updating dependencies
+2 -4
View File
@@ -53,13 +53,11 @@ export default function FooPage() {
```ts ```ts
// tests/main_test.ts // tests/main_test.ts
import { createHandler } from "$fresh/server.ts"; import { createHandler, ServeHandlerInfo } from "$fresh/server.ts";
import manifest from "../fresh.gen.ts"; import manifest from "../fresh.gen.ts";
import { assert, assertEquals } from "$std/testing/asserts.ts"; import { assert, assertEquals } from "$std/testing/asserts.ts";
import type { ConnInfo } from "$std/http/server.ts";
const CONN_INFO: ConnInfo = { const CONN_INFO: ServeHandlerInfo = {
localAddr: { hostname: "127.0.0.1", port: 8000, transport: "tcp" },
remoteAddr: { hostname: "127.0.0.1", port: 53496, transport: "tcp" }, remoteAddr: { hostname: "127.0.0.1", port: 53496, transport: "tcp" },
}; };
+1 -1
View File
@@ -10,7 +10,7 @@ framework. You'll learn how to create a new project, run it locally, edit and
create pages, fetch data, handle user interactions, and how to then deploy the create pages, fetch data, handle user interactions, and how to then deploy the
project to [Deno Deploy][deno-deploy]. project to [Deno Deploy][deno-deploy].
The documentation assumes you have Deno 1.31.0 or later installed. The documentation assumes you have Deno 1.35.0 or later installed.
To install Deno, follow the To install Deno, follow the
[installation instructions in the Deno manual][manual-installation]. [installation instructions in the Deno manual][manual-installation].
+5 -5
View File
@@ -1,5 +1,4 @@
import { import {
ConnInfo,
dirname, dirname,
extname, extname,
fromFileUrl, fromFileUrl,
@@ -33,6 +32,7 @@ import {
Route, Route,
RouteModule, RouteModule,
RouterOptions, RouterOptions,
ServeHandlerInfo,
UnknownPage, UnknownPage,
UnknownPageModule, UnknownPageModule,
} from "./types.ts"; } from "./types.ts";
@@ -47,7 +47,7 @@ import {
} from "../build/mod.ts"; } from "../build/mod.ts";
import { InternalRoute } from "./router.ts"; import { InternalRoute } from "./router.ts";
const DEFAULT_CONN_INFO: ConnInfo = { const DEFAULT_CONN_INFO: ServeHandlerInfo = {
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 }, localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 }, remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
}; };
@@ -374,7 +374,7 @@ export class ServerContext {
* This functions returns a request handler that handles all routes required * This functions returns a request handler that handles all routes required
* by fresh, including static files. * by fresh, including static files.
*/ */
handler(): (req: Request, connInfo?: ConnInfo) => Promise<Response> { handler(): (req: Request, connInfo?: ServeHandlerInfo) => Promise<Response> {
const handlers = this.#handlers(); const handlers = this.#handlers();
const inner = router.router<RouterState>(handlers); const inner = router.router<RouterState>(handlers);
const withMiddlewares = this.#composeMiddlewares( const withMiddlewares = this.#composeMiddlewares(
@@ -385,7 +385,7 @@ export class ServerContext {
const trailingSlashEnabled = this.#routerOptions?.trailingSlash; const trailingSlashEnabled = this.#routerOptions?.trailingSlash;
return async function handler( return async function handler(
req: Request, req: Request,
connInfo: ConnInfo = DEFAULT_CONN_INFO, connInfo: ServeHandlerInfo = DEFAULT_CONN_INFO,
) { ) {
// 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.
@@ -457,7 +457,7 @@ export class ServerContext {
) { ) {
return ( return (
req: Request, req: Request,
connInfo: ConnInfo, connInfo: ServeHandlerInfo,
inner: router.FinalHandler<RouterState>, inner: router.FinalHandler<RouterState>,
) => { ) => {
// identify middlewares to apply, if any. // identify middlewares to apply, if any.
+1 -4
View File
@@ -11,10 +11,7 @@ export {
type Handler as ServeHandler, type Handler as ServeHandler,
serve, serve,
} from "https://deno.land/std@0.193.0/http/server.ts"; } from "https://deno.land/std@0.193.0/http/server.ts";
export type { export type { ServeInit } from "https://deno.land/std@0.193.0/http/server.ts";
ConnInfo,
ServeInit,
} from "https://deno.land/std@0.193.0/http/server.ts";
export { Status } from "https://deno.land/std@0.193.0/http/http_status.ts"; export { Status } from "https://deno.land/std@0.193.0/http/http_status.ts";
export { export {
typeByExtension, typeByExtension,
+12 -5
View File
@@ -1,13 +1,15 @@
import { ServerContext } from "./context.ts"; import { ServerContext } from "./context.ts";
import * as colors from "https://deno.land/std@0.193.0/fmt/colors.ts"; import * as colors from "https://deno.land/std@0.193.0/fmt/colors.ts";
import { ConnInfo, serve, ServeHandler } from "./deps.ts";
export { Status } from "./deps.ts"; export { Status } from "./deps.ts";
import { serve } from "./deps.ts";
import { import {
AppModule, AppModule,
ErrorPageModule, ErrorPageModule,
IslandModule, IslandModule,
MiddlewareModule, MiddlewareModule,
RouteModule, RouteModule,
ServeHandler,
ServeHandlerInfo,
StartOptions, StartOptions,
UnknownPageModule, UnknownPageModule,
} from "./types.ts"; } from "./types.ts";
@@ -35,6 +37,7 @@ export type {
PluginRenderStyleTag, PluginRenderStyleTag,
RenderFunction, RenderFunction,
RouteConfig, RouteConfig,
ServeHandlerInfo,
StartOptions, StartOptions,
UnknownHandler, UnknownHandler,
UnknownHandlerContext, UnknownHandlerContext,
@@ -70,7 +73,9 @@ export { ServerContext };
export async function createHandler( export async function createHandler(
routes: Manifest, routes: Manifest,
opts: StartOptions = {}, opts: StartOptions = {},
): Promise<(req: Request, connInfo?: ConnInfo) => Promise<Response>> { ): Promise<
(req: Request, connInfo?: ServeHandlerInfo) => Promise<Response>
> {
const ctx = await ServerContext.fromManifest(routes, opts); const ctx = await ServerContext.fromManifest(routes, opts);
return ctx.handler(); return ctx.handler();
} }
@@ -132,10 +137,12 @@ export async function start(routes: Manifest, opts: StartOptions = {}) {
} }
async function bootServer(handler: ServeHandler, opts: StartOptions) { async function bootServer(handler: ServeHandler, opts: StartOptions) {
if (opts.experimentalDenoServe === true) { // @ts-ignore Ignore type error when type checking with Deno versions
// @ts-ignore as `Deno.serve` is still unstable. if (typeof Deno.serve === "function") {
await Deno.serve({ ...opts, handler }).finished; // @ts-ignore Ignore type error when type checking with Deno versions
await Deno.serve(opts, handler).finished;
} else { } else {
// @ts-ignore Deprecated std serve way
await serve(handler, opts); await serve(handler, opts);
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
import type { ConnInfo } from "./deps.ts"; import { ServeHandlerInfo } from "./types.ts";
type HandlerContext<T = unknown> = T & ConnInfo; type HandlerContext<T = unknown> = T & ServeHandlerInfo;
export type Handler<T = unknown> = ( export type Handler<T = unknown> = (
req: Request, req: Request,
+20 -14
View File
@@ -1,19 +1,11 @@
import { ComponentType } from "preact"; import { ComponentType } from "preact";
import { ConnInfo, ServeInit } from "./deps.ts"; import { ServeInit } from "./deps.ts";
import * as router from "./router.ts"; import * as router from "./router.ts";
import { InnerRenderFunction, RenderContext } from "./render.ts"; import { InnerRenderFunction, RenderContext } from "./render.ts";
// --- APPLICATION CONFIGURATION --- // --- APPLICATION CONFIGURATION ---
export type StartOptions = ServeInit & FreshOptions & { export type StartOptions = ServeInit & FreshOptions;
/**
* UNSTABLE: use the `Deno.serve` API as the underlying HTTP server instead of
* the `std/http` API. Do not use this in production.
*
* This option is experimental and may be removed in a future Fresh release.
*/
experimentalDenoServe?: boolean;
};
export interface FreshOptions { export interface FreshOptions {
render?: RenderFunction; render?: RenderFunction;
@@ -85,8 +77,22 @@ export interface RouteConfig {
// deno-lint-ignore no-empty-interface // deno-lint-ignore no-empty-interface
export interface RenderOptions extends ResponseInit {} export interface RenderOptions extends ResponseInit {}
export type ServeHandlerInfo = {
/**
* Backwards compatible with std/server
* @deprecated
*/
localAddr?: Deno.NetAddr;
remoteAddr: Deno.NetAddr;
};
export type ServeHandler = (
request: Request,
info: ServeHandlerInfo,
) => Response | Promise<Response>;
export interface HandlerContext<Data = unknown, State = Record<string, unknown>> export interface HandlerContext<Data = unknown, State = Record<string, unknown>>
extends ConnInfo { extends ServeHandlerInfo {
params: Record<string, string>; params: Record<string, string>;
render: ( render: (
data?: Data, data?: Data,
@@ -158,7 +164,7 @@ export interface UnknownPageProps<T = any> {
} }
export interface UnknownHandlerContext<State = Record<string, unknown>> export interface UnknownHandlerContext<State = Record<string, unknown>>
extends ConnInfo { extends ServeHandlerInfo {
render: () => Response | Promise<Response>; render: () => Response | Promise<Response>;
state: State; state: State;
} }
@@ -198,7 +204,7 @@ export interface ErrorPageProps {
} }
export interface ErrorHandlerContext<State = Record<string, unknown>> export interface ErrorHandlerContext<State = Record<string, unknown>>
extends ConnInfo { extends ServeHandlerInfo {
error: unknown; error: unknown;
render: () => Response | Promise<Response>; render: () => Response | Promise<Response>;
state: State; state: State;
@@ -227,7 +233,7 @@ export interface ErrorPage {
// --- MIDDLEWARES --- // --- MIDDLEWARES ---
export interface MiddlewareHandlerContext<State = Record<string, unknown>> export interface MiddlewareHandlerContext<State = Record<string, unknown>>
extends ConnInfo { extends ServeHandlerInfo {
next: () => Promise<Response>; next: () => Promise<Response>;
state: State; state: State;
destination: router.DestinationKind; destination: router.DestinationKind;
-5
View File
@@ -7,11 +7,6 @@ const ctx = await ServerContext.fromManifest(manifest, {});
const handler = ctx.handler(); const handler = ctx.handler();
const router = (req: Request) => { const router = (req: Request) => {
return handler(req, { return handler(req, {
localAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
remoteAddr: { remoteAddr: {
transport: "tcp", transport: "tcp",
hostname: "127.0.0.1", hostname: "127.0.0.1",
+1 -3
View File
@@ -8,6 +8,4 @@ import { start } from "$fresh/server.ts";
import routes from "./fresh.gen.ts"; import routes from "./fresh.gen.ts";
import options from "./options.ts"; import options from "./options.ts";
const experimentalDenoServe = Deno.args.includes("--experimental-deno-serve"); await start(routes, options);
await start(routes, { ...options, experimentalDenoServe });
+1 -3
View File
@@ -11,6 +11,4 @@ import { start } from "$fresh/server.ts";
import routes from "./fresh.gen.ts"; import routes from "./fresh.gen.ts";
import options from "./options.ts"; import options from "./options.ts";
const experimentalDenoServe = Deno.args.includes("--experimental-deno-serve"); await start(routes, options);
await start(routes, { ...options, experimentalDenoServe });
+1 -3
View File
@@ -7,6 +7,4 @@
import { start } from "$fresh/server.ts"; import { start } from "$fresh/server.ts";
import routes from "./fresh.gen.ts"; import routes from "./fresh.gen.ts";
const experimentalDenoServe = Deno.args.includes("--experimental-deno-serve"); await start(routes);
await start(routes, { experimentalDenoServe });
+1 -3
View File
@@ -10,6 +10,4 @@ import "./polyfill_deno_deploy.ts";
import { start } from "$fresh/server.ts"; import { start } from "$fresh/server.ts";
import routes from "./fresh.gen.ts"; import routes from "./fresh.gen.ts";
const experimentalDenoServe = Deno.args.includes("--experimental-deno-serve"); await start(routes);
await start(routes, { experimentalDenoServe });
+1 -3
View File
@@ -8,6 +8,4 @@ import { start } from "$fresh/server.ts";
import routes from "./fresh.gen.ts"; import routes from "./fresh.gen.ts";
import options from "./options.ts"; import options from "./options.ts";
const experimentalDenoServe = Deno.args.includes("--experimental-deno-serve"); await start(routes, options);
await start(routes, { ...options, experimentalDenoServe });
+1 -3
View File
@@ -11,6 +11,4 @@ import { start } from "$fresh/server.ts";
import routes from "./fresh.gen.ts"; import routes from "./fresh.gen.ts";
import options from "./options.ts"; import options from "./options.ts";
const experimentalDenoServe = Deno.args.includes("--experimental-deno-serve"); await start(routes, options);
await start(routes, { ...options, experimentalDenoServe });
-66
View File
@@ -269,11 +269,6 @@ Deno.test("static files in custom directory", async () => {
}); });
const newRouter = (req: Request) => { const newRouter = (req: Request) => {
return newCtx.handler()(req, { return newCtx.handler()(req, {
localAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
remoteAddr: { remoteAddr: {
transport: "tcp", transport: "tcp",
hostname: "127.0.0.1", hostname: "127.0.0.1",
@@ -670,67 +665,6 @@ Deno.test({
}, },
}); });
Deno.test("experimental Deno.serve", {
sanitizeOps: false,
sanitizeResources: false,
ignore: Deno.build.os === "windows", // TODO: Deno.serve hang on Windows?
}, async (t) => {
// Preparation
const { serverProcess, lines, address } = await startFreshServer({
args: [
"run",
"-A",
"--unstable",
"./tests/fixture/main.ts",
"--experimental-deno-serve",
],
});
await delay(100);
await t.step("ssr", async () => {
const resp = await fetch(address);
assert(resp);
assertEquals(resp.status, Status.OK);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
assertEquals(resp.headers.get("server"), "fresh test server");
const body = await resp.text();
assertStringIncludes(body, `<html lang="en">`);
assertStringIncludes(body, "test_default.js");
assertStringIncludes(body, "<p>Hello!</p>");
assertStringIncludes(body, "<p>Viewing JIT render.</p>");
assertStringIncludes(body, `>{"v":[[{"message":"Hello!"}],[]]}</script>`);
assertStringIncludes(
body,
'<meta name="description" content="Hello world!"/>',
);
assertStringIncludes(
body,
'<meta name="generator" content="The freshest framework!"/>',
);
assert(
!body.includes("specialTag"),
`Expected actual: "${body}" to not contain: "specialTag"`,
);
});
await t.step("static file", async () => {
const resp = await fetch(`${address}/foo.txt`);
assertEquals(resp.status, Status.OK);
const body = await resp.text();
assert(body.startsWith("bar"));
const etag = resp.headers.get("etag");
assert(etag);
// TODO(kt3k): Enable this assertion when new Deno.serve is released.
// https://github.com/denoland/deno/pull/18568
// assert(etag.startsWith("W/"), "etag should be weak");
assertEquals(resp.headers.get("content-type"), "text/plain");
});
await lines.cancel();
serverProcess.kill("SIGTERM");
});
Deno.test("jsx pragma works", { Deno.test("jsx pragma works", {
sanitizeOps: false, sanitizeOps: false,
sanitizeResources: false, sanitizeResources: false,
-5
View File
@@ -14,11 +14,6 @@ const ctx = await ServerContext.fromManifest(manifest, options);
const handler = ctx.handler(); const handler = ctx.handler();
const router = (req: Request) => { const router = (req: Request) => {
return handler(req, { return handler(req, {
localAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
remoteAddr: { remoteAddr: {
transport: "tcp", transport: "tcp",
hostname: "127.0.0.1", hostname: "127.0.0.1",
-5
View File
@@ -10,11 +10,6 @@ const ctx = await ServerContext.fromManifest(manifest, {
}); });
const router = (req: Request) => { const router = (req: Request) => {
return ctx.handler()(req, { return ctx.handler()(req, {
localAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
remoteAddr: { remoteAddr: {
transport: "tcp", transport: "tcp",
hostname: "127.0.0.1", hostname: "127.0.0.1",
+1
View File
@@ -61,6 +61,7 @@ function ga4(
// Create basic report. // Create basic report.
const measurementId = GA4_MEASUREMENT_ID; const measurementId = GA4_MEASUREMENT_ID;
// @ts-ignore GA4Report doesn't even use the localAddress parameter
const report = new GA4Report({ measurementId, request, response, conn }); const report = new GA4Report({ measurementId, request, response, conn });
// Override the default (page_view) event. // Override the default (page_view) event.