feat: add middleware destination (#1123)

Closes #521
This commit is contained in:
Leo Kettmeir
2023-04-20 13:14:12 +02:00
committed by GitHub
parent f3f6f227c4
commit 9dd026e0f5
5 changed files with 159 additions and 64 deletions
+42 -23
View File
@@ -22,6 +22,7 @@ import {
Handler, Handler,
Island, Island,
Middleware, Middleware,
MiddlewareHandlerContext,
MiddlewareModule, MiddlewareModule,
MiddlewareRoute, MiddlewareRoute,
Plugin, Plugin,
@@ -310,8 +311,12 @@ export class ServerContext {
* by fresh, including static files. * by fresh, including static files.
*/ */
handler(): RequestHandler { handler(): RequestHandler {
const inner = router.router<RouterState>(...this.#handlers()); const handlers = this.#handlers();
const withMiddlewares = this.#composeMiddlewares(this.#middlewares); const inner = router.router<RouterState>(handlers);
const withMiddlewares = this.#composeMiddlewares(
this.#middlewares,
handlers.errorHandler,
);
return async function handler(req: Request, connInfo: ConnInfo) { return async function handler(req: Request, connInfo: ConnInfo) {
// Redirect requests that end with a trailing slash // Redirect requests that end with a trailing slash
// to their non-trailing slash counterpart. // to their non-trailing slash counterpart.
@@ -346,11 +351,14 @@ export class ServerContext {
* Identify which middlewares should be applied for a request, * Identify which middlewares should be applied for a request,
* chain them and return a handler response * chain them and return a handler response
*/ */
#composeMiddlewares(middlewares: MiddlewareRoute[]) { #composeMiddlewares(
middlewares: MiddlewareRoute[],
errorHandler: router.ErrorHandler<RouterState>,
) {
return ( return (
req: Request, req: Request,
connInfo: ConnInfo, connInfo: ConnInfo,
inner: router.Handler<RouterState>, inner: router.FinalHandler<RouterState>,
) => { ) => {
// identify middlewares to apply, if any. // identify middlewares to apply, if any.
// middlewares should be already sorted from deepest to shallow layer // middlewares should be already sorted from deepest to shallow layer
@@ -358,30 +366,38 @@ export class ServerContext {
const handlers: (() => Response | Promise<Response>)[] = []; const handlers: (() => Response | Promise<Response>)[] = [];
const ctx = { const middlewareCtx: MiddlewareHandlerContext = {
next() { next() {
const handler = handlers.shift()!; const handler = handlers.shift()!;
return Promise.resolve(handler()); return Promise.resolve(handler());
}, },
...connInfo, ...connInfo,
state: {}, state: {},
destination: "route",
}; };
for (const mw of mws) { for (const mw of mws) {
if (mw.handler instanceof Array) { if (mw.handler instanceof Array) {
for (const handler of mw.handler) { for (const handler of mw.handler) {
handlers.push(() => handler(req, ctx)); handlers.push(() => handler(req, middlewareCtx));
} }
} else { } else {
const handler = mw.handler; const handler = mw.handler;
handlers.push(() => handler(req, ctx)); handlers.push(() => handler(req, middlewareCtx));
} }
} }
handlers.push(() => inner(req, ctx)); const ctx = {
...connInfo,
const handler = handlers.shift()!; state: middlewareCtx.state,
return handler(); };
const { destination, handler } = inner(
req,
ctx,
);
handlers.push(handler);
middlewareCtx.destination = destination;
return middlewareCtx.next().catch((e) => errorHandler(req, ctx, e));
}; };
} }
@@ -389,20 +405,23 @@ export class ServerContext {
* This function returns all routes required by fresh as an extended * This function returns all routes required by fresh as an extended
* path-to-regex, to handler mapping. * path-to-regex, to handler mapping.
*/ */
#handlers(): [ #handlers(): {
router.Routes<RouterState>, internalRoutes: router.Routes<RouterState>;
{ staticRoutes: router.Routes<RouterState>;
otherHandler: router.Handler<RouterState>; routes: router.Routes<RouterState>;
errorHandler: router.ErrorHandler<RouterState>;
}, otherHandler: router.Handler<RouterState>;
] { errorHandler: router.ErrorHandler<RouterState>;
} {
const internalRoutes: router.Routes<RouterState> = {};
const staticRoutes: router.Routes<RouterState> = {};
const routes: router.Routes<RouterState> = {}; const routes: router.Routes<RouterState> = {};
routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = { internalRoutes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = {
default: this.#bundleAssetRoute(), default: this.#bundleAssetRoute(),
}; };
if (this.#dev) { if (this.#dev) {
routes[REFRESH_JS_URL] = { internalRoutes[REFRESH_JS_URL] = {
default: () => { default: () => {
const js = const js =
`new EventSource("${ALIVE_URL}").addEventListener("message", function listener(e) { if (e.data !== "${BUILD_ID}") { this.removeEventListener('message', listener); location.reload(); } });`; `new EventSource("${ALIVE_URL}").addEventListener("message", function listener(e) { if (e.data !== "${BUILD_ID}") { this.removeEventListener('message', listener); location.reload(); } });`;
@@ -413,7 +432,7 @@ export class ServerContext {
}); });
}, },
}; };
routes[ALIVE_URL] = { internalRoutes[ALIVE_URL] = {
default: () => { default: () => {
let timerId: number | undefined = undefined; let timerId: number | undefined = undefined;
const body = new ReadableStream({ const body = new ReadableStream({
@@ -446,7 +465,7 @@ export class ServerContext {
const { localUrl, path, size, contentType, etag } of this.#staticFiles const { localUrl, path, size, contentType, etag } of this.#staticFiles
) { ) {
const route = sanitizePathToRegex(path); const route = sanitizePathToRegex(path);
routes[route] = { staticRoutes[route] = {
"GET": this.#staticFileHandler( "GET": this.#staticFileHandler(
localUrl, localUrl,
size, size,
@@ -590,7 +609,7 @@ export class ServerContext {
); );
}; };
return [routes, { otherHandler, errorHandler }]; return { internalRoutes, staticRoutes, routes, otherHandler, errorHandler };
} }
#staticFileHandler( #staticFileHandler(
+74 -41
View File
@@ -7,6 +7,14 @@ export type Handler<T = unknown> = (
ctx: HandlerContext<T>, ctx: HandlerContext<T>,
) => Response | Promise<Response>; ) => Response | Promise<Response>;
export type FinalHandler<T = unknown> = (
req: Request,
ctx: HandlerContext<T>,
) => {
destination: DestinationKind;
handler: () => Response | Promise<Response>;
};
export type ErrorHandler<T = unknown> = ( export type ErrorHandler<T = unknown> = (
req: Request, req: Request,
ctx: HandlerContext<T>, ctx: HandlerContext<T>,
@@ -30,16 +38,22 @@ export interface Routes<T = {}> {
[key: string]: { [K in KnownMethod | "default"]?: MatchHandler<T> }; [key: string]: { [K in KnownMethod | "default"]?: MatchHandler<T> };
} }
export type DestinationKind = "internal" | "static" | "route" | "notFound";
// deno-lint-ignore ban-types // deno-lint-ignore ban-types
export type InternalRoute<T = {}> = { export type InternalRoute<T = {}> = {
pattern: URLPattern; pattern: URLPattern;
methods: { [K in KnownMethod]?: MatchHandler<T> }; methods: { [K in KnownMethod]?: MatchHandler<T> };
default?: MatchHandler<T>; default?: MatchHandler<T>;
destination: DestinationKind;
}; };
export interface RouterOptions<T> { export interface RouterOptions<T> {
otherHandler?: Handler<T>; internalRoutes: Routes<T>;
errorHandler?: ErrorHandler<T>; staticRoutes: Routes<T>;
routes: Routes<T>;
otherHandler: Handler<T>;
errorHandler: ErrorHandler<T>;
unknownMethodHandler?: UnknownMethodHandler<T>; unknownMethodHandler?: UnknownMethodHandler<T>;
} }
@@ -86,24 +100,17 @@ export function defaultUnknownMethodHandler(
}); });
} }
export function router<T = unknown>( function processRoutes<T>(
processedRoutes: InternalRoute<T>[],
routes: Routes<T>, routes: Routes<T>,
{ otherHandler, errorHandler, unknownMethodHandler }: RouterOptions<T> = { destination: DestinationKind,
otherHandler: defaultOtherHandler, ) {
errorHandler: defaultErrorHandler,
unknownMethodHandler: defaultUnknownMethodHandler,
},
): Handler<T> {
otherHandler ??= defaultOtherHandler;
errorHandler ??= defaultErrorHandler;
unknownMethodHandler ??= defaultUnknownMethodHandler;
const internalRoutes: InternalRoute<T>[] = [];
for (const [path, methods] of Object.entries(routes)) { for (const [path, methods] of Object.entries(routes)) {
const entry: InternalRoute<T> = { const entry: InternalRoute<T> = {
pattern: new URLPattern({ pathname: path }), pattern: new URLPattern({ pathname: path }),
methods: {}, methods: {},
default: undefined, default: undefined,
destination,
}; };
for (const [method, handler] of Object.entries(methods)) { for (const [method, handler] of Object.entries(methods)) {
@@ -114,42 +121,68 @@ export function router<T = unknown>(
} }
} }
internalRoutes.push(entry); processedRoutes.push(entry);
} }
}
return async (req, ctx) => { export function router<T = unknown>(
try { {
for (const route of internalRoutes) { internalRoutes,
const res = route.pattern.exec(req.url); staticRoutes,
routes,
otherHandler,
unknownMethodHandler,
}: RouterOptions<T>,
): FinalHandler<T> {
unknownMethodHandler ??= defaultUnknownMethodHandler;
if (res !== null) { const processedRoutes: InternalRoute<T>[] = [];
const groups = res?.pathname.groups ?? {}; processRoutes(processedRoutes, internalRoutes, "internal");
processRoutes(processedRoutes, staticRoutes, "static");
processRoutes(processedRoutes, routes, "route");
for (const key in groups) { return (req, ctx) => {
groups[key] = decodeURIComponent(groups[key]); for (const route of processedRoutes) {
} const res = route.pattern.exec(req.url);
for (const [method, handler] of Object.entries(route.methods)) { if (res !== null) {
if (req.method === method) { const groups = res?.pathname.groups ?? {};
return await handler(req, ctx, groups);
}
}
if (route.default) { for (const key in groups) {
return await route.default(req, ctx, groups); groups[key] = decodeURIComponent(groups[key]);
} else { }
return await unknownMethodHandler!(
req, for (const [method, handler] of Object.entries(route.methods)) {
ctx, if (req.method === method) {
Object.keys(route.methods) as KnownMethod[], return {
); destination: route.destination,
handler: () => handler(req, ctx, groups),
};
} }
} }
}
return await otherHandler!(req, ctx); if (route.default) {
} catch (err) { return {
return errorHandler!(req, ctx, err); destination: route.destination,
handler: () => route.default!(req, ctx, groups),
};
} else {
return {
destination: route.destination,
handler: () =>
unknownMethodHandler!(
req,
ctx,
Object.keys(route.methods) as KnownMethod[],
),
};
}
}
} }
return {
destination: "notFound",
handler: () => otherHandler!(req, ctx),
};
}; };
} }
+1
View File
@@ -201,6 +201,7 @@ export interface MiddlewareHandlerContext<State = Record<string, unknown>>
extends ConnInfo { extends ConnInfo {
next: () => Promise<Response>; next: () => Promise<Response>;
state: State; state: State;
destination: router.DestinationKind;
} }
export interface MiddlewareRoute extends Middleware { export interface MiddlewareRoute extends Middleware {
+10
View File
@@ -50,8 +50,18 @@ async function rootHandler(
return resp; return resp;
} }
async function kindHandler(
_req: Request,
ctx: MiddlewareHandlerContext,
) {
const resp = await ctx.next();
resp.headers.set("destination", ctx.destination);
return resp;
}
export const handler: MiddlewareHandler | MiddlewareHandler[] = [ export const handler: MiddlewareHandler | MiddlewareHandler[] = [
rootHandler, rootHandler,
logHandler, logHandler,
kindHandler,
corsHandler, corsHandler,
]; ];
+32
View File
@@ -494,6 +494,38 @@ Deno.test({
}, },
}); });
Deno.test("middleware destination", async (t) => {
await t.step("internal", async () => {
const resp = await router(
new Request("https://fresh.deno.dev/_frsh/refresh.js"),
);
assert(resp);
assertEquals(resp.headers.get("destination"), "internal");
await resp.body?.cancel();
});
await t.step("static", async () => {
const resp = await router(new Request("https://fresh.deno.dev/foo.txt"));
assert(resp);
assertEquals(resp.headers.get("destination"), "static");
await resp.body?.cancel();
});
await t.step("route", async () => {
const resp = await router(new Request("https://fresh.deno.dev/"));
assert(resp);
assertEquals(resp.headers.get("destination"), "route");
await resp.body?.cancel();
});
await t.step("notFound", async () => {
const resp = await router(new Request("https://fresh.deno.dev/bar/bar"));
assert(resp);
assertEquals(resp.headers.get("destination"), "notFound");
await resp.body?.cancel();
});
});
Deno.test("experimental Deno.serve", { Deno.test("experimental Deno.serve", {
sanitizeOps: false, sanitizeOps: false,
sanitizeResources: false, sanitizeResources: false,