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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-09-27 16:35:51 +00:00
parent 364c498a24
commit de5abeceb2
74 changed files with 1795 additions and 792 deletions

View File

@@ -42,6 +42,8 @@ export function Avatar(
title={username}
style={sizeStyle}
className="avatar-img"
loading="lazy"
decoding="async"
onError={() => setImgFailed(true)}
/>
);

View File

@@ -1,10 +1,10 @@
import { t } from "@lingui/core/macro";
import { useWS } from "../hooks/useWS.ts";
import { useWSChat } from "../hooks/useWS.ts";
import { useChat } from "../hooks/useChat.ts";
/** Header chat button with an unread-message badge. Opens the app-wide chat. */
export function ChatButton() {
const { unreadChatCount } = useWS();
const { unreadChatCount } = useWSChat();
const { openChat } = useChat();
return (

View File

@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
import { useLocation } from "react-router";
import { t } from "@lingui/core/macro";
import { useAuth } from "../hooks/useAuth.ts";
import { useWS } from "../hooks/useWS.ts";
import { useWSChat } from "../hooks/useWS.ts";
import { useChat } from "../hooks/useChat.ts";
/**
@@ -12,7 +12,7 @@ import { useChat } from "../hooks/useChat.ts";
*/
export function ChatFab() {
const { user } = useAuth();
const { unreadChatCount } = useWS();
const { unreadChatCount } = useWSChat();
const { openChat } = useChat();
const location = useLocation();
const [headerHidden, setHeaderHidden] = useState(false);

View File

@@ -17,7 +17,7 @@ import { Avatar } from "./Avatar.tsx";
import { ConfirmModal } from "./ConfirmModal.tsx";
import { Tooltip } from "./Tooltip.tsx";
import { useHeightTransition } from "../hooks/useHeightTransition.ts";
import { useWS } from "../hooks/useWS.ts";
import { useWS, useWSChat } from "../hooks/useWS.ts";
import { useAuth } from "../hooks/useAuth.ts";
import { can } from "../utils/permissions.ts";
import { relativeTime } from "../utils/relativeTime.ts";
@@ -553,8 +553,8 @@ type Row =
};
export function ChatModal({ onClose }: { onClose: () => void }) {
const { wsStatus, connectionEpoch } = useWS();
const {
wsStatus,
chatMessages,
deletedChatIds,
pendingChatMessages,
@@ -571,8 +571,7 @@ export function ChatModal({ onClose }: { onClose: () => void }) {
reconcileChat,
setChatTyping,
setChatOpen,
connectionEpoch,
} = useWS();
} = useWSChat();
const { authFetch, user } = useAuth();
const canModerate = can(user, "chat:moderate");
const userId = user?.id;

View File

@@ -1,3 +1,4 @@
import { memo } from "react";
import { Link } from "react-router";
import { Plural, Trans } from "@lingui/react/macro";
import type { Dump } from "../model.ts";
@@ -25,7 +26,9 @@ interface DumpCardProps {
isOwner?: boolean;
}
export function DumpCard(
// Memoized: a feed re-renders on every live event (a vote anywhere, a new
// dump), and a card whose props haven't changed has nothing to redraw.
export const DumpCard = memo(function DumpCard(
{ dump, voteCount, voted, canVote, castVote, removeVote, className, isOwner }:
DumpCardProps,
) {
@@ -139,4 +142,4 @@ export function DumpCard(
</div>
</li>
);
}
});

View File

@@ -4,7 +4,11 @@ import { formatBytes } from "../utils/format.ts";
import { dumpFileUrl, dumpThumbnailUrl, dumpUrl } from "../utils/urls.ts";
import { useAuth } from "../hooks/useAuth.ts";
import { IconPause, IconPlay, MediaPlayer } from "./MediaPlayer.tsx";
import { PlayerContext, type PlayerItem } from "../contexts/PlayerContext.ts";
import {
PlayerContext,
type PlayerItem,
PlayerTimeContext,
} from "../contexts/PlayerContext.ts";
import {
BAR_GAP,
BAR_W,
@@ -50,13 +54,15 @@ function filePlayerItem(
}
// Waveform preview for the dump detail page — routes to global player,
// reflects live play state and position from PlayerContext.
// reflects live play state and position from PlayerContext/PlayerTimeContext.
function AudioFilePreview(
{ fileUrl, mime, dump }: { fileUrl: string; mime: string; dump: Dump },
) {
const { mediaToken: token } = useAuth();
const { current, playing, currentTime, duration, play, togglePlay, seekTo } =
useContext(PlayerContext);
const { current, playing, play, togglePlay, seekTo } = useContext(
PlayerContext,
);
const { currentTime, duration } = useContext(PlayerTimeContext);
const [peaks, setPeaks] = useState<Float32Array | null>(null);
const isActive = current?.kind === "file" && current.fileUrl === fileUrl;
const progress = isActive && duration > 0 ? currentTime / duration : 0;
@@ -159,6 +165,8 @@ function VideoThumb({ src, fallback }: { src: string; fallback: string }) {
src={src}
alt=""
className="rich-content-compact-thumbnail"
loading="lazy"
decoding="async"
onError={() => setFailed(true)}
/>
);
@@ -186,11 +194,15 @@ export default function FilePreview(
if (compact) {
if (mime.startsWith("image/")) {
// The server's preview (or the custom thumbnail): a card doesn't need
// the full upload.
return (
<img
src={thumbOverride ?? fileUrl}
src={dumpThumbnailUrl(dump, token)}
alt={dump.fileName}
className="rich-content-compact-thumbnail"
loading="lazy"
decoding="async"
onError={(e) => {
(e.target as HTMLImageElement).style.display = "none";
}}

View File

@@ -1,8 +1,9 @@
import { memo } from "react";
import { Link } from "react-router";
import { Plural, Trans } from "@lingui/react/macro";
import type { Dump } from "../model.ts";
import { relativeTime } from "../utils/relativeTime.ts";
import { dumpFileUrl, dumpThumbnailUrl, dumpUrl } from "../utils/urls.ts";
import { dumpThumbnailUrl, dumpUrl } from "../utils/urls.ts";
import { useAuth } from "../hooks/useAuth.ts";
import { useDumpCardLink } from "../hooks/useDumpCardLink.ts";
import { isDumpVisited, isRecent, markDumpVisited } from "../utils/visited.ts";
@@ -33,7 +34,8 @@ interface JournalCardProps {
isOwner?: boolean;
}
export function JournalCard(
// Memoized, like DumpCard: live events re-render the feed, not every card.
export const JournalCard = memo(function JournalCard(
{ dump, shape, voteCount, voted, canVote, castVote, removeVote, isOwner }:
JournalCardProps,
) {
@@ -51,13 +53,13 @@ export function JournalCard(
}
// Mirrors FilePreview (the hot/new feeds) so a video shows its generated
// still here too, rather than degrading to a text card with a 🎬.
// still here too, rather than degrading to a text card with a 🎬. An image
// shows the server's scaled-down preview, not the full upload.
const thumbnailUrl = dump.thumbnailMime
? dumpThumbnailUrl(dump, mediaToken)
: dump.kind === "file"
? (dump.fileMime?.startsWith("image/")
? dumpFileUrl(dump, mediaToken)
: dump.fileMime?.startsWith("video/")
? (dump.fileMime?.startsWith("image/") ||
dump.fileMime?.startsWith("video/")
? dumpThumbnailUrl(dump, mediaToken)
: null)
: (dump.richContent?.thumbnailUrl ?? null);
@@ -224,4 +226,4 @@ export function JournalCard(
{footer}
</li>
);
}
});

View File

@@ -1,3 +1,4 @@
import { memo } from "react";
import { Link } from "react-router";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
@@ -135,7 +136,9 @@ const INLINE_MARKDOWN_COMPONENTS: Components = {
img: () => null,
};
export function Markdown(
// Memoized: parsing runs the whole remark pipeline, and the text rarely
// changes when the component around it re-renders.
export const Markdown = memo(function Markdown(
{ children, className, inline = false }: MarkdownProps,
) {
return (
@@ -152,4 +155,4 @@ export function Markdown(
</ReactMarkdown>
</div>
);
}
});

View File

@@ -42,6 +42,8 @@ export function PlaylistCard(
src={playlistImageUrl(playlist)}
alt=""
className="playlist-card-img"
loading="lazy"
decoding="async"
/>
)
: <span className="playlist-card-icon">📋</span>}

View File

@@ -2,7 +2,7 @@ import { useState } from "react";
import { Link } from "react-router";
import { t } from "@lingui/core/macro";
import { Avatar } from "./Avatar.tsx";
import { useWS } from "../hooks/useWS.ts";
import { useWSPresence } from "../hooks/useWS.ts";
import { useRoomBeside } from "../hooks/useRoomBeside.ts";
// Past this many, the row ends in a "+N" counter rather than growing, so a
@@ -24,7 +24,7 @@ const SEAT_STEP = 22;
export function PresenceRow(
{ fitWithin, fitBeside }: { fitWithin?: string; fitBeside?: string },
) {
const { onlineUsers } = useWS();
const { onlineUsers } = useWSPresence();
const [el, setEl] = useState<HTMLDivElement | null>(null);
const room = useRoomBeside(el, { within: fitWithin, beside: fitBeside });

View File

@@ -64,6 +64,7 @@ export default function Thumbnail(
alt={alt}
className={className}
loading={loading}
decoding="async"
referrerPolicy="no-referrer"
onError={() =>
setAttempt(