|
| 1 | +// The whole production server: static client assets plus one import — the |
| 2 | +// built server bundle's `handleRequest`, an adapter-agnostic web |
| 3 | +// `Request -> Response` that streams the SSR render, resolves hashed assets |
| 4 | +// through the build manifest, and serves the `/_server` endpoint. The node |
| 5 | +// <-> web plumbing below is the only glue. |
| 6 | +// |
| 7 | +// Responses are compressed because every deployed host compresses text, and |
| 8 | +// a benchmark against an uncompressed origin measures the harness rather than |
| 9 | +// the app. Brotli quality 4 keeps per-chunk flushes cheap while still ~6x on |
| 10 | +// HTML; each SSR chunk is flushed so streaming boundaries survive. |
| 11 | +import { createServer } from "node:http"; |
| 12 | +import { readFileSync } from "node:fs"; |
| 13 | +import { Readable } from "node:stream"; |
| 14 | +import { fileURLToPath } from "node:url"; |
| 15 | +import path from "node:path"; |
| 16 | +import { brotliCompressSync, createBrotliCompress, createGzip, constants } from "node:zlib"; |
| 17 | +import { handleRequest } from "./dist/server/server.js"; |
| 18 | + |
| 19 | +const root = path.dirname(fileURLToPath(import.meta.url)); |
| 20 | +const PORT = process.env.PORT || 3020; |
| 21 | + |
| 22 | +const MIME = { |
| 23 | + ".js": "application/javascript", |
| 24 | + ".css": "text/css", |
| 25 | + ".html": "text/html", |
| 26 | + ".json": "application/json", |
| 27 | + ".ico": "image/x-icon", |
| 28 | + ".svg": "image/svg+xml" |
| 29 | +}; |
| 30 | + |
| 31 | +/** Negotiated streaming compressor piped into `res`, or null for identity. */ |
| 32 | +function encoder(req, res) { |
| 33 | + const accepts = req.headers["accept-encoding"] || ""; |
| 34 | + let stream; |
| 35 | + if (/\bbr\b/.test(accepts)) { |
| 36 | + res.setHeader("Content-Encoding", "br"); |
| 37 | + stream = createBrotliCompress({ params: { [constants.BROTLI_PARAM_QUALITY]: 4 } }); |
| 38 | + } else if (/\bgzip\b/.test(accepts)) { |
| 39 | + res.setHeader("Content-Encoding", "gzip"); |
| 40 | + stream = createGzip(); |
| 41 | + } else return null; |
| 42 | + stream.pipe(res); |
| 43 | + return stream; |
| 44 | +} |
| 45 | + |
| 46 | +// Static assets compress once at a higher quality — they're cached, not streamed. |
| 47 | +const staticBrotli = new Map(); |
| 48 | + |
| 49 | +function webRequest(req, signal) { |
| 50 | + const url = new URL(req.url || "/", `http://${req.headers.host || `localhost:${PORT}`}`); |
| 51 | + const method = req.method || "GET"; |
| 52 | + const body = method === "GET" || method === "HEAD" ? undefined : Readable.toWeb(req); |
| 53 | + return new Request(url, { |
| 54 | + method, |
| 55 | + headers: req.headers, |
| 56 | + body, |
| 57 | + signal, |
| 58 | + ...(body ? { duplex: "half" } : {}) |
| 59 | + }); |
| 60 | +} |
| 61 | + |
| 62 | +createServer(async (req, res) => { |
| 63 | + const url = req.url || "/"; |
| 64 | + |
| 65 | + if (url !== "/" && !url.includes("..")) { |
| 66 | + const file = url.split("?")[0]; |
| 67 | + try { |
| 68 | + const content = readFileSync(path.resolve(root, "dist/client" + file)); |
| 69 | + const headers = { |
| 70 | + "Content-Type": MIME[path.extname(file)] ?? "application/octet-stream", |
| 71 | + "Cache-Control": "public, max-age=3600" |
| 72 | + }; |
| 73 | + if (/\bbr\b/.test(req.headers["accept-encoding"] || "")) { |
| 74 | + let compressed = staticBrotli.get(file); |
| 75 | + if (!compressed) { |
| 76 | + compressed = brotliCompressSync(content, { |
| 77 | + params: { [constants.BROTLI_PARAM_QUALITY]: 9 } |
| 78 | + }); |
| 79 | + staticBrotli.set(file, compressed); |
| 80 | + } |
| 81 | + res.writeHead(200, { ...headers, "Content-Encoding": "br" }); |
| 82 | + return res.end(compressed); |
| 83 | + } |
| 84 | + res.writeHead(200, headers); |
| 85 | + return res.end(content); |
| 86 | + } catch { |
| 87 | + // Fall through to the handler (SSR routes, /_server, ...). |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + // A tab that closes must end its render: the live table's simulation runs |
| 92 | + // only while someone is watching. |
| 93 | + const gone = new AbortController(); |
| 94 | + res.on("close", () => gone.abort()); |
| 95 | + try { |
| 96 | + const response = await handleRequest(webRequest(req, gone.signal)); |
| 97 | + const cookies = response.headers.getSetCookie?.(); |
| 98 | + response.headers.forEach((value, key) => { |
| 99 | + if (key !== "set-cookie") res.setHeader(key, value); |
| 100 | + }); |
| 101 | + if (cookies?.length) res.setHeader("set-cookie", cookies); |
| 102 | + res.statusCode = response.status; |
| 103 | + const out = encoder(req, res) ?? res; |
| 104 | + if (response.body) { |
| 105 | + const reader = response.body.getReader(); |
| 106 | + gone.signal.addEventListener("abort", () => reader.cancel().catch(() => {}), { once: true }); |
| 107 | + for (;;) { |
| 108 | + const { done, value } = await reader.read(); |
| 109 | + if (done) break; |
| 110 | + out.write(value); |
| 111 | + if (out !== res) out.flush(); |
| 112 | + } |
| 113 | + } |
| 114 | + out.end(); |
| 115 | + } catch (e) { |
| 116 | + console.error(e); |
| 117 | + res.statusCode = 500; |
| 118 | + res.end(e.message); |
| 119 | + } |
| 120 | +}).listen(PORT, () => { |
| 121 | + console.log(`DBMon (server components) on http://localhost:${PORT}`); |
| 122 | +}); |
0 commit comments