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

@@ -68,8 +68,6 @@ export interface PlayerContextValue {
// Playback state — readable by any consumer
current: PlayerItem | null;
playing: boolean;
currentTime: number;
duration: number;
// Queue. Every playback is a queue of at least one item, so single tracks and
// albums share one code path. `current` is always `queue[queueIndex]`.
@@ -115,8 +113,6 @@ export interface PlayerContextValue {
export const defaultPlayerValue: PlayerContextValue = {
current: null,
playing: false,
currentTime: 0,
duration: 0,
queue: [],
queueIndex: 0,
hasNext: false,
@@ -143,3 +139,22 @@ export const defaultPlayerValue: PlayerContextValue = {
export const PlayerContext = createContext<PlayerContextValue>(
defaultPlayerValue,
);
/**
* The playhead, apart from the rest: it moves several times a second while
* something plays, and only what draws a position should re-render with it —
* not every card that reads `current` or `playing`.
*/
export interface PlayerTimeValue {
currentTime: number;
duration: number;
}
export const defaultPlayerTimeValue: PlayerTimeValue = {
currentTime: 0,
duration: 0,
};
export const PlayerTimeContext = createContext<PlayerTimeValue>(
defaultPlayerTimeValue,
);

View File

@@ -3,6 +3,7 @@ import {
PlayerContext,
type PlayerItem,
playerItemKey,
PlayerTimeContext,
} from "./PlayerContext.ts";
import { isStreamStale, resolveStreamQueue } from "../utils/streamSources.ts";
import { useAuth } from "../hooks/useAuth.ts";
@@ -392,8 +393,6 @@ export function PlayerProvider({ children }: { children: React.ReactNode }) {
const value = useMemo(() => ({
current,
playing,
currentTime,
duration,
queue,
queueIndex,
hasNext,
@@ -418,8 +417,6 @@ export function PlayerProvider({ children }: { children: React.ReactNode }) {
}), [
current,
playing,
currentTime,
duration,
queue,
queueIndex,
hasNext,
@@ -441,9 +438,16 @@ export function PlayerProvider({ children }: { children: React.ReactNode }) {
onError,
]);
const timeValue = useMemo(
() => ({ currentTime, duration }),
[currentTime, duration],
);
return (
<PlayerContext.Provider value={value}>
{children}
<PlayerTimeContext.Provider value={timeValue}>
{children}
</PlayerTimeContext.Provider>
</PlayerContext.Provider>
);
}

View File

@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import {
type ColorScheme,
type StyleName,
@@ -37,15 +37,15 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
localStorage.setItem("color-scheme", colorScheme);
}, [colorScheme]);
const value = useMemo(() => ({
style,
colorScheme,
setStyle: setStyleState,
setColorScheme: setColorSchemeState,
}), [style, colorScheme]);
return (
<ThemeContext.Provider
value={{
style,
colorScheme,
setStyle: setStyleState,
setColorScheme: setColorSchemeState,
}}
>
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
);

View File

@@ -65,10 +65,15 @@ export interface ChatError {
message: string;
}
/**
* The socket's state, split three ways by how often each part changes, so a
* consumer re-renders only with what it reads: typing and presence update
* every few seconds while people are around, chat with every message, and a
* feed has no use for either.
*/
export interface WSContextValue {
wsStatus: "connecting" | "connected" | "disconnected";
wsErrorMessage: string | null;
onlineUsers: OnlineUser[];
voteCounts: Record<string, number>;
myVotes: Set<string>;
likeCounts: Record<string, number>;
@@ -84,6 +89,19 @@ export interface WSContextValue {
lastUserEvent: UserEvent | null;
unreadNotificationCount: number;
lastNotification: Notification | null;
/** Increments on each WS reconnect so pages can backfill missed events. */
connectionEpoch: number;
/** `shownCount`: the count on screen, used until a live one arrives. */
castVote: (dumpId: string, shownCount?: number) => void;
removeVote: (dumpId: string, shownCount?: number) => void;
castCommentLike: (commentId: string, shownCount?: number) => void;
removeCommentLike: (commentId: string, shownCount?: number) => void;
injectDump: (dump: Dump) => void;
clearUnreadNotifications: () => void;
}
/** The chat room: its live stream, unread state and what to send into it. */
export interface WSChatContextValue {
/** Live buffer of chat messages received this session (capped). */
chatMessages: ChatMessage[];
/** Ids of chat messages deleted live this session, so fetched history can
@@ -100,15 +118,6 @@ export interface WSContextValue {
/** Users currently composing a chat message (excludes nobody — the chatbox
* filters out the current user itself). Shaped like presence for avatars. */
typingUsers: OnlineUser[];
/** Increments on each WS reconnect so pages can backfill missed events. */
connectionEpoch: number;
/** `shownCount`: the count on screen, used until a live one arrives. */
castVote: (dumpId: string, shownCount?: number) => void;
removeVote: (dumpId: string, shownCount?: number) => void;
castCommentLike: (commentId: string, shownCount?: number) => void;
removeCommentLike: (commentId: string, shownCount?: number) => void;
injectDump: (dump: Dump) => void;
clearUnreadNotifications: () => void;
sendChatMessage: (body: string, replyTo?: ChatReplyTarget) => void;
retryChatMessage: (nonce: string) => void;
discardChatMessage: (nonce: string) => void;
@@ -129,11 +138,15 @@ export interface WSContextValue {
setChatOpen: (open: boolean) => void;
}
/** Who's connected. */
export interface WSPresenceContextValue {
onlineUsers: OnlineUser[];
}
/** What a consumer outside any provider gets. */
export const defaultWSValue: WSContextValue = {
wsStatus: "connecting",
wsErrorMessage: null,
onlineUsers: [],
voteCounts: {},
myVotes: new Set(),
likeCounts: {},
@@ -149,13 +162,6 @@ export const defaultWSValue: WSContextValue = {
lastUserEvent: null,
unreadNotificationCount: 0,
lastNotification: null,
chatMessages: [],
deletedChatIds: new Set(),
unreadChatCount: 0,
chatReadAt: null,
pendingChatMessages: [],
chatError: null,
typingUsers: [],
connectionEpoch: 0,
castVote: () => {},
removeVote: () => {},
@@ -163,6 +169,16 @@ export const defaultWSValue: WSContextValue = {
removeCommentLike: () => {},
injectDump: () => {},
clearUnreadNotifications: () => {},
};
export const defaultWSChatValue: WSChatContextValue = {
chatMessages: [],
deletedChatIds: new Set(),
unreadChatCount: 0,
chatReadAt: null,
pendingChatMessages: [],
chatError: null,
typingUsers: [],
sendChatMessage: () => {},
retryChatMessage: () => {},
discardChatMessage: () => {},
@@ -175,4 +191,14 @@ export const defaultWSValue: WSContextValue = {
setChatOpen: () => {},
};
export const defaultWSPresenceValue: WSPresenceContextValue = {
onlineUsers: [],
};
export const WSContext = createContext<WSContextValue>(defaultWSValue);
export const WSChatContext = createContext<WSChatContextValue>(
defaultWSChatValue,
);
export const WSPresenceContext = createContext<WSPresenceContextValue>(
defaultWSPresenceValue,
);

View File

@@ -16,8 +16,12 @@ import {
type PlaylistEvent,
type UserEvent,
type VoteEvent,
WSChatContext,
type WSChatContextValue,
WSContext,
type WSContextValue,
WSPresenceContext,
type WSPresenceContextValue,
} from "./WSContext.ts";
import {
type AvatarOverride,
@@ -1130,7 +1134,6 @@ export function WSProvider({ children }: WSProviderProps) {
const value: WSContextValue = useMemo(() => ({
wsStatus,
wsErrorMessage,
onlineUsers,
voteCounts,
myVotes,
likeCounts,
@@ -1146,13 +1149,6 @@ export function WSProvider({ children }: WSProviderProps) {
lastUserEvent,
unreadNotificationCount,
lastNotification,
chatMessages,
deletedChatIds,
unreadChatCount,
chatReadAt,
pendingChatMessages,
chatError,
typingUsers,
connectionEpoch,
castVote,
removeVote,
@@ -1160,6 +1156,41 @@ export function WSProvider({ children }: WSProviderProps) {
removeCommentLike,
injectDump,
clearUnreadNotifications,
}), [
wsStatus,
wsErrorMessage,
voteCounts,
myVotes,
likeCounts,
myLikes,
recentDumps,
deletedDumpIds,
lastVoteEvent,
lastLikeEvent,
lastDumpEvent,
lastPlaylistEvent,
deletedPlaylistIds,
lastCommentEvent,
lastUserEvent,
unreadNotificationCount,
lastNotification,
connectionEpoch,
castVote,
removeVote,
castCommentLike,
removeCommentLike,
injectDump,
clearUnreadNotifications,
]);
const chatValue: WSChatContextValue = useMemo(() => ({
chatMessages,
deletedChatIds,
unreadChatCount,
chatReadAt,
pendingChatMessages,
chatError,
typingUsers,
sendChatMessage,
retryChatMessage,
discardChatMessage,
@@ -1171,24 +1202,6 @@ export function WSProvider({ children }: WSProviderProps) {
setChatTyping,
setChatOpen,
}), [
wsStatus,
wsErrorMessage,
onlineUsers,
voteCounts,
myVotes,
likeCounts,
myLikes,
recentDumps,
deletedDumpIds,
lastVoteEvent,
lastLikeEvent,
lastDumpEvent,
lastPlaylistEvent,
deletedPlaylistIds,
lastCommentEvent,
lastUserEvent,
unreadNotificationCount,
lastNotification,
chatMessages,
deletedChatIds,
unreadChatCount,
@@ -1196,13 +1209,6 @@ export function WSProvider({ children }: WSProviderProps) {
pendingChatMessages,
chatError,
typingUsers,
connectionEpoch,
castVote,
removeVote,
castCommentLike,
removeCommentLike,
injectDump,
clearUnreadNotifications,
sendChatMessage,
retryChatMessage,
discardChatMessage,
@@ -1215,11 +1221,20 @@ export function WSProvider({ children }: WSProviderProps) {
setChatOpen,
]);
const presenceValue: WSPresenceContextValue = useMemo(
() => ({ onlineUsers }),
[onlineUsers],
);
return (
<WSContext.Provider value={value}>
<AvatarOverrideContext.Provider value={avatarOverrides}>
{children}
</AvatarOverrideContext.Provider>
<WSChatContext.Provider value={chatValue}>
<WSPresenceContext.Provider value={presenceValue}>
<AvatarOverrideContext.Provider value={avatarOverrides}>
{children}
</AvatarOverrideContext.Provider>
</WSPresenceContext.Provider>
</WSChatContext.Provider>
</WSContext.Provider>
);
}