perf(library): fix N+1 query and reduce logging overhead
Backend performance improvements for large libraries: - Change per-album INFO logging to DEBUG level (was logging every album during deserialization, causing 10k+ log lines) - Add get_albums_with_full_filter() method that filters network folders directly in SQL instead of N+1 query pattern - Replace library_get_albums N+1 loop with single SQL query (was doing 1 + N queries for N albums when excluding network folders) Frontend infrastructure: - Add libraryPerformanceStore.ts with feature flags for: - virtualizationEnabled (default: true) - thumbnailsEnabled (default: false, for future use) - optimizedNetworkFilter (default: true) - albumSearchDebounceMs (default: 150) - performanceModeThreshold (default: 500 albums) - forcePerformanceMode (default: false) Part of #13 - LocalLibrary performance optimization
This commit is contained in:
1 parent
4c4b35bce9
commit
befe93e619
3 files changed
+214
-39
No files matched your search
@@ -796,42 +796,15 @@ pub async fn library_get_albums(
|
||||
.unwrap_or(false);
|
||||
|
||||
let db = state.db.lock().await;
|
||||
let mut albums = db.get_albums_with_filter(include_hidden.unwrap_or(false), include_qobuz)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// Filter out albums from network folders when in offline mode
|
||||
if exclude_network_folders.unwrap_or(false) {
|
||||
let network_folders = db.get_network_folder_paths()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if !network_folders.is_empty() {
|
||||
log::info!("Filtering out albums from {} network folders", network_folders.len());
|
||||
|
||||
// Filter albums whose tracks are from network folders
|
||||
albums.retain(|album| {
|
||||
// Get first track's file path to determine if album is on network
|
||||
if let Ok(tracks) = db.get_album_tracks(&album.id) {
|
||||
if let Some(first_track) = tracks.first() {
|
||||
// Check if track's file_path starts with any network folder path
|
||||
let is_network = network_folders.iter().any(|folder_path| {
|
||||
first_track.file_path.starts_with(folder_path)
|
||||
});
|
||||
|
||||
if is_network {
|
||||
log::debug!("Excluding network album: {} - {}", album.artist, album.title);
|
||||
}
|
||||
|
||||
return !is_network;
|
||||
}
|
||||
}
|
||||
// If we can't determine, keep it
|
||||
true
|
||||
});
|
||||
|
||||
log::info!("Filtered to {} albums after excluding network folders", albums.len());
|
||||
}
|
||||
}
|
||||
// Use optimized SQL-based filtering instead of N+1 query pattern
|
||||
let albums = db.get_albums_with_full_filter(
|
||||
include_hidden.unwrap_or(false),
|
||||
include_qobuz,
|
||||
exclude_network_folders.unwrap_or(false),
|
||||
).map_err(|e| e.to_string())?;
|
||||
|
||||
log::info!("Returning {} albums", albums.len());
|
||||
Ok(albums)
|
||||
}
|
||||
|
||||
|
||||
@@ -831,6 +831,17 @@ impl LibraryDatabase {
|
||||
&self,
|
||||
include_hidden: bool,
|
||||
include_qobuz_downloads: bool,
|
||||
) -> Result<Vec<LocalAlbum>, LibraryError> {
|
||||
self.get_albums_with_full_filter(include_hidden, include_qobuz_downloads, false)
|
||||
}
|
||||
|
||||
/// Get all albums with full filter options including network folder exclusion
|
||||
/// This method filters network folders directly in SQL to avoid N+1 query patterns
|
||||
pub fn get_albums_with_full_filter(
|
||||
&self,
|
||||
include_hidden: bool,
|
||||
include_qobuz_downloads: bool,
|
||||
exclude_network_folders: bool,
|
||||
) -> Result<Vec<LocalAlbum>, LibraryError> {
|
||||
let source_filter = if include_qobuz_downloads {
|
||||
""
|
||||
@@ -838,6 +849,17 @@ impl LibraryDatabase {
|
||||
"AND (source IS NULL OR source != 'qobuz_download')"
|
||||
};
|
||||
|
||||
// Network folder filter: exclude tracks whose file_path starts with any network folder path
|
||||
let network_filter = if exclude_network_folders {
|
||||
"AND NOT EXISTS (
|
||||
SELECT 1 FROM library_folders nf
|
||||
WHERE nf.is_network = 1
|
||||
AND local_tracks.file_path LIKE nf.path || '%'
|
||||
)"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
|
||||
let query = if include_hidden {
|
||||
format!(
|
||||
r#"
|
||||
@@ -870,12 +892,12 @@ impl LibraryDatabase {
|
||||
bit_depth,
|
||||
sample_rate
|
||||
FROM local_tracks
|
||||
WHERE 1=1 {}
|
||||
WHERE 1=1 {} {}
|
||||
)
|
||||
GROUP BY group_key
|
||||
ORDER BY artist, title
|
||||
"#,
|
||||
source_filter
|
||||
source_filter, network_filter
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
@@ -909,7 +931,7 @@ impl LibraryDatabase {
|
||||
bit_depth,
|
||||
sample_rate
|
||||
FROM local_tracks
|
||||
WHERE 1=1 {}
|
||||
WHERE 1=1 {} {}
|
||||
)
|
||||
WHERE group_key NOT IN (
|
||||
SELECT album_group_key FROM album_settings WHERE hidden = 1
|
||||
@@ -917,7 +939,7 @@ impl LibraryDatabase {
|
||||
GROUP BY group_key
|
||||
ORDER BY artist, title
|
||||
"#,
|
||||
source_filter
|
||||
source_filter, network_filter
|
||||
)
|
||||
};
|
||||
|
||||
@@ -933,7 +955,7 @@ impl LibraryDatabase {
|
||||
let artist: String = row.get(2)?;
|
||||
let artwork_path: Option<String> = row.get(5)?;
|
||||
|
||||
log::info!("Album {} by {}: artwork_path = {:?}", album, artist, artwork_path);
|
||||
log::debug!("Album {} by {}: artwork_path = {:?}", album, artist, artwork_path);
|
||||
|
||||
Ok(LocalAlbum {
|
||||
id: group_key.clone(),
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* Library Performance Store
|
||||
*
|
||||
* Feature flags and settings for library performance optimizations.
|
||||
* Controls virtualization, thumbnails, and other performance features.
|
||||
*/
|
||||
|
||||
export interface LibraryPerformanceSettings {
|
||||
/**
|
||||
* Enable virtualized rendering for album/artist/track lists.
|
||||
* When enabled, only visible items are rendered in the DOM.
|
||||
*/
|
||||
virtualizationEnabled: boolean;
|
||||
|
||||
/**
|
||||
* Enable thumbnail generation and usage for album artwork.
|
||||
* When enabled, uses smaller thumbnails in list/grid views.
|
||||
*/
|
||||
thumbnailsEnabled: boolean;
|
||||
|
||||
/**
|
||||
* Use optimized network folder filtering (SQL-based instead of N+1).
|
||||
*/
|
||||
optimizedNetworkFilter: boolean;
|
||||
|
||||
/**
|
||||
* Debounce delay for album search (ms).
|
||||
* Higher values reduce CPU usage during typing.
|
||||
*/
|
||||
albumSearchDebounceMs: number;
|
||||
|
||||
/**
|
||||
* Album count threshold for auto-enabling performance mode.
|
||||
* When library exceeds this, performance optimizations activate automatically.
|
||||
*/
|
||||
performanceModeThreshold: number;
|
||||
|
||||
/**
|
||||
* Force performance mode regardless of library size.
|
||||
* Useful for testing or user preference.
|
||||
*/
|
||||
forcePerformanceMode: boolean;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'qbz-library-performance';
|
||||
|
||||
const DEFAULT_SETTINGS: LibraryPerformanceSettings = {
|
||||
virtualizationEnabled: true,
|
||||
thumbnailsEnabled: false, // Will enable when thumbnail system is ready
|
||||
optimizedNetworkFilter: true,
|
||||
albumSearchDebounceMs: 150,
|
||||
performanceModeThreshold: 500,
|
||||
forcePerformanceMode: false,
|
||||
};
|
||||
|
||||
// State
|
||||
let settings: LibraryPerformanceSettings = loadSettings();
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function notifyListeners(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load settings from localStorage
|
||||
*/
|
||||
function loadSettings(): LibraryPerformanceSettings {
|
||||
try {
|
||||
const saved = localStorage.getItem(STORAGE_KEY);
|
||||
if (saved) {
|
||||
const parsed = JSON.parse(saved) as Partial<LibraryPerformanceSettings>;
|
||||
return { ...DEFAULT_SETTINGS, ...parsed };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load library performance settings:', err);
|
||||
}
|
||||
return { ...DEFAULT_SETTINGS };
|
||||
}
|
||||
|
||||
/**
|
||||
* Save settings to localStorage
|
||||
*/
|
||||
function saveSettings(): void {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
|
||||
} catch (err) {
|
||||
console.error('Failed to save library performance settings:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Public API ============
|
||||
|
||||
/**
|
||||
* Subscribe to settings changes
|
||||
*/
|
||||
export function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current settings
|
||||
*/
|
||||
export function getSettings(): LibraryPerformanceSettings {
|
||||
return settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if performance mode should be active based on album count
|
||||
*/
|
||||
export function shouldUsePerformanceMode(albumCount: number): boolean {
|
||||
return settings.forcePerformanceMode || albumCount >= settings.performanceModeThreshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if virtualization is enabled
|
||||
*/
|
||||
export function isVirtualizationEnabled(): boolean {
|
||||
return settings.virtualizationEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if thumbnails are enabled
|
||||
*/
|
||||
export function isThumbnailsEnabled(): boolean {
|
||||
return settings.thumbnailsEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if optimized network filter is enabled
|
||||
*/
|
||||
export function isOptimizedNetworkFilterEnabled(): boolean {
|
||||
return settings.optimizedNetworkFilter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get album search debounce delay
|
||||
*/
|
||||
export function getAlbumSearchDebounceMs(): number {
|
||||
return settings.albumSearchDebounceMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a setting
|
||||
*/
|
||||
export function updateSetting<K extends keyof LibraryPerformanceSettings>(
|
||||
key: K,
|
||||
value: LibraryPerformanceSettings[K]
|
||||
): void {
|
||||
settings[key] = value;
|
||||
saveSettings();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update multiple settings at once
|
||||
*/
|
||||
export function updateSettings(updates: Partial<LibraryPerformanceSettings>): void {
|
||||
settings = { ...settings, ...updates };
|
||||
saveSettings();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset to defaults
|
||||
*/
|
||||
export function resetToDefaults(): void {
|
||||
settings = { ...DEFAULT_SETTINGS };
|
||||
saveSettings();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get performance mode threshold
|
||||
*/
|
||||
export function getPerformanceModeThreshold(): number {
|
||||
return settings.performanceModeThreshold;
|
||||
}
|
||||
Reference in new issue
Block a user