feat: stream static files (#79)

This commit adds support for streaming static files. Instead of them
being fully buffered in memory, they are now streamed directly to the
client.
This commit is contained in:
Luca Casonato
2022-01-04 17:43:08 +01:00
committed by GitHub
parent 64da4005bb
commit 6abf62c832
2 changed files with 45 additions and 21 deletions
+1 -1
View File
@@ -8,4 +8,4 @@ test:
deno test -A --no-check deno test -A --no-check
dev: dev:
deno run -A --watch --no-check www/main.ts deno run -A --watch=www/static --no-check www/main.ts
+44 -20
View File
@@ -27,17 +27,28 @@ import {
SELF, SELF,
} from "../runtime/csp.ts"; } from "../runtime/csp.ts";
interface StaticFile {
/** The URL to the static file on disk. */
localUrl: URL;
/** The path to the file as it would be in the incoming request. */
path: string;
/** The size of the file. */
size: number;
/** The content-type of the file. */
contentType: string;
}
export class ServerContext { export class ServerContext {
#dev: boolean; #dev: boolean;
#pages: Page[]; #pages: Page[];
#staticFiles: [URL, string][]; #staticFiles: StaticFile[];
#bundler: Bundler; #bundler: Bundler;
#renderer: Renderer; #renderer: Renderer;
#middleware: Middleware; #middleware: Middleware;
constructor( constructor(
pages: Page[], pages: Page[],
staticFiles: [URL, string][], staticFiles: StaticFile[],
renderer: Renderer, renderer: Renderer,
middleware: Middleware, middleware: Middleware,
) { ) {
@@ -106,7 +117,7 @@ export class ServerContext {
} }
sortRoutes(pages); sortRoutes(pages);
const staticFiles: [URL, string][] = []; const staticFiles: StaticFile[] = [];
try { try {
const staticFolder = new URL("./static", routes.baseUrl); const staticFolder = new URL("./static", routes.baseUrl);
// TODO(lucacasonato): remove the extranious Deno.readDir when // TODO(lucacasonato): remove the extranious Deno.readDir when
@@ -120,9 +131,18 @@ export class ServerContext {
followSymlinks: false, followSymlinks: false,
}); });
for await (const entry of entires) { for await (const entry of entires) {
const path = toFileUrl(entry.path); const localUrl = toFileUrl(entry.path);
const subpath = path.href.substring(staticFolder.href.length); const path = localUrl.href.substring(staticFolder.href.length);
staticFiles.push([path, subpath]); const stat = await Deno.stat(localUrl);
const contentType = mediaTypeLookup(extname(path)) ??
"application/octet-stream";
const staticFile: StaticFile = {
localUrl,
path,
size: stat.size,
contentType,
};
staticFiles.push(staticFile);
} }
} catch (err) { } catch (err) {
if (err instanceof Deno.errors.NotFound) { if (err instanceof Deno.errors.NotFound) {
@@ -163,9 +183,13 @@ export class ServerContext {
const routes: router.Routes = {}; const routes: router.Routes = {};
// Add the static file routes. // Add the static file routes.
for (const [fullPath, path] of this.#staticFiles) { for (const { localUrl, path, size, contentType } of this.#staticFiles) {
const route = sanitizePathToRegex(path); const route = sanitizePathToRegex(path);
routes[`GET@${route}`] = this.#staticFileHandler(fullPath); routes[`GET@${route}`] = this.#staticFileHandler(
localUrl,
size,
contentType,
);
} }
for (const page of this.#pages) { for (const page of this.#pages) {
@@ -299,19 +323,19 @@ export class ServerContext {
return routes; return routes;
} }
#staticFileHandler(fullPath: URL): router.MatchHandler { #staticFileHandler(
localUrl: URL,
size: number,
contentType: string,
): router.MatchHandler {
return async (_req: Request) => { return async (_req: Request) => {
try { const resp = await fetch(localUrl);
const data = await Deno.readFile(fullPath); return new Response(resp.body, {
const contentType = mediaTypeLookup(extname(fullPath.href)) ?? headers: {
"application/octet-stream"; "content-type": contentType,
return new Response(data, { headers: { "content-type": contentType } }); "content-length": String(size),
} catch (err) { },
if (err instanceof Deno.errors.NotFound) { });
return new Response("404 Not Found", { status: 404 });
}
throw err;
}
}; };
} }