v3: a performance pass over both halves — indexed queries, streamed files, cached previews, and feeds that stop re-rendering on every tick — a review turned up whole-file reads, unindexed scans and render storms; each fix comes with a test. Database: migration 0016 adds the indexes the hot queries lacked — dumps by created_at, (user_id, created_at) and slug, votes by (user_id, created_at), playlists by slug, users by lower(username) for @mentions, and the child side of every cascading foreign key (comment replies, a user's comments, follows both ways, chat messages, invites, reset tokens); the feeds, dump and playlist pages, upvotes and follower fan-out all plan as index searches now, with no temp-table sort. SQLite runs in WAL with synchronous=NORMAL and a busy timeout, and a transaction() helper wraps the multi-row writes (a dump and its categories, category sets, backlinks, attachment links, playlist reorders, follower notifications) so they commit once instead of once a row. Lists no longer run a COUNT(*) per page: they fetch limit + 1 rows and hasMore comes from the extra one; total stays only on search, the one place it's shown. Files: /api/files read the whole upload (up to 50 MB) for every range request a player makes while seeking; api/lib/serve-file.ts streams the requested bytes from disk, with an ETag and 304s, and serves avatars, attachments, covers and thumbnails too. File and thumbnail URLs carry the file's version (size and last change), so the current one is cached for a year and anything else revalidates — a same-size replacement used to stay stale, and a video's still was cached immutable forever under a URL that never changed. Feeds showed image dumps at full size: /api/thumbnails now makes a 960px preview with ffmpeg (GIFs and unreadable images go out as they are), one run per output however many cards ask at once, and ffmpeg is probed once per process instead of spawned per request. Uploads stream to disk; replacing a file writes beside it and renames over, a hard link keeping the old one for rollback instead of holding both in memory; generated stills and previews go when the file is replaced or the dump deleted, and a custom thumbnail with its dump. Outbound: fetchWithTimeout's deadline now covers the body — a server that answered at once and then dripped could hold a create open indefinitely — and pages are read to 4 MB at most; metadata is cached five minutes so the create form's preview and the post that follows share one fetch (refresh-metadata still goes to the page); proxied images sit in a 32 MB LRU. Broadcasts serialize once rather than per socket, and index.html is kept in memory until the file changes. Frontend: currentTime lived in PlayerContext, so every card re-rendered — and re-parsed its Markdown — four times a second while anything played; the playhead has its own PlayerTimeContext now. The socket context is split three ways (feed, chat via useWSChat, presence via useWSPresence), so typing, presence and chat messages leave the feeds alone. DumpCard, JournalCard and Markdown are memoized; card images use the server preview and load lazily; the feed cache is written when the page is left rather than after every pause in scrolling; the theme context value is memoized.
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 49s
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 49s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
import { Router } from "@oak/oak";
|
||||
import { APIErrorCode, APIException } from "../model/interfaces.ts";
|
||||
import { getDump } from "../services/dump-service.ts";
|
||||
import { DUMPS_DIR } from "../lib/upload.ts";
|
||||
import { authenticateMedia } from "../lib/auth.ts";
|
||||
import { serveFile } from "../lib/serve-file.ts";
|
||||
import { dumpFileVersion, getDump } from "../services/dump-service.ts";
|
||||
|
||||
const router = new Router({ prefix: "/api/files" });
|
||||
|
||||
@@ -63,17 +64,7 @@ router.get("/:dumpId", async (ctx) => {
|
||||
}
|
||||
|
||||
const path = `${DUMPS_DIR}/${dumpId}`;
|
||||
|
||||
let data: Uint8Array;
|
||||
try {
|
||||
data = await Deno.readFile(path);
|
||||
} catch {
|
||||
throw new APIException(APIErrorCode.NOT_FOUND, 404, "File not found");
|
||||
}
|
||||
|
||||
const total = data.byteLength;
|
||||
const inline = isInlineSafe(dump.fileMime);
|
||||
ctx.response.headers.set("Content-Type", dump.fileMime);
|
||||
ctx.response.headers.set(
|
||||
"Content-Disposition",
|
||||
contentDisposition(inline ? "inline" : "attachment", dump.fileName),
|
||||
@@ -91,46 +82,23 @@ router.get("/:dumpId", async (ctx) => {
|
||||
// The URL may carry a media token; don't pass it on to wherever the file
|
||||
// links.
|
||||
ctx.response.headers.set("Referrer-Policy", "no-referrer");
|
||||
// A private dump's bytes must not sit in a shared cache.
|
||||
if (dump.isPrivate) ctx.response.headers.set("Cache-Control", "private");
|
||||
ctx.response.headers.set("Accept-Ranges", "bytes");
|
||||
|
||||
// Only a single byte range is served as one. Anything else — several
|
||||
// ranges, another unit — is a header RFC 9110 lets us ignore, so the whole
|
||||
// file goes out with a 200 rather than a 416 for ranges that were fine.
|
||||
const match = ctx.request.headers.get("Range")?.match(
|
||||
/^bytes=(\d*)-(\d*)$/,
|
||||
);
|
||||
|
||||
if (match) {
|
||||
// "bytes=a-b", "bytes=a-" (to the end) or "bytes=-n" (the last n bytes).
|
||||
let start: number;
|
||||
let end: number;
|
||||
if (match[1]) {
|
||||
start = parseInt(match[1], 10);
|
||||
end = match[2] ? Math.min(parseInt(match[2], 10), total - 1) : total - 1;
|
||||
} else {
|
||||
const suffix = parseInt(match[2], 10);
|
||||
start = Math.max(total - suffix, 0);
|
||||
end = total - 1;
|
||||
// "bytes=-" and "bytes=-0" name no bytes at all.
|
||||
if (!(suffix > 0)) start = total;
|
||||
}
|
||||
|
||||
if (start > end || start >= total) {
|
||||
ctx.response.status = 416;
|
||||
ctx.response.headers.set("Content-Range", `bytes */${total}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const chunk = data.subarray(start, end + 1);
|
||||
ctx.response.status = 206;
|
||||
ctx.response.headers.set("Content-Range", `bytes ${start}-${end}/${total}`);
|
||||
ctx.response.headers.set("Content-Length", String(chunk.byteLength));
|
||||
ctx.response.body = chunk;
|
||||
} else {
|
||||
ctx.response.headers.set("Content-Length", String(total));
|
||||
ctx.response.body = data;
|
||||
// The app's URLs carry the file's version (see dumpFileVersion), so one
|
||||
// naming the current version never changes and is cached for good; any
|
||||
// other URL is revalidated against the ETag. A private dump's bytes must not
|
||||
// sit in a shared cache.
|
||||
const scope = dump.isPrivate ? "private" : "public";
|
||||
const current = ctx.request.url.searchParams.get("v") ===
|
||||
dumpFileVersion(dump);
|
||||
const served = await serveFile(ctx, path, {
|
||||
mime: dump.fileMime,
|
||||
cacheControl: current
|
||||
? `${scope}, max-age=31536000, immutable`
|
||||
: `${scope}, no-cache`,
|
||||
ranges: true,
|
||||
});
|
||||
if (!served) {
|
||||
throw new APIException(APIErrorCode.NOT_FOUND, 404, "File not found");
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user