Make the site faster to load and lighter on the server
- Every page but Home, and the whole admin, loads on first visit: the main bundle drops from 579 kB to 314 kB (173 to 98 kB gzipped); a tab on an old build reloads once when a page chunk has gone - Home asks for events and the timeline alongside its own data, and the server preloads /api/front-page and the first hero photo - Hero headline rises in as one piece (it held back the page's largest paint), sized to stay within two lines; min-h in dvh; first slide fetched at high priority - Every raster upload gets a 640px copy (at upload, and at boot for older files); logos, avatars and card pictures load it and fall back to the full file - Login password checks run off the event loop; only admin requests are logged per request; ffmpeg runs at nice 19 on Linux - Page HTML is no-cache, so a deploy can't strand a cached page on missing assets; source maps are no longer linked - Migration 042: index person_awards by award - docs/performance.md, and gzip and HTTP/2 for nginx Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
be7e92417e
commit
f72a9604d2
23 changed files with 420 additions and 139 deletions
|
|
@ -18,9 +18,11 @@
|
|||
import {
|
||||
createHash,
|
||||
randomBytes,
|
||||
scrypt,
|
||||
scryptSync,
|
||||
timingSafeEqual,
|
||||
} from "node:crypto";
|
||||
import { promisify } from "node:util";
|
||||
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
|
||||
|
||||
const SESSION_DAYS = 30;
|
||||
|
|
@ -68,7 +70,11 @@ export function hashPassword(password) {
|
|||
].join("$");
|
||||
}
|
||||
|
||||
export function verifyPassword(password, stored) {
|
||||
/* Async: a login's hash runs on libuv's thread pool, so the ~100 ms it
|
||||
takes doesn't stall every other request while it runs. */
|
||||
const scryptAsync = promisify(scrypt);
|
||||
|
||||
export async function verifyPassword(password, stored) {
|
||||
if (typeof stored !== "string") return false;
|
||||
|
||||
const [scheme, N, r, p, saltHex, keyHex] = stored.split("$");
|
||||
|
|
@ -76,7 +82,7 @@ export function verifyPassword(password, stored) {
|
|||
|
||||
let candidate;
|
||||
try {
|
||||
candidate = scryptSync(
|
||||
candidate = await scryptAsync(
|
||||
password.normalize("NFKC"),
|
||||
Buffer.from(saltHex, "hex"),
|
||||
Buffer.from(keyHex, "hex").length,
|
||||
|
|
|
|||
|
|
@ -150,11 +150,16 @@ export function checkClip(input, source) {
|
|||
|
||||
/* Runs a tool, calling onLine for each line of its output, and
|
||||
resolves with the tail of stderr, or rejects with it. */
|
||||
function run(command, args, { onLine } = {}) {
|
||||
function run(command, args, { onLine, background = false } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let child;
|
||||
// An encode takes every core it can get; at the lowest priority it
|
||||
// still does, but the API and its pages come first. Linux only
|
||||
// (the VPS); elsewhere it runs as it is.
|
||||
const [cmd, argv] =
|
||||
background && process.platform === "linux" ? ["nice", ["-n", "19", command, ...args]] : [command, args];
|
||||
try {
|
||||
child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
||||
child = spawn(cmd, argv, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
return;
|
||||
|
|
@ -425,6 +430,7 @@ async function cut(db, job) {
|
|||
args.push("-progress", "pipe:1", "-nostats", filePath(name));
|
||||
|
||||
await run(FFMPEG, args, {
|
||||
background: true,
|
||||
onLine: (line) => {
|
||||
const us = line.match(/^out_time_us=(\d+)/);
|
||||
if (us) update(db, job.id, { progress: Math.min(0.99, Number(us[1]) / 1e6 / length) });
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ import adminEntities from "./routes/admin-entities.js";
|
|||
import media from "./routes/media.js";
|
||||
import clips from "./routes/clips.js";
|
||||
import { CLIPS_DIR, startClipWorker } from "./clips.js";
|
||||
import { UPLOADS_DIR } from "./media.js";
|
||||
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
|
||||
import { logSafe, startSessionSweeper } from "./auth.js";
|
||||
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
|
||||
import { ENTITIES } from "./admin-schema.js";
|
||||
|
|
@ -53,12 +53,20 @@ syncDescriptorsWithSchema(db, ENTITIES);
|
|||
console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`);
|
||||
await mkdir(UPLOADS_DIR, { recursive: true });
|
||||
console.log(`uploads ${UPLOADS_DIR}`);
|
||||
// In the background: pages fall back to the full file until it's done.
|
||||
writeMissingThumbs()
|
||||
.then((made) => made && console.log(`uploads: made ${made} small copies`))
|
||||
.catch((err) => console.warn(`uploads: small copies failed: ${err.message}`));
|
||||
|
||||
/* ── App ─────────────────────────────────────────────────────── */
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
app.use("*", logger());
|
||||
// One log line per admin request, for the record of who did what.
|
||||
// Public traffic is left to nginx's access log: logging every request
|
||||
// here too would double the lines and, under a spike, cost the event
|
||||
// loop a synchronous write each.
|
||||
app.use("/api/admin/*", logger());
|
||||
|
||||
/* Headers for every response. Referrer kept to the origin (YouTube
|
||||
embeds refuse to play without one). No HSTS here: nginx sends it on
|
||||
|
|
|
|||
|
|
@ -172,6 +172,7 @@ export async function store(buf, { keepOriginal = false } = {}) {
|
|||
const tmp = path.join(UPLOADS_DIR, `.${filename}.tmp`);
|
||||
await writeFile(tmp, out);
|
||||
await rename(tmp, path.join(UPLOADS_DIR, filename));
|
||||
if (kind !== "svg") await writeThumb(filename, out);
|
||||
|
||||
return {
|
||||
filename,
|
||||
|
|
@ -183,16 +184,72 @@ export async function store(buf, { keepOriginal = false } = {}) {
|
|||
};
|
||||
}
|
||||
|
||||
/* Deletes one stored file. A file that's already gone is not an
|
||||
error: the row is what's being removed. */
|
||||
/* ── Small copies ──────────────────────────────────────────────
|
||||
Beside every raster upload, <name>-640.webp: the same image at most
|
||||
640px on its longer side. Photos and logos shown small (avatars,
|
||||
cards, marks) load it instead of the full file; the page falls back
|
||||
to the full file if it's missing (src/lib/media.ts, mediaThumb).
|
||||
Made when a file is uploaded, and at boot for any upload that
|
||||
doesn't have one yet (files from before this, or copied in by hand).
|
||||
───────────────────────────────────────────────────────────── */
|
||||
|
||||
export const THUMB_EDGE = 640;
|
||||
const THUMB = /-640\.webp$/;
|
||||
|
||||
export const thumbName = (filename) => `${filename.replace(/\.[^.]+$/, "")}-640.webp`;
|
||||
|
||||
async function writeThumb(filename, buf) {
|
||||
const name = thumbName(filename);
|
||||
const tmp = path.join(UPLOADS_DIR, `.${name}.tmp`);
|
||||
try {
|
||||
await sharp(buf, { animated: true, limitInputPixels: MAX_INPUT_PIXELS })
|
||||
.rotate()
|
||||
.resize({ width: THUMB_EDGE, height: THUMB_EDGE, fit: "inside", withoutEnlargement: true })
|
||||
.webp({ quality: WEBP_QUALITY })
|
||||
.toFile(tmp);
|
||||
await rename(tmp, path.join(UPLOADS_DIR, name));
|
||||
} catch (err) {
|
||||
// The full file is what matters; without a copy the page uses it.
|
||||
await unlink(tmp).catch(() => {});
|
||||
console.warn(`media: no small copy of ${filename}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/* Makes the small copy for every raster upload that lacks one.
|
||||
Returns how many it made. */
|
||||
export async function writeMissingThumbs() {
|
||||
let names;
|
||||
try {
|
||||
names = await readdir(UPLOADS_DIR);
|
||||
} catch (err) {
|
||||
if (err.code === "ENOENT") return 0;
|
||||
throw err;
|
||||
}
|
||||
const present = new Set(names);
|
||||
let made = 0;
|
||||
for (const name of names) {
|
||||
if (name.startsWith(".") || THUMB.test(name) || /\.svg$/i.test(name)) continue;
|
||||
if (present.has(thumbName(name))) continue;
|
||||
const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null);
|
||||
if (!buf || !sniff(buf) || sniff(buf) === "svg") continue;
|
||||
await writeThumb(name, buf);
|
||||
made += 1;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
/* Deletes one stored file and its small copy. A file that's already
|
||||
gone is not an error: the row is what's being removed. */
|
||||
export async function remove(filename) {
|
||||
// filename comes from our own table, but it's joined onto a
|
||||
// directory, so refuse anything that isn't a bare name.
|
||||
if (path.basename(filename) !== filename) return;
|
||||
try {
|
||||
await unlink(path.join(UPLOADS_DIR, filename));
|
||||
} catch (err) {
|
||||
if (err.code !== "ENOENT") throw err;
|
||||
for (const name of [filename, thumbName(filename)]) {
|
||||
try {
|
||||
await unlink(path.join(UPLOADS_DIR, name));
|
||||
} catch (err) {
|
||||
if (err.code !== "ENOENT") throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -252,7 +309,7 @@ export async function registerLooseFiles(db) {
|
|||
|
||||
let added = 0;
|
||||
for (const name of names) {
|
||||
if (known.has(name) || name.startsWith(".") || path.basename(name) !== name) continue;
|
||||
if (known.has(name) || name.startsWith(".") || THUMB.test(name) || path.basename(name) !== name) continue;
|
||||
let row;
|
||||
try {
|
||||
row = await describe(name);
|
||||
|
|
|
|||
10
server/src/migrations/042_person_awards_index.sql
Normal file
10
server/src/migrations/042_person_awards_index.sql
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 042 AWARD RECIPIENTS BY AWARD
|
||||
--
|
||||
-- person_awards is read by award (an award's page lists its
|
||||
-- recipients, an organization counts them), but its only index
|
||||
-- starts with person_id, so those reads scan the table. Tiny today;
|
||||
-- this keeps it from mattering later.
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE INDEX person_awards_award_idx ON person_awards (award_id);
|
||||
|
|
@ -347,8 +347,23 @@ export function metaFor(db, rawPath) {
|
|||
const meta = defaults(site, db, pathname);
|
||||
|
||||
if (pathname === "/") {
|
||||
// The home page's data, and its first hero photo when the hero is
|
||||
// a slideshow, requested alongside the app's JavaScript instead of
|
||||
// after it has run.
|
||||
const hero = db.prepare(`SELECT hero_backdrop FROM front_page WHERE id = 'home'`).get();
|
||||
const slide =
|
||||
hero?.hero_backdrop === "photos"
|
||||
? db
|
||||
.prepare(`SELECT media FROM front_page_slides WHERE page_id = 'home' ORDER BY sort_order LIMIT 1`)
|
||||
.get()
|
||||
: null;
|
||||
const slideSrc = slide?.media ? (/^(https?:|\/)/.test(slide.media) ? slide.media : `${UPLOADS}/${slide.media}`) : null;
|
||||
return {
|
||||
...meta,
|
||||
preload: [
|
||||
{ href: "/api/front-page", as: "fetch" },
|
||||
...(slideSrc ? [{ href: slideSrc, as: "image" }] : []),
|
||||
],
|
||||
jsonLd: {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Organization",
|
||||
|
|
@ -446,6 +461,11 @@ export function renderPage(html, meta) {
|
|||
site.icons?.icon && `<link rel="icon" href="${escapeHtml(site.icons.icon)}">`,
|
||||
site.icons?.apple && `<link rel="apple-touch-icon" href="${escapeHtml(site.icons.apple)}">`,
|
||||
meta.jsonLd && `<script type="application/ld+json">${scriptJson(meta.jsonLd)}</script>`,
|
||||
...(meta.preload ?? []).map((p) =>
|
||||
p.as === "fetch"
|
||||
? `<link rel="preload" href="${escapeHtml(p.href)}" as="fetch" crossorigin>`
|
||||
: `<link rel="preload" href="${escapeHtml(p.href)}" as="image" fetchpriority="high">`,
|
||||
),
|
||||
// Read by src/lib/site.ts before the app's module runs (a plain
|
||||
// script in the head runs during parsing; modules wait).
|
||||
`<script>window.__NGU_SITE__ = ${scriptJson(forBrowser(site))}</script>`,
|
||||
|
|
|
|||
|
|
@ -94,8 +94,8 @@ auth.post("/login", async (c) => {
|
|||
|
||||
const ok =
|
||||
user && user.is_active === 1
|
||||
? verifyPassword(password, user.password_hash)
|
||||
: (verifyPassword(password, DUMMY_HASH), false);
|
||||
? await verifyPassword(password, user.password_hash)
|
||||
: (await verifyPassword(password, DUMMY_HASH), false);
|
||||
|
||||
if (!ok) {
|
||||
loginFailures.fail(email);
|
||||
|
|
|
|||
|
|
@ -120,8 +120,12 @@ pages.get("*", (c, next) => {
|
|||
return c.html(html, 200, { "Cache-Control": "no-store" });
|
||||
}
|
||||
|
||||
// no-cache: a browser may keep the page but asks again each time.
|
||||
// HTML names the build's hashed /assets files, and after a deploy
|
||||
// those are gone, so a cached old page would load nothing. Pages
|
||||
// are rebuilt in well under a millisecond.
|
||||
return c.html(page, meta.status, {
|
||||
"Cache-Control": meta.status === 200 ? CACHE : "no-store",
|
||||
"Cache-Control": meta.status === 200 ? "no-cache" : "no-store",
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue