feat(slint): search cortinilla — main-header + immersive
Intelligent Search (phases 3-4): a frontend-agnostic SearchService in qbz-app (Capa A result cache + Capa B interaction ranking) behind a live header dropdown with skeleton loading, stale-while-revalidate, 220ms debounce, keyboard nav + scroll-into-view, per-section caps, a URL-match artwork guard, and an opt-out Settings toggle. Typing previews in the dropdown; Enter goes to Search > All; local-library results show in the dropdown only. Immersive search: an in-immersive glass cortinilla (Albums/Artists/Playlists) that switches playback without navigating — a Settings action select (disabled/replace-queue/play-next/add-to-queue), the HUD stays up while searching and never hides while the cursor rests on the chrome, twinned top buttons, and a clear button with always-centered field text. cc
This commit is contained in:
18 files changed
+4456
-68
No files matched your search
@@ -13,5 +13,8 @@ pub mod plex;
|
||||
pub mod reco_store;
|
||||
pub mod remote_control;
|
||||
pub mod scrobblers;
|
||||
pub mod search_cache;
|
||||
pub mod search_ranking;
|
||||
pub mod search_service;
|
||||
pub mod subscription;
|
||||
pub mod tray;
|
||||
@@ -0,0 +1,412 @@
|
||||
//! CAPA A — stale-while-revalidate result cache for Intelligent Search.
|
||||
//!
|
||||
//! Frontend-agnostic (ADR-006) cache layer for combined search results.
|
||||
//! It owns ONLY the caching of `SearchAllResults` and exposes a tiny,
|
||||
//! synchronous `get`/`put` surface. It does NOT hold a `QbzCore`, does NOT
|
||||
//! call `core.search_all`, and knows nothing about the live network fetch.
|
||||
//! The SWR orchestration (render cached → fire live → replace, guarded by a
|
||||
//! version counter) lives in the qbz-slint controller, which already calls
|
||||
//! `core.search_all()` itself.
|
||||
//!
|
||||
//! ## Two tiers, by volatility
|
||||
//!
|
||||
//! - **Volatile (albums / tracks / playlists):** an in-memory, insertion-order
|
||||
//! LRU bounded to [`VOLATILE_CACHE_CAPACITY`] queries. These categories are
|
||||
//! new-release-sensitive, so they are intentionally NOT persisted — a fresh
|
||||
//! app launch starts them empty and the first live fetch repopulates them.
|
||||
//! - **Persisted (artists):** a small JSON store (`<base>/search_artist_cache.json`)
|
||||
//! mapping a normalized query → its cached `Vec<Artist>`. Artists change far
|
||||
//! less often than album/track/playlist catalogs, so persisting them lets a
|
||||
//! repeated query return its artist slice instantly across restarts. The store
|
||||
//! degrades gracefully: a missing or corrupt file simply starts empty and is
|
||||
//! overwritten on the next `put`, never a panic.
|
||||
//!
|
||||
//! ## The cache key
|
||||
//!
|
||||
//! [`normalize_query`] is THE single source of truth for the key: lowercased,
|
||||
//! trimmed, with internal runs of whitespace collapsed to single spaces. Both
|
||||
//! the volatile LRU and the persisted artist store key on the same normalized
|
||||
//! string, and `search_service.rs` / `search_ranking.rs` re-use this function
|
||||
//! (there is exactly ONE definition, here).
|
||||
|
||||
use qbz_models::{Album, Artist, Playlist, SearchAllResults, SearchResultsPage, Track};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tunables
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Max distinct queries held in the volatile (album/track/playlist) LRU.
|
||||
/// The spec calls for "~40 queries"; the oldest is evicted past this bound.
|
||||
pub const VOLATILE_CACHE_CAPACITY: usize = 40;
|
||||
|
||||
/// On-disk filename for the persisted artist slice (under the per-user base dir).
|
||||
pub const ARTIST_CACHE_FILE: &str = "search_artist_cache.json";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Key normalization — THE cache key
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Normalize a raw query into the canonical cache key: lowercase, trimmed,
|
||||
/// internal whitespace runs collapsed to single spaces.
|
||||
///
|
||||
/// This is the ONLY definition of the cache key; `search_service.rs` and
|
||||
/// `search_ranking.rs` import it from here.
|
||||
pub fn normalize_query(q: &str) -> String {
|
||||
q.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.to_lowercase()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Volatile slice (albums / tracks / playlists) held per query
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The non-persisted, new-release-sensitive portion of a cached result.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct VolatileSlice {
|
||||
albums: Vec<Album>,
|
||||
tracks: Vec<Track>,
|
||||
playlists: Vec<Playlist>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Persisted artist store (JSON file: normalized_query -> Vec<Artist>)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// JSON-backed store for the artist slice. Models the graceful-degradation
|
||||
/// discipline of `discover_prefs.rs` (never panics; a missing/corrupt file
|
||||
/// yields an empty map) but is a plain `serde_json` read/write of a
|
||||
/// `HashMap<normalized_query, Vec<Artist>>` rather than SQLite, since the
|
||||
/// payload is a single small blob with no query needs.
|
||||
struct ArtistCacheStore {
|
||||
path: PathBuf,
|
||||
entries: HashMap<String, Vec<Artist>>,
|
||||
}
|
||||
|
||||
impl ArtistCacheStore {
|
||||
/// Open the store at `<base_dir>/search_artist_cache.json`, loading any
|
||||
/// existing entries. A missing directory is created; a missing or corrupt
|
||||
/// file degrades to an empty map (never an error to the caller).
|
||||
fn open_at(base_dir: &Path) -> Self {
|
||||
// Best-effort: if the dir can't be created the first save() will retry.
|
||||
let _ = std::fs::create_dir_all(base_dir);
|
||||
let path = base_dir.join(ARTIST_CACHE_FILE);
|
||||
let entries = Self::load_from(&path);
|
||||
Self { path, entries }
|
||||
}
|
||||
|
||||
fn load_from(path: &Path) -> HashMap<String, Vec<Artist>> {
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return HashMap::new();
|
||||
};
|
||||
serde_json::from_str::<HashMap<String, Vec<Artist>>>(&text).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<&Vec<Artist>> {
|
||||
self.entries.get(key)
|
||||
}
|
||||
|
||||
/// Upsert the artist slice for `key` and persist the whole map. A write
|
||||
/// failure is logged but never propagated (the in-memory map stays correct).
|
||||
fn put(&mut self, key: String, artists: Vec<Artist>) {
|
||||
self.entries.insert(key, artists);
|
||||
if let Err(e) = self.persist() {
|
||||
log::warn!("search_cache: failed to persist artist cache: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
fn persist(&self) -> Result<(), String> {
|
||||
if let Some(dir) = self.path.parent() {
|
||||
std::fs::create_dir_all(dir)
|
||||
.map_err(|e| format!("Failed to create search cache directory: {}", e))?;
|
||||
}
|
||||
let text = serde_json::to_string(&self.entries)
|
||||
.map_err(|e| format!("Failed to serialize artist cache: {}", e))?;
|
||||
std::fs::write(&self.path, text)
|
||||
.map_err(|e| format!("Failed to write artist cache: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SearchCache — the public CAPA A surface
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The result cache. Combines an in-memory LRU for the volatile categories
|
||||
/// (albums / tracks / playlists) with a persisted artist store. Keyed on the
|
||||
/// [`normalize_query`] of the raw query string.
|
||||
pub struct SearchCache {
|
||||
/// Volatile per-query slices, keyed by normalized query.
|
||||
volatile: HashMap<String, VolatileSlice>,
|
||||
/// Insertion order of `volatile` keys (front = oldest), for LRU eviction.
|
||||
order: VecDeque<String>,
|
||||
/// Persisted artist slices.
|
||||
artists: ArtistCacheStore,
|
||||
}
|
||||
|
||||
impl SearchCache {
|
||||
/// Open the cache rooted at `base_dir` (typically the per-user data dir).
|
||||
/// The persisted artist store is loaded; the volatile maps start empty.
|
||||
/// Never fails: a missing/corrupt artist file degrades to empty.
|
||||
pub fn new(base_dir: &Path) -> Self {
|
||||
Self {
|
||||
volatile: HashMap::new(),
|
||||
order: VecDeque::new(),
|
||||
artists: ArtistCacheStore::open_at(base_dir),
|
||||
}
|
||||
}
|
||||
|
||||
/// Look up the cached merged result for `query`. Returns `None` when nothing
|
||||
/// at all is cached for the normalized key (neither artists nor volatile).
|
||||
///
|
||||
/// When only the artist slice is cached, the album/track/playlist pages come
|
||||
/// back empty (but the result is still `Some`). When only the volatile slice
|
||||
/// is cached, the artist page is empty.
|
||||
pub fn get(&self, query: &str) -> Option<SearchAllResults> {
|
||||
let key = normalize_query(query);
|
||||
|
||||
let volatile = self.volatile.get(&key);
|
||||
let cached_artists = self.artists.get(&key);
|
||||
|
||||
if volatile.is_none() && cached_artists.is_none() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (albums, tracks, playlists) = match volatile {
|
||||
Some(v) => (v.albums.clone(), v.tracks.clone(), v.playlists.clone()),
|
||||
None => (Vec::new(), Vec::new(), Vec::new()),
|
||||
};
|
||||
let artists = cached_artists.cloned().unwrap_or_default();
|
||||
|
||||
Some(SearchAllResults {
|
||||
albums: page(albums),
|
||||
tracks: page(tracks),
|
||||
artists: page(artists),
|
||||
playlists: page(playlists),
|
||||
// most_popular is a derived hero, not cached; the controller can
|
||||
// recompute it from the live result. Cached reads return None.
|
||||
most_popular: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Store `results` for `query`: the album/track/playlist items go into the
|
||||
/// volatile LRU (evicting the oldest query past the bound) and the artist
|
||||
/// items are persisted to disk. A live result always wins — any existing
|
||||
/// entry for the key is overwritten.
|
||||
pub fn put(&mut self, query: &str, results: &SearchAllResults) {
|
||||
let key = normalize_query(query);
|
||||
|
||||
// --- volatile slice (LRU) ---
|
||||
let slice = VolatileSlice {
|
||||
albums: results.albums.items.clone(),
|
||||
tracks: results.tracks.items.clone(),
|
||||
playlists: results.playlists.items.clone(),
|
||||
};
|
||||
let is_new_key = !self.volatile.contains_key(&key);
|
||||
self.volatile.insert(key.clone(), slice);
|
||||
if is_new_key {
|
||||
self.order.push_back(key.clone());
|
||||
} else {
|
||||
// Refresh recency: move the key to the back (most-recent) position.
|
||||
if let Some(pos) = self.order.iter().position(|k| k == &key) {
|
||||
self.order.remove(pos);
|
||||
}
|
||||
self.order.push_back(key.clone());
|
||||
}
|
||||
self.evict_to_bound();
|
||||
|
||||
// --- persisted artist slice ---
|
||||
self.artists.put(key, results.artists.items.clone());
|
||||
}
|
||||
|
||||
/// Evict the oldest volatile entries until within [`VOLATILE_CACHE_CAPACITY`].
|
||||
/// Only the volatile maps are bounded; the persisted artist store is not
|
||||
/// evicted here (it is small and survives restarts by design).
|
||||
fn evict_to_bound(&mut self) {
|
||||
while self.volatile.len() > VOLATILE_CACHE_CAPACITY {
|
||||
if let Some(oldest) = self.order.pop_front() {
|
||||
self.volatile.remove(&oldest);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a `SearchResultsPage<T>` from cached items: `total` = items.len(),
|
||||
/// `offset` = 0, `limit` = items.len() (a full single-page reconstruction).
|
||||
fn page<T>(items: Vec<T>) -> SearchResultsPage<T> {
|
||||
let n = items.len() as u32;
|
||||
SearchResultsPage {
|
||||
items,
|
||||
total: n,
|
||||
offset: 0,
|
||||
limit: n,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn unique_test_dir(name: &str) -> PathBuf {
|
||||
let nonce = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
std::env::temp_dir().join(format!("qbz-app-{name}-{}-{nonce}", std::process::id()))
|
||||
}
|
||||
|
||||
// Album/Track do not derive Default; build them via serde from a minimal
|
||||
// object (all their fields are Option or #[serde(default)]).
|
||||
fn album(id: u64) -> Album {
|
||||
serde_json::from_value(serde_json::json!({ "id": id.to_string() })).unwrap()
|
||||
}
|
||||
|
||||
fn track(id: u64) -> Track {
|
||||
serde_json::from_value(serde_json::json!({ "id": id })).unwrap()
|
||||
}
|
||||
|
||||
fn playlist(id: u64) -> Playlist {
|
||||
serde_json::from_value(serde_json::json!({ "id": id })).unwrap()
|
||||
}
|
||||
|
||||
fn artist(id: u64) -> Artist {
|
||||
Artist {
|
||||
id,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn results(
|
||||
albums: Vec<Album>,
|
||||
tracks: Vec<Track>,
|
||||
artists: Vec<Artist>,
|
||||
playlists: Vec<Playlist>,
|
||||
) -> SearchAllResults {
|
||||
SearchAllResults {
|
||||
albums: page(albums),
|
||||
tracks: page(tracks),
|
||||
artists: page(artists),
|
||||
playlists: page(playlists),
|
||||
most_popular: None,
|
||||
}
|
||||
}
|
||||
|
||||
// (a) put-then-get round-trips albums/tracks/playlists/artists.
|
||||
#[test]
|
||||
fn put_then_get_roundtrips_all_categories() {
|
||||
let dir = unique_test_dir("search-roundtrip");
|
||||
let mut cache = SearchCache::new(&dir);
|
||||
|
||||
let r = results(
|
||||
vec![album(1), album(2)],
|
||||
vec![track(10)],
|
||||
vec![artist(100), artist(200)],
|
||||
vec![playlist(7)],
|
||||
);
|
||||
cache.put("Pink Floyd", &r);
|
||||
|
||||
let got = cache.get("Pink Floyd").expect("cached entry");
|
||||
assert_eq!(got.albums.items.iter().map(|a| a.id.clone()).collect::<Vec<_>>(), vec!["1", "2"]);
|
||||
assert_eq!(got.albums.total, 2);
|
||||
assert_eq!(got.albums.offset, 0);
|
||||
assert_eq!(got.albums.limit, 2);
|
||||
assert_eq!(got.tracks.items.iter().map(|t| t.id).collect::<Vec<_>>(), vec![10]);
|
||||
assert_eq!(got.artists.items.iter().map(|a| a.id).collect::<Vec<_>>(), vec![100, 200]);
|
||||
assert_eq!(got.playlists.items.iter().map(|p| p.id).collect::<Vec<_>>(), vec![7]);
|
||||
assert!(got.most_popular.is_none());
|
||||
|
||||
// Unknown key -> None.
|
||||
assert!(cache.get("nothing here").is_none());
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
// (b) LRU eviction drops the oldest beyond the bound.
|
||||
#[test]
|
||||
fn lru_evicts_oldest_beyond_bound() {
|
||||
let dir = unique_test_dir("search-lru");
|
||||
let mut cache = SearchCache::new(&dir);
|
||||
|
||||
// Fill exactly to capacity with distinct volatile queries.
|
||||
for i in 0..VOLATILE_CACHE_CAPACITY {
|
||||
let q = format!("query {i}");
|
||||
cache.put(&q, &results(vec![album(i as u64)], vec![], vec![], vec![]));
|
||||
}
|
||||
// The oldest ("query 0") is still present at the bound.
|
||||
assert!(cache.volatile.contains_key(&normalize_query("query 0")));
|
||||
assert_eq!(cache.volatile.len(), VOLATILE_CACHE_CAPACITY);
|
||||
|
||||
// One more distinct query evicts the oldest.
|
||||
cache.put("overflow query", &results(vec![album(999)], vec![], vec![], vec![]));
|
||||
assert_eq!(cache.volatile.len(), VOLATILE_CACHE_CAPACITY);
|
||||
assert!(!cache.volatile.contains_key(&normalize_query("query 0")));
|
||||
assert!(cache.volatile.contains_key(&normalize_query("overflow query")));
|
||||
|
||||
// get() on the evicted volatile key still returns Some, because the
|
||||
// ARTIST slice persists (albums/tracks/playlists come back empty).
|
||||
let evicted = cache.get("query 0").expect("artist slice persists");
|
||||
assert!(evicted.albums.items.is_empty());
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
// (c) persisted artists survive a fresh SearchCache::new at the same base_dir.
|
||||
#[test]
|
||||
fn persisted_artists_survive_reopen() {
|
||||
let dir = unique_test_dir("search-persist");
|
||||
{
|
||||
let mut cache = SearchCache::new(&dir);
|
||||
cache.put(
|
||||
"Miles Davis",
|
||||
&results(vec![album(1)], vec![track(2)], vec![artist(42), artist(43)], vec![]),
|
||||
);
|
||||
}
|
||||
// Reopen at the same base dir: volatile is gone, artists survive.
|
||||
{
|
||||
let cache = SearchCache::new(&dir);
|
||||
let got = cache.get("Miles Davis").expect("artist slice persisted");
|
||||
assert_eq!(got.artists.items.iter().map(|a| a.id).collect::<Vec<_>>(), vec![42, 43]);
|
||||
// Volatile categories did NOT persist.
|
||||
assert!(got.albums.items.is_empty());
|
||||
assert!(got.tracks.items.is_empty());
|
||||
}
|
||||
// The on-disk file lives at <base>/search_artist_cache.json.
|
||||
assert!(dir.join(ARTIST_CACHE_FILE).exists());
|
||||
|
||||
// Corrupt the file -> a fresh open degrades to empty (no panic).
|
||||
std::fs::write(dir.join(ARTIST_CACHE_FILE), "{not valid json").unwrap();
|
||||
{
|
||||
let cache = SearchCache::new(&dir);
|
||||
assert!(cache.get("Miles Davis").is_none());
|
||||
}
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
// (d) normalize_query collapses whitespace/case.
|
||||
#[test]
|
||||
fn normalize_collapses_whitespace_and_case() {
|
||||
assert_eq!(normalize_query(" Pink Floyd "), "pink floyd");
|
||||
assert_eq!(normalize_query("MILES\tDAVIS"), "miles davis");
|
||||
assert_eq!(normalize_query("a\n\n b"), "a b");
|
||||
assert_eq!(normalize_query("Already normal"), "already normal");
|
||||
assert_eq!(normalize_query(""), "");
|
||||
|
||||
// The cache keys equivalently-normalized queries together.
|
||||
let dir = unique_test_dir("search-normkey");
|
||||
let mut cache = SearchCache::new(&dir);
|
||||
cache.put(" Pink Floyd ", &results(vec![album(1)], vec![], vec![], vec![]));
|
||||
assert!(cache.get("pink floyd").is_some());
|
||||
assert!(cache.get("PINK FLOYD").is_some());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
//! Per-query interaction ranking for the Intelligent Search module (Capa B).
|
||||
//!
|
||||
//! This is the frontend-agnostic, headless ranking layer (ADR-006). It learns,
|
||||
//! per *normalized query*, which entities the user actually interacts with
|
||||
//! (opens, plays, favorites) and uses that signal to reorder the **cortinilla**
|
||||
//! (the inline suggestion strip) — NEVER the results page itself.
|
||||
//!
|
||||
//! ## Privacy
|
||||
//!
|
||||
//! Everything here is local: a single JSON file under the per-user data dir.
|
||||
//! There is zero telemetry — no network, no analytics, no remote reporting.
|
||||
//!
|
||||
//! ## Persistence
|
||||
//!
|
||||
//! State is a `HashMap<normalized_query, HashMap<(kind, id), score>>` serialized
|
||||
//! to `<base_dir>/search/search_ranking.json`. A missing or corrupt file loads
|
||||
//! as empty state and never panics (same graceful-degradation discipline as
|
||||
//! `discover_prefs` / `reco_store`). Writes are best-effort: a failure is logged
|
||||
//! via `log::warn!` and swallowed, never propagated to the caller.
|
||||
//!
|
||||
//! ## Bounds (so the file can't grow unbounded)
|
||||
//!
|
||||
//! - Each `(kind, id)` score is capped at `MAX_SCORE` (1000).
|
||||
//! - The number of distinct queries is LRU-bound to `MAX_QUERIES` (200); the
|
||||
//! least-recently-touched query is evicted when the cap is exceeded.
|
||||
//!
|
||||
//! ## Architecture note
|
||||
//!
|
||||
//! This struct owns ONLY Capa A's sibling (Capa B). It does NOT hold `QbzCore`
|
||||
//! and does NOT call `search_all`. The SWR orchestration (render cached -> fire
|
||||
//! live -> replace) lives in the qbz-slint controller. See the module-level
|
||||
//! decision in the search module.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// Normalization is shared with Capa A (the cache). Both files compile together.
|
||||
use super::search_cache::normalize_query;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tunables
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Weight added for an "open" / navigate interaction.
|
||||
pub const WEIGHT_OPEN: i64 = 1;
|
||||
/// Weight added for a "play" interaction.
|
||||
pub const WEIGHT_PLAY: i64 = 2;
|
||||
/// Weight added for a "favorite" interaction.
|
||||
pub const WEIGHT_FAVORITE: i64 = 3;
|
||||
|
||||
/// Maximum accumulated score for any single `(kind, id)` pair. Prevents a
|
||||
/// single hammered entity from dominating and bounds the on-disk integer size.
|
||||
pub const MAX_SCORE: i64 = 1000;
|
||||
|
||||
/// Maximum number of distinct normalized queries retained. LRU-evicted.
|
||||
pub const MAX_QUERIES: usize = 200;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Interaction action
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A user interaction with a search-surfaced entity. The weight is the score
|
||||
/// increment applied to that entity for the originating query.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum InteractionAction {
|
||||
/// Opened / navigated to the entity (album page, artist page, ...).
|
||||
Open,
|
||||
/// Started playback of the entity.
|
||||
Play,
|
||||
/// Favorited the entity.
|
||||
Favorite,
|
||||
}
|
||||
|
||||
impl InteractionAction {
|
||||
/// The score increment for this action.
|
||||
pub fn weight(self) -> i64 {
|
||||
match self {
|
||||
InteractionAction::Open => WEIGHT_OPEN,
|
||||
InteractionAction::Play => WEIGHT_PLAY,
|
||||
InteractionAction::Favorite => WEIGHT_FAVORITE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Persisted shape
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// One scored entity within a query bucket. `kind` is one of
|
||||
/// `"artist" | "album" | "track" | "playlist"`; `id` is the entity id as a
|
||||
/// string. We persist as a flat list (instead of a map keyed by a tuple)
|
||||
/// because JSON object keys must be strings — a list of records round-trips
|
||||
/// cleanly and is unambiguous.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct ScoredEntity {
|
||||
kind: String,
|
||||
id: String,
|
||||
score: i64,
|
||||
}
|
||||
|
||||
/// One query bucket: the normalized query plus its scored entities. `order` is
|
||||
/// a monotonically increasing recency stamp used for LRU eviction.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct QueryBucket {
|
||||
query: String,
|
||||
#[serde(default)]
|
||||
order: u64,
|
||||
entities: Vec<ScoredEntity>,
|
||||
}
|
||||
|
||||
/// The full persisted document.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
struct RankingDoc {
|
||||
#[serde(default)]
|
||||
buckets: Vec<QueryBucket>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory store
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Per-query interaction ranking. See module docs.
|
||||
pub struct SearchRanking {
|
||||
/// Path to the JSON file we read/write.
|
||||
path: PathBuf,
|
||||
/// `normalized_query -> { (kind, id) : score }`.
|
||||
ranking: HashMap<String, HashMap<(String, String), i64>>,
|
||||
/// `normalized_query -> recency stamp` (higher = more recently touched).
|
||||
order: HashMap<String, u64>,
|
||||
/// Monotonic counter feeding `order`.
|
||||
tick: u64,
|
||||
}
|
||||
|
||||
impl SearchRanking {
|
||||
/// Load the ranking from `<base_dir>/search/search_ranking.json`.
|
||||
///
|
||||
/// A missing or corrupt file yields an empty ranking — this never panics
|
||||
/// and never returns an error. The `search/` subdir is created lazily on
|
||||
/// the first successful save, not here.
|
||||
pub fn new(base_dir: &Path) -> Self {
|
||||
let path = base_dir.join("search").join("search_ranking.json");
|
||||
let mut store = SearchRanking {
|
||||
path,
|
||||
ranking: HashMap::new(),
|
||||
order: HashMap::new(),
|
||||
tick: 0,
|
||||
};
|
||||
store.load();
|
||||
store
|
||||
}
|
||||
|
||||
/// Read + parse the JSON file into memory. Any error degrades to empty.
|
||||
fn load(&mut self) {
|
||||
let text = match std::fs::read_to_string(&self.path) {
|
||||
Ok(t) => t,
|
||||
Err(_) => return, // missing file == empty ranking (normal first run)
|
||||
};
|
||||
let doc: RankingDoc = match serde_json::from_str(&text) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"search_ranking: corrupt JSON at {:?} ({e}); starting empty",
|
||||
self.path
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut max_order = 0u64;
|
||||
for bucket in doc.buckets {
|
||||
let mut map: HashMap<(String, String), i64> = HashMap::new();
|
||||
for ent in bucket.entities {
|
||||
let score = ent.score.clamp(0, MAX_SCORE);
|
||||
if score <= 0 {
|
||||
continue;
|
||||
}
|
||||
map.insert((ent.kind, ent.id), score);
|
||||
}
|
||||
if map.is_empty() {
|
||||
continue;
|
||||
}
|
||||
max_order = max_order.max(bucket.order);
|
||||
self.order.insert(bucket.query.clone(), bucket.order);
|
||||
self.ranking.insert(bucket.query, map);
|
||||
}
|
||||
self.tick = max_order;
|
||||
}
|
||||
|
||||
/// Serialize the current in-memory state and write it to disk. Best-effort:
|
||||
/// failures are logged and swallowed. Creates the `search/` subdir if needed.
|
||||
fn persist(&self) {
|
||||
if let Some(parent) = self.path.parent() {
|
||||
if let Err(e) = std::fs::create_dir_all(parent) {
|
||||
log::warn!(
|
||||
"search_ranking: cannot create dir {:?} ({e}); skipping persist",
|
||||
parent
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let mut buckets: Vec<QueryBucket> = self
|
||||
.ranking
|
||||
.iter()
|
||||
.map(|(query, map)| {
|
||||
let mut entities: Vec<ScoredEntity> = map
|
||||
.iter()
|
||||
.map(|((kind, id), &score)| ScoredEntity {
|
||||
kind: kind.clone(),
|
||||
id: id.clone(),
|
||||
score,
|
||||
})
|
||||
.collect();
|
||||
// Deterministic on-disk order: highest score first, then kind/id.
|
||||
entities.sort_by(|a, b| {
|
||||
b.score
|
||||
.cmp(&a.score)
|
||||
.then_with(|| a.kind.cmp(&b.kind))
|
||||
.then_with(|| a.id.cmp(&b.id))
|
||||
});
|
||||
QueryBucket {
|
||||
query: query.clone(),
|
||||
order: self.order.get(query).copied().unwrap_or(0),
|
||||
entities,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// Stable file output: sort buckets by query name.
|
||||
buckets.sort_by(|a, b| a.query.cmp(&b.query));
|
||||
|
||||
let doc = RankingDoc { buckets };
|
||||
let json = match serde_json::to_string_pretty(&doc) {
|
||||
Ok(j) => j,
|
||||
Err(e) => {
|
||||
log::warn!("search_ranking: serialize failed ({e}); skipping persist");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Err(e) = std::fs::write(&self.path, json) {
|
||||
log::warn!(
|
||||
"search_ranking: write to {:?} failed ({e}); state kept in memory",
|
||||
self.path
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Touch a query's recency stamp (call when a query bucket is created or
|
||||
/// mutated). Returns the new stamp.
|
||||
fn touch(&mut self, query: &str) -> u64 {
|
||||
self.tick += 1;
|
||||
self.order.insert(query.to_string(), self.tick);
|
||||
self.tick
|
||||
}
|
||||
|
||||
/// Evict the least-recently-touched query when over the LRU cap.
|
||||
fn enforce_query_cap(&mut self) {
|
||||
while self.ranking.len() > MAX_QUERIES {
|
||||
// Find the query with the smallest recency stamp.
|
||||
let victim = self
|
||||
.order
|
||||
.iter()
|
||||
.filter(|(q, _)| self.ranking.contains_key(*q))
|
||||
.min_by_key(|(_, &stamp)| stamp)
|
||||
.map(|(q, _)| q.clone());
|
||||
match victim {
|
||||
Some(q) => {
|
||||
self.ranking.remove(&q);
|
||||
self.order.remove(&q);
|
||||
}
|
||||
None => break, // defensive: nothing to evict
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record an interaction: bump `(kind, id)`'s score for `query` by the
|
||||
/// action weight, cap it at `MAX_SCORE`, enforce the LRU query cap, then
|
||||
/// persist (best-effort). `kind` should be one of
|
||||
/// `"artist" | "album" | "track" | "playlist"`.
|
||||
pub fn record(&mut self, query: &str, kind: &str, id: &str, action: InteractionAction) {
|
||||
let key = normalize_query(query);
|
||||
if key.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.touch(&key);
|
||||
let bucket = self.ranking.entry(key.clone()).or_default();
|
||||
let slot = bucket.entry((kind.to_string(), id.to_string())).or_insert(0);
|
||||
*slot = (*slot + action.weight()).min(MAX_SCORE);
|
||||
self.enforce_query_cap();
|
||||
self.persist();
|
||||
}
|
||||
|
||||
/// The single highest-scored entity for `query`, if any. Ties break
|
||||
/// deterministically: higher score, then kind ascending, then id ascending.
|
||||
pub fn top_for_query(&self, query: &str) -> Option<(String, String)> {
|
||||
let key = normalize_query(query);
|
||||
let bucket = self.ranking.get(&key)?;
|
||||
bucket
|
||||
.iter()
|
||||
.max_by(|(ak, &asc), (bk, &bsc)| {
|
||||
// We want the *max* element; for ties we prefer the lexically
|
||||
// smaller (kind, id), so invert those comparisons.
|
||||
asc.cmp(&bsc)
|
||||
.then_with(|| bk.0.cmp(&ak.0))
|
||||
.then_with(|| bk.1.cmp(&ak.1))
|
||||
})
|
||||
.map(|((kind, id), _)| (kind.clone(), id.clone()))
|
||||
}
|
||||
|
||||
/// The learned score for a specific `(kind, id)` under `query`, or 0.
|
||||
pub fn score_for(&self, query: &str, kind: &str, id: &str) -> i64 {
|
||||
let key = normalize_query(query);
|
||||
self.ranking
|
||||
.get(&key)
|
||||
.and_then(|b| b.get(&(kind.to_string(), id.to_string())))
|
||||
.copied()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Stable-sort `items` in place, descending by their learned score for
|
||||
/// `(kind, id_of(item))` under `query`. Items with no learned score keep
|
||||
/// their original relative order and sit behind all scored items.
|
||||
///
|
||||
/// This is for the **cortinilla only** — never call it to reorder the
|
||||
/// results page.
|
||||
pub fn rank_within<T>(
|
||||
&self,
|
||||
query: &str,
|
||||
kind: &str,
|
||||
items: &mut Vec<T>,
|
||||
id_of: impl Fn(&T) -> String,
|
||||
) {
|
||||
let key = normalize_query(query);
|
||||
let bucket = match self.ranking.get(&key) {
|
||||
Some(b) if !b.is_empty() => b,
|
||||
_ => return, // nothing learned for this query: leave API order intact
|
||||
};
|
||||
// `sort_by` is stable, so equal-score items (including all unscored,
|
||||
// which share score 0) retain their original relative order. Descending
|
||||
// by score puts scored items ahead of unscored ones.
|
||||
items.sort_by(|a, b| {
|
||||
let sa = bucket
|
||||
.get(&(kind.to_string(), id_of(a)))
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
let sb = bucket
|
||||
.get(&(kind.to_string(), id_of(b)))
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
sb.cmp(&sa)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn unique_test_dir(name: &str) -> PathBuf {
|
||||
let nonce = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
std::env::temp_dir().join(format!("qbz_search_ranking_{name}_{nonce}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_bumps_by_correct_weights_and_accumulates() {
|
||||
let dir = unique_test_dir("weights");
|
||||
let mut r = SearchRanking::new(&dir);
|
||||
r.record("Pink Floyd", "artist", "42", InteractionAction::Open); // +1
|
||||
assert_eq!(r.score_for("pink floyd", "artist", "42"), 1);
|
||||
r.record("Pink Floyd", "artist", "42", InteractionAction::Play); // +2
|
||||
assert_eq!(r.score_for("Pink Floyd", "artist", "42"), 3);
|
||||
r.record("Pink Floyd", "artist", "42", InteractionAction::Favorite); // +3
|
||||
assert_eq!(r.score_for("PINK FLOYD", "artist", "42"), 6);
|
||||
// Distinct entity is tracked separately.
|
||||
r.record("Pink Floyd", "album", "99", InteractionAction::Play);
|
||||
assert_eq!(r.score_for("pink floyd", "album", "99"), 2);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_for_query_returns_the_max() {
|
||||
let dir = unique_test_dir("top");
|
||||
let mut r = SearchRanking::new(&dir);
|
||||
r.record("daft punk", "artist", "1", InteractionAction::Open); // 1
|
||||
r.record("daft punk", "album", "2", InteractionAction::Favorite); // 3
|
||||
r.record("daft punk", "track", "3", InteractionAction::Play); // 2
|
||||
assert_eq!(
|
||||
r.top_for_query("Daft Punk"),
|
||||
Some(("album".to_string(), "2".to_string()))
|
||||
);
|
||||
assert_eq!(r.top_for_query("never searched"), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn score_cap_holds() {
|
||||
let dir = unique_test_dir("cap");
|
||||
let mut r = SearchRanking::new(&dir);
|
||||
// 500 favorites * 3 = 1500, capped at MAX_SCORE.
|
||||
for _ in 0..500 {
|
||||
r.record("x", "track", "7", InteractionAction::Favorite);
|
||||
}
|
||||
assert_eq!(r.score_for("x", "track", "7"), MAX_SCORE);
|
||||
// Further bumps don't exceed the cap.
|
||||
r.record("x", "track", "7", InteractionAction::Play);
|
||||
assert_eq!(r.score_for("x", "track", "7"), MAX_SCORE);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_lru_cap_evicts_oldest() {
|
||||
let dir = unique_test_dir("lru");
|
||||
let mut r = SearchRanking::new(&dir);
|
||||
// Fill exactly to the cap.
|
||||
for i in 0..MAX_QUERIES {
|
||||
r.record(&format!("q{i}"), "artist", "1", InteractionAction::Open);
|
||||
}
|
||||
assert_eq!(r.ranking.len(), MAX_QUERIES);
|
||||
// q0 is the oldest, still present.
|
||||
assert_eq!(r.score_for("q0", "artist", "1"), 1);
|
||||
// One more distinct query evicts the oldest (q0).
|
||||
r.record("overflow", "artist", "1", InteractionAction::Open);
|
||||
assert_eq!(r.ranking.len(), MAX_QUERIES);
|
||||
assert_eq!(r.score_for("q0", "artist", "1"), 0); // evicted
|
||||
assert_eq!(r.score_for("overflow", "artist", "1"), 1); // present
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_round_trips() {
|
||||
let dir = unique_test_dir("persist");
|
||||
{
|
||||
let mut r = SearchRanking::new(&dir);
|
||||
r.record("radiohead", "album", "okc", InteractionAction::Favorite); // 3
|
||||
r.record("radiohead", "track", "creep", InteractionAction::Play); // 2
|
||||
}
|
||||
// Fresh instance over the SAME dir reads persisted state.
|
||||
let r2 = SearchRanking::new(&dir);
|
||||
assert_eq!(r2.score_for("radiohead", "album", "okc"), 3);
|
||||
assert_eq!(r2.score_for("radiohead", "track", "creep"), 2);
|
||||
assert_eq!(
|
||||
r2.top_for_query("Radiohead"),
|
||||
Some(("album".to_string(), "okc".to_string()))
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_file_loads_empty() {
|
||||
let dir = unique_test_dir("corrupt");
|
||||
let search_dir = dir.join("search");
|
||||
std::fs::create_dir_all(&search_dir).unwrap();
|
||||
std::fs::write(search_dir.join("search_ranking.json"), b"{ not json").unwrap();
|
||||
let r = SearchRanking::new(&dir);
|
||||
assert_eq!(r.score_for("anything", "artist", "1"), 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rank_within_reorders_scored_ahead_keeping_unscored_stable() {
|
||||
let dir = unique_test_dir("rank");
|
||||
let mut r = SearchRanking::new(&dir);
|
||||
// Learn scores: id "b" highest, id "d" lower, others unseen.
|
||||
r.record("metallica", "album", "b", InteractionAction::Favorite); // 3
|
||||
r.record("metallica", "album", "d", InteractionAction::Open); // 1
|
||||
|
||||
// Original API order: a, b, c, d, e (a/c/e unscored).
|
||||
let mut items = vec!["a", "b", "c", "d", "e"];
|
||||
r.rank_within("metallica", "album", &mut items, |s| s.to_string());
|
||||
|
||||
// Scored items first (b=3, d=1), then unscored in original order (a,c,e).
|
||||
assert_eq!(items, vec!["b", "d", "a", "c", "e"]);
|
||||
|
||||
// A query with nothing learned leaves order untouched.
|
||||
let mut untouched = vec!["x", "y", "z"];
|
||||
r.rank_within("unknown", "album", &mut untouched, |s| s.to_string());
|
||||
assert_eq!(untouched, vec!["x", "y", "z"]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
//! SearchService — the composed, frontend-agnostic Intelligent Search facade.
|
||||
//!
|
||||
//! This is the single reusable entry point that owns the two headless layers of
|
||||
//! Intelligent Search (ADR-006):
|
||||
//!
|
||||
//! - **Capa A** — [`SearchCache`]: stale-while-revalidate result cache.
|
||||
//! - **Capa B** — [`SearchRanking`]: per-query interaction ranking for the
|
||||
//! cortinilla.
|
||||
//!
|
||||
//! ## What it deliberately does NOT own
|
||||
//!
|
||||
//! `SearchService` is **non-generic**. It does NOT hold a `QbzCore` and does NOT
|
||||
//! call `core.search_all`. `QbzCore` is `QbzCore<A: FrontendAdapter>`; making
|
||||
//! `SearchService<A>` would force that generic through every qbz-slint global
|
||||
//! accessor for no benefit. The SWR orchestration (render cached → fire live →
|
||||
//! replace, guarded by the version counter) lives in the qbz-slint controller,
|
||||
//! which already calls `core.search_all()` itself. This struct is purely the
|
||||
//! reusable cache + ranking layer.
|
||||
//!
|
||||
//! ## Interior mutability
|
||||
//!
|
||||
//! Cache `put` and ranking `record` need `&mut self`; the corresponding service
|
||||
//! methods therefore take `&mut self`. There is intentionally NO interior
|
||||
//! `Mutex` inside `SearchService` — the qbz-slint global wraps the whole service
|
||||
//! in a `Mutex` (Phase 4), so the caller owns the locking. The only interior
|
||||
//! mutability here is the [`AtomicBool`] enabled flag, which `set_enabled` /
|
||||
//! `enabled` can flip through a shared `&self` (the kill switch must work even
|
||||
//! while another thread holds nothing but `&self`).
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use super::search_cache::SearchCache;
|
||||
use super::search_ranking::SearchRanking;
|
||||
|
||||
// Re-export so qbz-slint imports the action enum from ONE place.
|
||||
pub use super::search_ranking::InteractionAction;
|
||||
|
||||
/// The composed Intelligent Search service: cache (Capa A) + ranking (Capa B),
|
||||
/// gated by an `enabled` kill switch. Frontend-agnostic, headless, plain (no
|
||||
/// interior `Mutex` around the stores — the caller locks).
|
||||
pub struct SearchService {
|
||||
/// Capa A — result cache (SWR).
|
||||
cache: SearchCache,
|
||||
/// Capa B — per-query interaction ranking.
|
||||
ranking: SearchRanking,
|
||||
/// Master on/off. Default `true`. When `false`, every method is an inert
|
||||
/// no-op (`cached`/`top_for_query` return `None`; `store`/`record_interaction`/
|
||||
/// `rank_within` do nothing).
|
||||
enabled: AtomicBool,
|
||||
}
|
||||
|
||||
impl SearchService {
|
||||
/// Construct both stores rooted at `base_dir` (typically the per-user data
|
||||
/// dir). Each store owns its own sub-file / sub-dir under that base. Never
|
||||
/// fails: missing or corrupt persisted state degrades to empty.
|
||||
pub fn new(base_dir: &Path) -> Self {
|
||||
Self {
|
||||
cache: SearchCache::new(base_dir),
|
||||
ranking: SearchRanking::new(base_dir),
|
||||
enabled: AtomicBool::new(true),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Intelligent Search is currently enabled.
|
||||
pub fn enabled(&self) -> bool {
|
||||
self.enabled.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Flip the master kill switch. Works through a shared `&self` so the toggle
|
||||
/// can be applied without taking the store lock for mutation.
|
||||
pub fn set_enabled(&self, on: bool) {
|
||||
self.enabled.store(on, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Cached merged result for `query`, or `None` when disabled or uncached.
|
||||
pub fn cached(&self, query: &str) -> Option<qbz_models::SearchAllResults> {
|
||||
if !self.enabled() {
|
||||
return None;
|
||||
}
|
||||
self.cache.get(query)
|
||||
}
|
||||
|
||||
/// Store a live `results` page for `query` in the cache. No-op when disabled.
|
||||
pub fn store(&mut self, query: &str, results: &qbz_models::SearchAllResults) {
|
||||
if !self.enabled() {
|
||||
return;
|
||||
}
|
||||
self.cache.put(query, results);
|
||||
}
|
||||
|
||||
/// Record a user interaction with a search-surfaced entity. No-op when
|
||||
/// disabled. `kind` is one of `"artist" | "album" | "track" | "playlist"`.
|
||||
pub fn record_interaction(
|
||||
&mut self,
|
||||
query: &str,
|
||||
kind: &str,
|
||||
id: &str,
|
||||
action: InteractionAction,
|
||||
) {
|
||||
if !self.enabled() {
|
||||
return;
|
||||
}
|
||||
self.ranking.record(query, kind, id, action);
|
||||
}
|
||||
|
||||
/// The single highest-scored `(kind, id)` learned for `query`, or `None`
|
||||
/// when disabled / nothing learned.
|
||||
pub fn top_for_query(&self, query: &str) -> Option<(String, String)> {
|
||||
if !self.enabled() {
|
||||
return None;
|
||||
}
|
||||
self.ranking.top_for_query(query)
|
||||
}
|
||||
|
||||
/// Stable-sort `items` in place by their learned score for `query` (the
|
||||
/// cortinilla reorder). No-op when disabled.
|
||||
pub fn rank_within<T>(
|
||||
&self,
|
||||
query: &str,
|
||||
kind: &str,
|
||||
items: &mut Vec<T>,
|
||||
id_of: impl Fn(&T) -> String,
|
||||
) {
|
||||
if !self.enabled() {
|
||||
return;
|
||||
}
|
||||
self.ranking.rank_within(query, kind, items, id_of);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use qbz_models::{Album, Artist, Playlist, SearchAllResults, SearchResultsPage, Track};
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn unique_test_dir(name: &str) -> PathBuf {
|
||||
let nonce = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
std::env::temp_dir().join(format!(
|
||||
"qbz-app-search-service-{name}-{}-{nonce}",
|
||||
std::process::id()
|
||||
))
|
||||
}
|
||||
|
||||
fn page<T>(items: Vec<T>) -> SearchResultsPage<T> {
|
||||
let n = items.len() as u32;
|
||||
SearchResultsPage {
|
||||
items,
|
||||
total: n,
|
||||
offset: 0,
|
||||
limit: n,
|
||||
}
|
||||
}
|
||||
|
||||
fn album(id: u64) -> Album {
|
||||
serde_json::from_value(serde_json::json!({ "id": id.to_string() })).unwrap()
|
||||
}
|
||||
fn track(id: u64) -> Track {
|
||||
serde_json::from_value(serde_json::json!({ "id": id })).unwrap()
|
||||
}
|
||||
fn playlist(id: u64) -> Playlist {
|
||||
serde_json::from_value(serde_json::json!({ "id": id })).unwrap()
|
||||
}
|
||||
fn artist(id: u64) -> Artist {
|
||||
Artist {
|
||||
id,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_results() -> SearchAllResults {
|
||||
SearchAllResults {
|
||||
albums: page(vec![album(1)]),
|
||||
tracks: page(vec![track(10)]),
|
||||
artists: page(vec![artist(100)]),
|
||||
playlists: page(vec![playlist(7)]),
|
||||
most_popular: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smoke_store_get_record_top_and_disable_gate() {
|
||||
let dir = unique_test_dir("smoke");
|
||||
let mut svc = SearchService::new(&dir);
|
||||
|
||||
// Enabled by default.
|
||||
assert!(svc.enabled());
|
||||
|
||||
// store -> cached round-trips.
|
||||
svc.store("Pink Floyd", &sample_results());
|
||||
let got = svc.cached("Pink Floyd").expect("cached entry");
|
||||
assert_eq!(
|
||||
got.albums.items.iter().map(|a| a.id.clone()).collect::<Vec<_>>(),
|
||||
vec!["1"]
|
||||
);
|
||||
assert_eq!(got.tracks.items.iter().map(|t| t.id).collect::<Vec<_>>(), vec![10]);
|
||||
assert_eq!(got.artists.items.iter().map(|a| a.id).collect::<Vec<_>>(), vec![100]);
|
||||
|
||||
// record -> top_for_query returns it.
|
||||
svc.record_interaction("Pink Floyd", "artist", "100", InteractionAction::Favorite);
|
||||
assert_eq!(
|
||||
svc.top_for_query("Pink Floyd"),
|
||||
Some(("artist".to_string(), "100".to_string()))
|
||||
);
|
||||
|
||||
// Disable: reads return None, writes no-op.
|
||||
svc.set_enabled(false);
|
||||
assert!(!svc.enabled());
|
||||
assert!(svc.cached("Pink Floyd").is_none());
|
||||
assert!(svc.top_for_query("Pink Floyd").is_none());
|
||||
|
||||
// store/record are no-ops while disabled (no new data observed once re-enabled).
|
||||
svc.store("New Query", &sample_results());
|
||||
svc.record_interaction("Pink Floyd", "album", "1", InteractionAction::Play);
|
||||
|
||||
// Re-enable: the data written while disabled was never stored.
|
||||
svc.set_enabled(true);
|
||||
assert!(svc.cached("New Query").is_none());
|
||||
// The pre-disable artist interaction survives; the disabled-period album bump did not.
|
||||
assert_eq!(
|
||||
svc.top_for_query("Pink Floyd"),
|
||||
Some(("artist".to_string(), "100".to_string()))
|
||||
);
|
||||
|
||||
// rank_within is a no-op while disabled (order preserved).
|
||||
svc.set_enabled(false);
|
||||
let mut items = vec!["x", "y", "z"];
|
||||
svc.rank_within("Pink Floyd", "artist", &mut items, |s| s.to_string());
|
||||
assert_eq!(items, vec!["x", "y", "z"]);
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user