Files
Psychotoxical-psysonic/src/cover/diskSrcCache.ts
T
cucadmuh 9925771a86 feat(browse,cover,perf): lazy catalogs, cover pipeline, and Performance Probe (#890)
* fix(cover): per-server cache stats and cover pipeline perf probe

Stop count_cached_cover_ids from borrowing sibling bucket counts so
Settings progress no longer attributes one server's disk cache to another.

Add cover pipeline queue stats (ui ensure queue, ui vs lib HTTP/WebP
semaphores) to Performance Probe overlay, with clearer ui/lib labels.

* fix(browse): stabilize in-page infinite scroll and cap cover memory caches

Extract useInpageScrollSentinel for album grids and song lists so sentinel
reconnects do not spam loadMore during scroll. Harden useAlbumBrowseData with
sync loading refs, tighter root margin, and hasMore termination when dedupe
adds nothing. Pause middle-priority cover work during SQL pagination and bound
diskSrc/resolve/ensure tail maps on long cold-cache sessions.

* refactor(browse): unify in-page infinite scroll hooks and sentinel UI

Extract shared transport (viewport ref, async pagination guards, client slice)
and InpageScrollSentinel so Albums, New Releases, Artists, and song lists
use one pagination pattern instead of duplicated IntersectionObserver wiring.

* fix(browse): prioritize album SQL pagination over cover ensures

Pause the entire webview ensure pump during grid page fetches, resume after
SQL settles, add cover-queue backpressure before load-more, and re-probe the
sentinel when pagination finishes so cold-cache scroll does not stall.

* fix(browse): unblock covers, SQL spawn_blocking, and pagination retry

Pair grid-pagination hold begin/end on stale fetches, resume the ensure pump
after SQL, retry load-more when the cover backlog drains while the sentinel
stays visible, and run album browse SQL on spawn_blocking so Tokio stays
responsive during library_advanced_search.

* feat(browse): All Albums client-slice scroll on local index (Artists-style)

Load the filtered catalog once from SQLite when the library index is ready,
then grow the visible grid with useClientSliceInfiniteScroll instead of
offset SQL pagination per scroll. Network-only servers keep page mode.

* fix(browse): lazy local catalog chunks instead of full 50k SQL fetch

All Albums slice mode now loads 200 albums first, shows the grid immediately,
then appends catalog chunks in the background as the user scrolls. Avoids the
blocking library_advanced_search that hung the app on large libraries.

* fix(browse): keep album covers loading during active grid scroll

Pass high ensure priority and the in-page scroll root to AlbumCard on All
Albums, stop pausing cover traffic for background catalog chunks, and never
trim high-priority ensure jobs from the queue during scroll bursts.

* fix(cover): viewport priority tiers and unstick ensure invoke pump

All Albums uses IO-driven high/middle instead of blanket high; release
only on unmount so scroll-ahead jobs are not dropped on reprioritize.
Ensure queue shares one Rust flight per cover id, attaches duplicate
waiters without consuming invoke slots, and times out wedged calls.
Warm the first viewport slice on large grids; acquire CPU permits before
spawn_blocking in cover_cache to avoid blocking-thread deadlocks.

* fix(cover): wire in-page scroll root on New Releases and Lossless grids

AlbumCard IO uses the same viewport id as VirtualCardGrid so cover
ensure priority tracks visible in-page rows like All Albums.

* fix(browse): lazy local artist catalog in 200-row chunks

Replace runLocalBrowseAllArtists bulk fetch with paginated local-index
chunks so large libraries do not hang on open; preserve text search,
starred, letter filter, and client-slice scroll behavior.

* feat(perf): add RSS and thread CPU groups to Performance Probe

Extend performance_cpu_snapshot with process RSS (psysonic + WebKit
children) and in-process thread CPU breakdown. Classify tokio-rt-worker
and tokio-* workers separately from glib, audio/pipewire, reqwest, and
other misc threads (Linux /proc only).

* feat(perf): redesign Performance Probe with tabs, pins, and overlay layout

Split the probe into Monitor (live metric cards, per-metric overlay pins,
corner and opacity controls) and Toggles (diagnostic tree). Share live
polling via perfLiveStore; label analysis/cover pipeline blocks in the HUD.

* feat(perf): overlay sparklines, macOS CPU/memory, and sync fixes

Add 1-minute pinned-metric sparklines with right-aligned growth and a shared
poll clock. Enable macOS performance snapshots via sysinfo. Fix overlay infinite
loop from unstable history snapshots, bar/sparkline tick jitter, and probe bar
rescale flicker.

* docs: CHANGELOG and credits for PR #890

* perf(probe): scoped CPU poll, adjustable interval, lazy thread groups

Read only psysonic + WebKit children instead of the full process table;
macOS uses sysctl host CPU and refreshes cached child PIDs. Add 0.5–10s
poll slider (default 2s). Collect /proc thread groups only when the
Monitor section is open or a thread metric is pinned.

* feat(perf): three-way overlay mode switch (off / FPS / pinned)

Add Monitor control for overlay visibility: hidden, FPS-only, or pinned
metrics from Monitor. Live CPU poll runs only in pinned mode with live pins.
2026-05-29 04:40:31 +03:00

173 lines
5.4 KiB
TypeScript

import { convertFileSrc, isTauri } from '@tauri-apps/api/core';
import { coverIndexKeyFromScope } from './storageKeys';
import type { CoverServerScope } from './types';
/** Stable asset URLs for disk `.webp` tiers — survives route unmount. */
const diskSrcByStorageKey = new Map<string, string>();
/** Bound webview memory when scrolling large grids with a cold cover cache. */
const MAX_DISK_SRC_CACHE_ENTRIES = 4096;
let cacheGeneration = 0;
const cacheListeners = new Set<() => void>();
function bumpDiskSrcCache(): void {
cacheGeneration += 1;
for (const fn of cacheListeners) {
try {
fn();
} catch {
/* ignore */
}
}
}
/** Re-render `useCoverArt` when warm/peek seeds this map (no wait for ensure queue). */
export function subscribeDiskSrcCache(onStoreChange: () => void): () => void {
cacheListeners.add(onStoreChange);
return () => cacheListeners.delete(onStoreChange);
}
export function getDiskSrcCacheGeneration(): number {
return cacheGeneration;
}
function isAssetProtocolUrl(url: string): boolean {
return url.startsWith('asset:') || /^https?:\/\/asset\.localhost/i.test(url);
}
/** Windows: forward slashes before `convertFileSrc` (tauri#7970). */
function normalizePathForConvert(fsPath: string): string {
if (/^[a-zA-Z]:[\\/]/.test(fsPath)) {
return fsPath.replace(/\\/g, '/');
}
return fsPath;
}
/** True when `convertFileSrc` failed and returned the filesystem path unchanged. */
function isRawFsPath(url: string, fsPath: string): boolean {
if (url === fsPath) return true;
if (url.startsWith('/') && fsPath.startsWith('/')) return true;
if (/^[a-zA-Z]:[\\/]/.test(fsPath)) {
const norm = fsPath.replace(/\\/g, '/');
const urlNorm = url.replace(/\\/g, '/');
// `endsWith(norm)`: convertFileSrc passthrough; `norm.endsWith(urlNorm)`: partial URL match.
if (urlNorm === norm || urlNorm.endsWith(norm) || norm.endsWith(urlNorm)) {
return !isAssetProtocolUrl(url);
}
}
return false;
}
/**
* Turn a Rust disk path into a webview-loadable URL.
* Returns empty when not in Tauri or path is outside asset scope (never put raw paths in `<img src>`).
*/
function tryCoverDiskUrl(fsPath: string): string {
const paths = fsPath.includes('\\')
? [normalizePathForConvert(fsPath), fsPath]
: [fsPath, normalizePathForConvert(fsPath)];
const seen = new Set<string>();
for (const p of paths) {
if (!p || seen.has(p)) continue;
seen.add(p);
const src = convertFileSrc(p);
if (!src || isRawFsPath(src, p) || isRawFsPath(src, fsPath)) continue;
return src;
}
return '';
}
export function coverDiskUrl(fsPath: string): string {
if (!fsPath || !isTauri()) return '';
const src = tryCoverDiskUrl(fsPath);
if (!src && import.meta.env.DEV) {
console.warn('[cover] convertFileSrc out of asset scope — check tauri.conf assetProtocol', {
fsPath,
src: convertFileSrc(normalizePathForConvert(fsPath)),
});
}
return src;
}
export function rememberDiskSrc(storageKey: string, fsPath: string): string {
if (!storageKey || !fsPath) return '';
const src = coverDiskUrl(fsPath);
if (!src) return '';
const prev = diskSrcByStorageKey.get(storageKey);
if (prev === src) return src;
if (diskSrcByStorageKey.size >= MAX_DISK_SRC_CACHE_ENTRIES) {
const oldest = diskSrcByStorageKey.keys().next().value;
if (oldest !== undefined) diskSrcByStorageKey.delete(oldest);
}
diskSrcByStorageKey.set(storageKey, src);
bumpDiskSrcCache();
return src;
}
export function getDiskSrc(storageKey: string): string {
const src = diskSrcByStorageKey.get(storageKey) ?? '';
if (src && diskSrcByStorageKey.has(storageKey)) {
diskSrcByStorageKey.delete(storageKey);
diskSrcByStorageKey.set(storageKey, src);
}
return src;
}
export function forgetDiskSrc(storageKey: string): void {
if (diskSrcByStorageKey.delete(storageKey)) bumpDiskSrcCache();
}
export function forgetDiskSrcPrefix(ref: {
serverScope: CoverServerScope;
cacheKind: string;
cacheEntityId: string;
}): void {
const serverIndexKey = coverIndexKeyFromScope(ref.serverScope);
const prefix = `${serverIndexKey}:cover:${ref.cacheKind}:${ref.cacheEntityId}:`;
let changed = false;
for (const key of diskSrcByStorageKey.keys()) {
if (key.startsWith(prefix)) {
diskSrcByStorageKey.delete(key);
changed = true;
}
}
if (changed) bumpDiskSrcCache();
}
/**
* Drop every cached disk-src under a server index key (all cover ids, all
* tiers). Used by the URL-change remigration `cover:bucket-renamed` listener
* so entries pointing at the now-renamed `{root}/{oldKey}/…` path stop
* serving stale URLs.
*/
export function forgetDiskSrcForServer(serverIndexKey: string): void {
if (!serverIndexKey) return;
const prefix = `${serverIndexKey}:cover:`;
let changed = false;
for (const key of diskSrcByStorageKey.keys()) {
if (key.startsWith(prefix)) {
diskSrcByStorageKey.delete(key);
changed = true;
}
}
if (changed) bumpDiskSrcCache();
}
export function clearAllDiskSrcCache(): void {
if (diskSrcByStorageKey.size === 0) return;
diskSrcByStorageKey.clear();
bumpDiskSrcCache();
}
export function clearDiskSrcCacheForServer(serverIndexKey: string): void {
const prefix = `${serverIndexKey}:cover:`;
let changed = false;
for (const key of [...diskSrcByStorageKey.keys()]) {
if (key.startsWith(prefix)) {
diskSrcByStorageKey.delete(key);
changed = true;
}
}
if (changed) bumpDiskSrcCache();
}