merge: integrate static-review hardening into pre-release
cc
This commit is contained in:
34 files changed
+849
-381
No files matched your search
@@ -40,6 +40,9 @@
|
||||
# and preference preservation; qt-runtime-gate.sh covers the update UI.
|
||||
# Shared cargo-test.sh also gates Orbit HTTP host isolation, library profiles
|
||||
# and the SSE public-identity projection. No separate test command to drift.
|
||||
# Shared cargo-test.sh also gates the 2026-09 static-review regressions: image-cache
|
||||
# LRU eviction, loudness-cache degrade, live-writer log rotation lock, URL-free
|
||||
# CDN fetch errors + signed-param redaction, and the link-resolver timeout.
|
||||
# Qt runtime gate includes Library source/count regressions and the Rust
|
||||
# playlist-deletion/creation/offline-gapless and maintenance retry regressions.
|
||||
# The shared library service gate preserves manual scan feedback while keeping
|
||||
|
||||
Generated
+1
@@ -4316,6 +4316,7 @@ dependencies = [
|
||||
"qbz-models",
|
||||
"qbz-qobuz",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.20",
|
||||
|
||||
@@ -190,10 +190,21 @@ pub fn plan(source: &AccountSnapshot, target: &AccountSnapshot, ledger: &Ledger)
|
||||
.unwrap_or(&[]);
|
||||
// §9.3: same name and nothing foreign in the target copy = the same
|
||||
// playlist (possibly behind); anything foreign = a different one.
|
||||
let twin = same_name
|
||||
let is_twin = |tgt: &&OwnedPlaylist| tgt.track_ids.iter().all(|id| src_set.contains(id));
|
||||
let twin = same_name.iter().copied().find(is_twin);
|
||||
// An earlier run may have created the "(migrated)" copy and died
|
||||
// before the ledger recorded it (apply.rs creates first, saves second).
|
||||
// Before creating a SECOND copy, look for that orphan by its copy
|
||||
// name under the same twin rule.
|
||||
let copy_name = format!("{}{}", src.name.trim(), COPY_SUFFIX);
|
||||
let orphan_copy = target_by_name
|
||||
.get(&normalized(©_name))
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.find(|tgt| tgt.track_ids.iter().all(|id| src_set.contains(id)));
|
||||
match twin {
|
||||
.copied()
|
||||
.find(is_twin);
|
||||
match twin.or(orphan_copy) {
|
||||
Some(tgt) => {
|
||||
let tgt_set: HashSet<u64> = tgt.track_ids.iter().copied().collect();
|
||||
let missing: Vec<u64> = src
|
||||
@@ -386,6 +397,37 @@ mod tests {
|
||||
assert!(matches!(&p.playlists[0], PlaylistAction::Create { .. }));
|
||||
}
|
||||
|
||||
/// apply.rs creates the copy BEFORE the ledger records it; a crash in
|
||||
/// between left an orphan "(migrated)" playlist that the next run copied
|
||||
/// again. The orphan is found by name under the same twin rule and
|
||||
/// merged into instead.
|
||||
#[test]
|
||||
fn a_rerun_after_an_interrupted_copy_merges_into_the_orphan_copy() {
|
||||
let mut source = snap();
|
||||
source.playlists = vec![owned(12, "Metal", &[6, 7])];
|
||||
let mut target = snap();
|
||||
target.playlists = vec![
|
||||
// the foreign same-name playlist that forced the copy
|
||||
owned(101, "Metal", &[6, 99]),
|
||||
// the copy the crashed run created, never written to the ledger
|
||||
owned(300, "Metal (migrated)", &[6]),
|
||||
];
|
||||
let p = plan(&source, &target, &Ledger::default());
|
||||
assert_eq!(
|
||||
p.playlists,
|
||||
vec![PlaylistAction::Merge {
|
||||
source_id: 12,
|
||||
target_id: 300,
|
||||
name: "Metal".into(),
|
||||
missing_track_ids: vec![7],
|
||||
}]
|
||||
);
|
||||
// A copy that holds foreign tracks is somebody else's playlist: copy again.
|
||||
target.playlists[1] = owned(300, "Metal (migrated)", &[6, 42]);
|
||||
let p = plan(&source, &target, &Ledger::default());
|
||||
assert!(matches!(&p.playlists[0], PlaylistAction::CreateCopy { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscriptions_skip_what_the_target_already_follows_or_owns() {
|
||||
let mut source = snap();
|
||||
|
||||
@@ -1171,7 +1171,9 @@ pub async fn restore_session_paused<A: FrontendAdapter + Send + Sync + 'static>(
|
||||
core.set_queue_with_order(tracks, index, pb.shuffle_enabled, None)
|
||||
.await;
|
||||
core.set_repeat_mode(repeat_from_str(&pb.repeat_mode)).await;
|
||||
let _ = core.set_volume(pb.volume);
|
||||
if let Err(e) = core.set_volume(pb.volume) {
|
||||
log::warn!("[qbzd] driver: volume restore failed: {e}");
|
||||
}
|
||||
log::info!(
|
||||
"[qbzd] driver: restored {count} queue tracks (index {index:?}), paused; \
|
||||
saved position {position}s"
|
||||
|
||||
@@ -453,7 +453,9 @@ pub async fn restore<A: Adapter>(runtime: &Arc<AppRuntime<A>>) -> bool {
|
||||
.await;
|
||||
// The queue session carries the authoritative last volume; apply it to the
|
||||
// player (the slider also seeds from ui_prefs, but this keeps them in step).
|
||||
let _ = runtime.core().set_volume(pb_sess.volume);
|
||||
if let Err(e) = runtime.core().set_volume(pb_sess.volume) {
|
||||
log::warn!("[session] persist: volume restore failed: {e}");
|
||||
}
|
||||
if RESUME_POSITION.load(Ordering::Relaxed) && position > 0 && current_track_id != 0 {
|
||||
PENDING_RESUME.store(position, Ordering::Relaxed);
|
||||
PENDING_RESUME_TRACK.store(current_track_id, Ordering::Relaxed);
|
||||
|
||||
@@ -17,7 +17,8 @@ pub struct CachedLoudness {
|
||||
}
|
||||
|
||||
pub struct LoudnessCache {
|
||||
conn: Mutex<Connection>,
|
||||
/// `None` = disabled: every lookup misses, every store is dropped.
|
||||
conn: Option<Mutex<Connection>>,
|
||||
}
|
||||
|
||||
impl LoudnessCache {
|
||||
@@ -32,7 +33,26 @@ impl LoudnessCache {
|
||||
let db_path = data_dir.join("loudness_cache.db");
|
||||
let conn = Connection::open(&db_path)
|
||||
.map_err(|e| format!("Failed to open loudness cache database: {}", e))?;
|
||||
let cache = Self::with_connection(conn)?;
|
||||
log::info!("[LoudnessCache] Opened at {}", db_path.display());
|
||||
Ok(cache)
|
||||
}
|
||||
|
||||
/// Session-only cache (SQLite in memory): the fallback when the on-disk
|
||||
/// database cannot be opened. Analyses are reused within the run and lost
|
||||
/// at exit.
|
||||
pub fn in_memory() -> Result<Self, String> {
|
||||
let conn = Connection::open_in_memory()
|
||||
.map_err(|e| format!("Failed to open in-memory loudness cache: {}", e))?;
|
||||
Self::with_connection(conn)
|
||||
}
|
||||
|
||||
/// No cache at all: `get*` always miss and `set*` are no-ops. Last resort.
|
||||
pub fn disabled() -> Self {
|
||||
Self { conn: None }
|
||||
}
|
||||
|
||||
fn with_connection(conn: Connection) -> Result<Self, String> {
|
||||
conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;")
|
||||
.map_err(|e| format!("Failed to enable WAL for loudness cache database: {}", e))?;
|
||||
|
||||
@@ -58,16 +78,18 @@ impl LoudnessCache {
|
||||
ON track_loudness(content_key) WHERE content_key IS NOT NULL;",
|
||||
);
|
||||
|
||||
log::info!("[LoudnessCache] Opened at {}", db_path.display());
|
||||
|
||||
Ok(Self {
|
||||
conn: Mutex::new(conn),
|
||||
conn: Some(Mutex::new(conn)),
|
||||
})
|
||||
}
|
||||
|
||||
fn lock(&self) -> Option<std::sync::MutexGuard<'_, Connection>> {
|
||||
self.conn.as_ref()?.lock().ok()
|
||||
}
|
||||
|
||||
/// Look up cached loudness for a track.
|
||||
pub fn get(&self, track_id: u64) -> Option<CachedLoudness> {
|
||||
let conn = self.conn.lock().ok()?;
|
||||
let conn = self.lock()?;
|
||||
conn.query_row(
|
||||
"SELECT gain_db, peak, source FROM track_loudness WHERE track_id = ?1",
|
||||
params![track_id as i64],
|
||||
@@ -88,7 +110,7 @@ impl LoudnessCache {
|
||||
if content_key.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Ok(conn) = self.conn.lock() {
|
||||
if let Some(conn) = self.lock() {
|
||||
let _ = conn.execute(
|
||||
"UPDATE track_loudness SET content_key = ?1 WHERE track_id = ?2",
|
||||
params![content_key.trim(), track_id as i64],
|
||||
@@ -99,7 +121,7 @@ impl LoudnessCache {
|
||||
/// Look up cached loudness by content key (any source's copy of the
|
||||
/// same recording). Newest analysis wins.
|
||||
pub fn get_by_content_key(&self, content_key: &str) -> Option<CachedLoudness> {
|
||||
let conn = self.conn.lock().ok()?;
|
||||
let conn = self.lock()?;
|
||||
conn.query_row(
|
||||
"SELECT gain_db, peak, source FROM track_loudness
|
||||
WHERE content_key = ?1 ORDER BY created_at DESC LIMIT 1",
|
||||
@@ -117,7 +139,7 @@ impl LoudnessCache {
|
||||
|
||||
/// Store or update loudness data for a track.
|
||||
pub fn set(&self, track_id: u64, gain_db: f32, peak: f32, source: &str) {
|
||||
if let Ok(conn) = self.conn.lock() {
|
||||
if let Some(conn) = self.lock() {
|
||||
let result = conn.execute(
|
||||
"INSERT OR REPLACE INTO track_loudness (track_id, gain_db, peak, source, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, strftime('%s', 'now'))",
|
||||
@@ -133,3 +155,28 @@ impl LoudnessCache {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn in_memory_cache_round_trips_by_track_and_content_key() {
|
||||
let cache = LoudnessCache::in_memory().unwrap();
|
||||
assert!(cache.get(7).is_none());
|
||||
cache.set(7, -3.5, 0.9, "ebur128");
|
||||
let hit = cache.get(7).unwrap();
|
||||
assert_eq!((hit.gain_db, hit.peak, hit.source.as_str()), (-3.5, 0.9, "ebur128"));
|
||||
cache.set_content_key(7, "USRC17607839");
|
||||
assert_eq!(cache.get_by_content_key("USRC17607839").unwrap().gain_db, -3.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_cache_misses_and_swallows_writes() {
|
||||
let cache = LoudnessCache::disabled();
|
||||
cache.set(7, -3.5, 0.9, "ebur128");
|
||||
cache.set_content_key(7, "USRC17607839");
|
||||
assert!(cache.get(7).is_none());
|
||||
assert!(cache.get_by_content_key("USRC17607839").is_none());
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@
|
||||
//! LRU disk cache for Qobuz album/artist images.
|
||||
//! - Stores images keyed by MD5 hash of URL
|
||||
//! - Tracks last-access time for LRU eviction
|
||||
//! - Respects a configurable max size
|
||||
//! - Framework-agnostic: shared by the Tauri app and the Slint shell so
|
||||
//! both read and write the same `~/.cache/qbz/images` cache.
|
||||
//! - Respects a configurable max size ([`ImageCacheService::evict`], batched)
|
||||
//! - Framework-agnostic: the Qt shell owns the policy (`artwork_qt.rs`), this
|
||||
//! crate owns the store (`~/.cache/qbz/images`).
|
||||
|
||||
use md5::{Digest, Md5};
|
||||
use rusqlite::{params, Connection};
|
||||
@@ -18,6 +18,13 @@ pub struct ImageCacheStats {
|
||||
pub file_count: u64,
|
||||
}
|
||||
|
||||
/// Outcome of one [`ImageCacheService::evict`] batch.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct EvictBatch {
|
||||
pub freed_bytes: u64,
|
||||
pub evicted_entries: usize,
|
||||
}
|
||||
|
||||
pub struct ImageCacheService {
|
||||
cache_dir: PathBuf,
|
||||
conn: Connection,
|
||||
@@ -29,7 +36,12 @@ impl ImageCacheService {
|
||||
.ok_or_else(|| "Could not find cache directory".to_string())?
|
||||
.join("qbz")
|
||||
.join("images");
|
||||
Self::open_at(cache_dir)
|
||||
}
|
||||
|
||||
/// Open (or create) the cache at an explicit directory. `new` is this on
|
||||
/// `~/.cache/qbz/images`; tests use a temp dir.
|
||||
pub fn open_at(cache_dir: PathBuf) -> Result<Self, String> {
|
||||
std::fs::create_dir_all(&cache_dir)
|
||||
.map_err(|e| format!("Failed to create image cache dir: {}", e))?;
|
||||
|
||||
@@ -54,6 +66,18 @@ impl ImageCacheService {
|
||||
Ok(Self { cache_dir, conn })
|
||||
}
|
||||
|
||||
/// Test hook: rewrite an entry's `last_accessed` stamp.
|
||||
#[cfg(test)]
|
||||
fn backdate(&self, url: &str, last_accessed: i64) {
|
||||
let hash = Self::url_hash(url);
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE cached_images SET last_accessed = ?1 WHERE hash = ?2",
|
||||
params![last_accessed, hash],
|
||||
)
|
||||
.expect("backdate");
|
||||
}
|
||||
|
||||
fn url_hash(url: &str) -> String {
|
||||
let mut hasher = Md5::new();
|
||||
hasher.update(url.as_bytes());
|
||||
@@ -115,8 +139,14 @@ impl ImageCacheService {
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Evict least-recently-accessed entries until total size is under max_bytes.
|
||||
pub fn evict(&self, max_bytes: u64) -> Result<u64, String> {
|
||||
/// Evict least-recently-accessed entries until the total size is under
|
||||
/// `max_bytes`, deleting at most `max_entries` rows per call.
|
||||
///
|
||||
/// Batched on purpose: the Qt shell holds a process-wide mutex around
|
||||
/// this service and its GUI thread takes that mutex to resolve covers,
|
||||
/// so a caller trims in small batches and releases the lock in between.
|
||||
/// Loop until `evicted_entries == 0`.
|
||||
pub fn evict(&self, max_bytes: u64, max_entries: usize) -> Result<EvictBatch, String> {
|
||||
let total: i64 = self
|
||||
.conn
|
||||
.query_row(
|
||||
@@ -126,21 +156,23 @@ impl ImageCacheService {
|
||||
)
|
||||
.map_err(|e| format!("Failed to query cache size: {}", e))?;
|
||||
|
||||
let mut batch = EvictBatch {
|
||||
freed_bytes: 0,
|
||||
evicted_entries: 0,
|
||||
};
|
||||
if (total as u64) <= max_bytes {
|
||||
return Ok(0);
|
||||
return Ok(batch);
|
||||
}
|
||||
|
||||
let mut to_free = (total as u64) - max_bytes;
|
||||
let mut freed: u64 = 0;
|
||||
|
||||
// Get LRU entries (oldest access first)
|
||||
// LRU entries (oldest access first), bounded to this batch.
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare("SELECT hash, file_size FROM cached_images ORDER BY last_accessed ASC")
|
||||
.prepare("SELECT hash, file_size FROM cached_images ORDER BY last_accessed ASC LIMIT ?1")
|
||||
.map_err(|e| format!("Failed to prepare eviction query: {}", e))?;
|
||||
|
||||
let limit = i64::try_from(max_entries).unwrap_or(i64::MAX);
|
||||
let entries: Vec<(String, i64)> = stmt
|
||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.query_map(params![limit], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||
.map_err(|e| format!("Failed to query LRU entries: {}", e))?
|
||||
.filter_map(|r| r.ok())
|
||||
.collect();
|
||||
@@ -157,11 +189,12 @@ impl ImageCacheService {
|
||||
.conn
|
||||
.execute("DELETE FROM cached_images WHERE hash = ?1", params![hash]);
|
||||
let size = file_size as u64;
|
||||
freed += size;
|
||||
batch.freed_bytes += size;
|
||||
batch.evicted_entries += 1;
|
||||
to_free = to_free.saturating_sub(size);
|
||||
}
|
||||
|
||||
Ok(freed)
|
||||
Ok(batch)
|
||||
}
|
||||
|
||||
/// Get cache statistics.
|
||||
@@ -203,3 +236,80 @@ impl ImageCacheService {
|
||||
Ok(stats.total_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fresh_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("qbz-image-cache-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evict_drops_least_recently_accessed_first_and_unlinks_files() {
|
||||
let dir = fresh_dir("lru");
|
||||
let cache = ImageCacheService::open_at(dir.clone()).unwrap();
|
||||
let oldest = cache.store("https://img/oldest", &[0u8; 100]).unwrap();
|
||||
let middle = cache.store("https://img/middle", &[0u8; 100]).unwrap();
|
||||
let newest = cache.store("https://img/newest", &[0u8; 100]).unwrap();
|
||||
cache.backdate("https://img/oldest", 1_000);
|
||||
cache.backdate("https://img/middle", 2_000);
|
||||
cache.backdate("https://img/newest", 3_000);
|
||||
|
||||
let batch = cache.evict(150, usize::MAX).unwrap();
|
||||
|
||||
assert_eq!(batch, EvictBatch { freed_bytes: 200, evicted_entries: 2 });
|
||||
assert!(!oldest.exists());
|
||||
assert!(!middle.exists());
|
||||
assert!(newest.exists());
|
||||
let stats = cache.stats().unwrap();
|
||||
assert_eq!((stats.total_bytes, stats.file_count), (100, 1));
|
||||
assert!(cache.get("https://img/oldest").is_none());
|
||||
assert!(cache.get("https://img/newest").is_some());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evict_is_a_no_op_at_or_under_budget() {
|
||||
let dir = fresh_dir("noop");
|
||||
let cache = ImageCacheService::open_at(dir.clone()).unwrap();
|
||||
let kept = cache.store("https://img/a", &[0u8; 100]).unwrap();
|
||||
assert_eq!(cache.evict(100, usize::MAX).unwrap(), EvictBatch { freed_bytes: 0, evicted_entries: 0 });
|
||||
assert_eq!(cache.evict(u64::MAX, usize::MAX).unwrap().evicted_entries, 0);
|
||||
assert!(kept.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evict_honours_the_batch_size_so_a_caller_can_release_its_lock_between_batches() {
|
||||
let dir = fresh_dir("batch");
|
||||
let cache = ImageCacheService::open_at(dir.clone()).unwrap();
|
||||
for i in 0..3 {
|
||||
cache.store(&format!("https://img/{i}"), &[0u8; 100]).unwrap();
|
||||
cache.backdate(&format!("https://img/{i}"), 1_000 + i);
|
||||
}
|
||||
assert_eq!(cache.evict(0, 1).unwrap(), EvictBatch { freed_bytes: 100, evicted_entries: 1 });
|
||||
assert_eq!(cache.evict(0, 1).unwrap(), EvictBatch { freed_bytes: 100, evicted_entries: 1 });
|
||||
assert_eq!(cache.evict(0, 1).unwrap(), EvictBatch { freed_bytes: 100, evicted_entries: 1 });
|
||||
assert_eq!(cache.evict(0, 1).unwrap(), EvictBatch { freed_bytes: 0, evicted_entries: 0 });
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_refreshes_last_accessed_so_a_touched_entry_survives_eviction() {
|
||||
let dir = fresh_dir("touch");
|
||||
let cache = ImageCacheService::open_at(dir.clone()).unwrap();
|
||||
let touched = cache.store("https://img/touched", &[0u8; 100]).unwrap();
|
||||
let untouched = cache.store("https://img/untouched", &[0u8; 100]).unwrap();
|
||||
cache.backdate("https://img/touched", 1_000);
|
||||
cache.backdate("https://img/untouched", 2_000);
|
||||
// A read is an access: it moves `touched` to the newest slot.
|
||||
assert!(cache.get("https://img/touched").is_some());
|
||||
assert_eq!(cache.evict(100, usize::MAX).unwrap().freed_bytes, 100);
|
||||
assert!(touched.exists());
|
||||
assert!(!untouched.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -61,5 +61,5 @@ mod image_cache;
|
||||
mod playback_cache;
|
||||
|
||||
pub use audio_cache::{AudioCache, CacheStats, CachedTrack, CacheAdmission};
|
||||
pub use image_cache::{ImageCacheService, ImageCacheStats};
|
||||
pub use image_cache::{EvictBatch, ImageCacheService, ImageCacheStats};
|
||||
pub use playback_cache::{PlaybackCache, PlaybackCacheStats};
|
||||
@@ -35,10 +35,12 @@ pub async fn resolve_offline_bytes(
|
||||
let guard = offline.db.lock().await;
|
||||
let db = guard.as_ref()?;
|
||||
let row = db.get_cmaf_bundle(track_id).ok().flatten()?;
|
||||
// A play IS an access. LRU eviction (`maintenance::check_cache_limit`)
|
||||
// orders by `last_accessed_at`, which until now only the download
|
||||
// wrote — so the cache evicted the tracks the user played most,
|
||||
// oldest download first. This is the one place every offline play
|
||||
// A play IS an access: keep `last_accessed_at` truthful (before this
|
||||
// only the download wrote it). Nothing evicts on it today —
|
||||
// `maintenance::check_cache_limit` only REFUSES new downloads at the
|
||||
// limit, and downloaded albums are user data kept until removed in
|
||||
// the offline manager — but it is the stamp any future space-reclaim
|
||||
// policy must order by. This is the one place every offline play
|
||||
// funnels through (both frontends and qbzd resolve here).
|
||||
if let Err(e) = db.touch(track_id) {
|
||||
log::debug!("[OfflineResolve] touch({track_id}) failed: {e}");
|
||||
|
||||
@@ -596,12 +596,15 @@ fn load_from_fallback() -> Result<Option<QobuzCredentials>, String> {
|
||||
Ok(Some(creds))
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("Failed to decrypt credentials: {}", e);
|
||||
// Try legacy format as fallback
|
||||
if let Ok(Some(creds)) = load_legacy_credentials(&path) {
|
||||
log::info!("Loaded from legacy format, will re-encrypt on next save");
|
||||
return Ok(Some(creds));
|
||||
}
|
||||
// A new-format file that fails to decrypt is a key mismatch
|
||||
// (machine-id / install salt / portal secret changed — see the
|
||||
// daemon hazard on `PortalKey`) or a corrupt file; the legacy
|
||||
// loader cannot succeed on JSON, so it is not tried. A fresh
|
||||
// login rewrites the file.
|
||||
log::warn!(
|
||||
"Failed to decrypt credentials at {}: {e} (key derivation inputs changed or the file is corrupt; log in again to rewrite it)",
|
||||
path.display()
|
||||
);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
|
||||
+140
-56
@@ -1,43 +1,52 @@
|
||||
//! One-shot logger installation + the on-disk file sink (open / rotate).
|
||||
|
||||
use std::fs::File;
|
||||
use std::fs::{File, OpenOptions, TryLockError};
|
||||
use std::io::BufWriter;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use crate::tee::TeeLogger;
|
||||
|
||||
static INSTALLED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Install the [`TeeLogger`] as the global `log` logger.
|
||||
/// The desktop app's log file name.
|
||||
pub const DEFAULT_LOG_FILE: &str = "qbz.log";
|
||||
|
||||
/// The on-disk sink plus the advisory lock that marks this process as a live
|
||||
/// writer of that file (see [`open_log_file_at`]). Dropping it releases both.
|
||||
pub(crate) struct FileSink {
|
||||
pub(crate) writer: BufWriter<File>,
|
||||
pub(crate) lock: Option<File>,
|
||||
}
|
||||
|
||||
/// Install the [`TeeLogger`] as the global `log` logger, writing to
|
||||
/// [`DEFAULT_LOG_FILE`].
|
||||
///
|
||||
/// Builds the inner `env_logger` logger from `RUST_LOG` (falling back to `default_level`),
|
||||
/// opens/rotates the on-disk file, then sets the boxed logger + max level. Idempotent:
|
||||
/// a second call is a guarded no-op (it neither rotates the file again nor panics).
|
||||
pub fn install(default_level: &str) {
|
||||
install_with_file_sink(default_level, true);
|
||||
install_with_file_sink(default_level, Some(DEFAULT_LOG_FILE));
|
||||
}
|
||||
|
||||
/// Same as [`install`], but to `file_name` inside the same logs directory.
|
||||
/// `qbzd` uses `qbzd.log` so a daemon never shares (or rotates) the desktop
|
||||
/// app's file.
|
||||
pub fn install_named(default_level: &str, file_name: &str) {
|
||||
install_with_file_sink(default_level, Some(file_name));
|
||||
}
|
||||
|
||||
/// Same as [`install`], but with the on-disk file sink DISABLED (stderr + ring only).
|
||||
///
|
||||
/// For an internal, disposable child process that re-enters the same `main`.
|
||||
/// [`open_log_file`] rotates `qbz.log` to `qbz.log.prev` and creates a fresh
|
||||
/// file on every call, so a child running it MID-RUN renames the live log out
|
||||
/// from under the parent — which keeps writing to the renamed inode — and
|
||||
/// leaves `qbz.log` holding nothing but the child's own first lines.
|
||||
///
|
||||
/// Field-reported in #749: on Linux every launch spawns the presentation /
|
||||
/// GPU preflight child, so `~/.local/share/qbz/logs/qbz.log` ended at two
|
||||
/// lines on EVERY run while the app itself was healthy and its whole log went
|
||||
/// to `qbz.log.prev`. The user's log file, the first thing a bug report
|
||||
/// attaches, was structurally useless. A child's output is already captured
|
||||
/// by the parent (proof line on stdout, `preflight_output_tail` on failure),
|
||||
/// so it loses nothing by staying off the file.
|
||||
/// For an internal, disposable child process that re-enters the same `main`
|
||||
/// (presentation / GPU preflight, #749). A child's output is already captured
|
||||
/// by the parent, so it loses nothing by staying off the file — and it never
|
||||
/// has to touch the parent's file at all.
|
||||
pub fn install_without_file_sink(default_level: &str) {
|
||||
install_with_file_sink(default_level, false);
|
||||
install_with_file_sink(default_level, None);
|
||||
}
|
||||
|
||||
fn install_with_file_sink(default_level: &str, file_sink: bool) {
|
||||
fn install_with_file_sink(default_level: &str, file_name: Option<&str>) {
|
||||
// True one-shot guard: avoid re-rotating the log file or fighting an already-set logger.
|
||||
if INSTALLED.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
@@ -57,10 +66,10 @@ fn install_with_file_sink(default_level: &str, file_sink: bool) {
|
||||
)
|
||||
.build();
|
||||
let level = inner.filter();
|
||||
let file = if file_sink { open_log_file() } else { None };
|
||||
let sink = file_name.and_then(open_log_file);
|
||||
|
||||
// Ignore the Err if a logger was somehow already set elsewhere.
|
||||
if log::set_boxed_logger(Box::new(TeeLogger::new(inner, file))).is_ok() {
|
||||
if log::set_boxed_logger(Box::new(TeeLogger::new(inner, sink))).is_ok() {
|
||||
log::set_max_level(level);
|
||||
}
|
||||
}
|
||||
@@ -70,35 +79,74 @@ pub fn set_level(level: log::LevelFilter) {
|
||||
log::set_max_level(level);
|
||||
}
|
||||
|
||||
/// Path to the current-run log file (`~/.local/share/qbz/logs/qbz.log`), if a data dir exists.
|
||||
/// `~/.local/share/qbz/logs`, if a data dir exists.
|
||||
fn logs_dir() -> Option<PathBuf> {
|
||||
Some(dirs::data_dir()?.join("qbz").join("logs"))
|
||||
}
|
||||
|
||||
/// Path to the desktop app's current-run log file (`~/.local/share/qbz/logs/qbz.log`).
|
||||
pub fn log_file_path() -> Option<PathBuf> {
|
||||
Some(dirs::data_dir()?.join("qbz").join("logs").join("qbz.log"))
|
||||
log_file_path_named(DEFAULT_LOG_FILE)
|
||||
}
|
||||
|
||||
/// Open the log file for this run, rotating any previous one to `qbz.log.prev`.
|
||||
/// Returns `None` (file sink disabled, gracefully) on any filesystem error.
|
||||
fn open_log_file() -> Option<BufWriter<File>> {
|
||||
open_log_file_at(&log_file_path()?)
|
||||
/// Path to `file_name` inside the logs directory (`qbzd.log` for the daemon).
|
||||
pub fn log_file_path_named(file_name: &str) -> Option<PathBuf> {
|
||||
Some(logs_dir()?.join(file_name))
|
||||
}
|
||||
|
||||
/// [`open_log_file`] against an explicit path, so the rotation contract is
|
||||
/// testable without a real data dir.
|
||||
fn open_log_file(file_name: &str) -> Option<FileSink> {
|
||||
open_log_file_at(&log_file_path_named(file_name)?)
|
||||
}
|
||||
|
||||
/// Open the run's log file at `path`.
|
||||
///
|
||||
/// NOTE the hazard this encodes: every call renames the CURRENT file away and
|
||||
/// starts an empty one. That is right once per process run and wrong for
|
||||
/// anything else — see [`install_without_file_sink`].
|
||||
fn open_log_file_at(path: &std::path::Path) -> Option<BufWriter<File>> {
|
||||
/// Rotation (`<name>` → `<name>.prev`, then a fresh file) happens ONLY when no
|
||||
/// live process is writing the file. Liveness is an advisory lock on the
|
||||
/// sidecar `<name>.lock`: every writer holds it shared for its lifetime; an
|
||||
/// opener probes it with a non-blocking exclusive lock and, when that is
|
||||
/// refused, APPENDS to the live file instead of renaming it away. That is
|
||||
/// what a second `qbz` launch, a `qbzd` sharing the directory, or any future
|
||||
/// caller of [`install`] used to do to a running process (#749, and the
|
||||
/// 2026-09 static review). The lock lives on the sidecar, never on the log
|
||||
/// itself, so it can never interfere with writes (a shared `LockFileEx`
|
||||
/// would, on Windows). Returns `None` (file sink disabled, gracefully) on any
|
||||
/// filesystem error.
|
||||
fn open_log_file_at(path: &Path) -> Option<FileSink> {
|
||||
let dir = path.parent()?;
|
||||
std::fs::create_dir_all(dir).ok()?;
|
||||
let name = path.file_name()?.to_string_lossy().into_owned();
|
||||
|
||||
if path.exists() {
|
||||
let prev = dir.join("qbz.log.prev");
|
||||
// Best-effort rotation; a failure here must not disable logging.
|
||||
let _ = std::fs::rename(path, &prev);
|
||||
let lock = OpenOptions::new()
|
||||
.create(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(dir.join(format!("{name}.lock")))
|
||||
.ok();
|
||||
let live_writer = match lock.as_ref().map(File::try_lock) {
|
||||
Some(Err(TryLockError::WouldBlock)) => true,
|
||||
// Granted, unsupported (exotic filesystem) or no sidecar: nobody we
|
||||
// can see is live — keep the historical rotate behaviour.
|
||||
Some(Ok(())) | Some(Err(TryLockError::Error(_))) | None => false,
|
||||
};
|
||||
if let Some(lock) = lock.as_ref() {
|
||||
// Join the live writers (downgrade the probe if we held it).
|
||||
let _ = lock.unlock();
|
||||
let _ = lock.lock_shared();
|
||||
}
|
||||
|
||||
let file = File::create(path).ok()?;
|
||||
Some(BufWriter::new(file))
|
||||
let file = if live_writer && path.exists() {
|
||||
OpenOptions::new().append(true).open(path).ok()?
|
||||
} else {
|
||||
if path.exists() {
|
||||
// Best-effort rotation; a failure here must not disable logging.
|
||||
let _ = std::fs::rename(path, dir.join(format!("{name}.prev")));
|
||||
}
|
||||
File::create(path).ok()?
|
||||
};
|
||||
Some(FileSink {
|
||||
writer: BufWriter::new(file),
|
||||
lock,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -106,32 +154,68 @@ mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
/// The rotation contract, and the reason a child process must never run it:
|
||||
/// a second open renames the live file to `qbz.log.prev` and leaves an
|
||||
/// empty `qbz.log` behind. This is #749 in three lines.
|
||||
#[test]
|
||||
fn a_second_open_rotates_the_live_file_away() {
|
||||
let dir = std::env::temp_dir().join(format!("qbz-log-rotate-{}", std::process::id()));
|
||||
fn fresh_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("qbz-log-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
/// #749 was a child process renaming the live log away; a second `qbz`
|
||||
/// launch or a `qbzd` in the same directory did the same. A live writer
|
||||
/// holds the sidecar lock, so a second opener APPENDS.
|
||||
#[test]
|
||||
fn a_second_open_while_the_first_writer_is_live_appends() {
|
||||
let dir = fresh_dir("live");
|
||||
let path = dir.join("qbz.log");
|
||||
|
||||
let mut first = open_log_file_at(&path).expect("first open");
|
||||
writeln!(first, "parent line").unwrap();
|
||||
first.flush().unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "parent line\n");
|
||||
writeln!(first.writer, "parent line").unwrap();
|
||||
first.writer.flush().unwrap();
|
||||
|
||||
// A second process (the preflight child) installing its own logger.
|
||||
let mut second = open_log_file_at(&path).expect("second open");
|
||||
writeln!(second, "child line").unwrap();
|
||||
second.flush().unwrap();
|
||||
writeln!(second.writer, "second-instance line").unwrap();
|
||||
second.writer.flush().unwrap();
|
||||
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "child line\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("qbz.log.prev")).unwrap(),
|
||||
"parent line\n",
|
||||
"the parent's log survives only under .prev"
|
||||
std::fs::read_to_string(&path).unwrap(),
|
||||
"parent line\nsecond-instance line\n"
|
||||
);
|
||||
|
||||
assert!(!dir.join("qbz.log.prev").exists(), "nothing was rotated");
|
||||
drop(second);
|
||||
drop(first);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// With no live writer the historical contract holds: rotate to
|
||||
/// `<name>.prev` and start fresh. The prev name follows the file name.
|
||||
#[test]
|
||||
fn open_after_the_previous_writer_closed_rotates_to_prev() {
|
||||
let dir = fresh_dir("rotate");
|
||||
let path = dir.join("qbzd.log");
|
||||
{
|
||||
let mut first = open_log_file_at(&path).expect("first open");
|
||||
writeln!(first.writer, "run one").unwrap();
|
||||
first.writer.flush().unwrap();
|
||||
}
|
||||
let mut second = open_log_file_at(&path).expect("second open");
|
||||
writeln!(second.writer, "run two").unwrap();
|
||||
second.writer.flush().unwrap();
|
||||
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "run two\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("qbzd.log.prev")).unwrap(),
|
||||
"run one\n"
|
||||
);
|
||||
drop(second);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_log_paths_share_the_logs_directory() {
|
||||
let Some(default) = log_file_path() else { return };
|
||||
let daemon = log_file_path_named("qbzd.log").unwrap();
|
||||
assert_eq!(default.parent(), daemon.parent());
|
||||
assert_eq!(default.file_name().unwrap(), DEFAULT_LOG_FILE);
|
||||
assert_eq!(daemon.file_name().unwrap(), "qbzd.log");
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
//! `env_logger`'s built `Logger` and fans visible records out to three sinks:
|
||||
//! 1. **stderr** (redacted text, same line format as the file sink),
|
||||
//! 2. a bounded **in-memory ring** ([`ring`], cap [`ring::RING_CAP`]), and
|
||||
//! 3. an **on-disk file** (`~/.local/share/qbz/logs/qbz.log`, prev-rotated at startup).
|
||||
//! 3. an **on-disk file** (`~/.local/share/qbz/logs/qbz.log`; `qbzd.log` for the daemon),
|
||||
//! prev-rotated at startup unless another live process is writing it.
|
||||
//!
|
||||
//! Secret **redaction** ([`redact`]) is applied once at the single write choke point,
|
||||
//! so every downstream consumer (stderr, ring, file, clipboard, paste upload) gets clean text.
|
||||
@@ -26,6 +27,6 @@ pub mod tee;
|
||||
|
||||
pub use bundle::{format_diagnostics_bundle, DiagFields};
|
||||
pub use fatal::install as install_fatal_signal_reporter;
|
||||
pub use install::{install, install_without_file_sink, set_level};
|
||||
pub use install::{install, install_named, install_without_file_sink, set_level};
|
||||
pub use line::LogLine;
|
||||
pub use redact::{redact, register_secret};
|
||||
@@ -45,6 +45,12 @@ fn patterns() -> &'static Vec<Regex> {
|
||||
r#"(?i)((access|refresh)_token["':=\s]+)[A-Za-z0-9._\-]+"#,
|
||||
// generic URL token param
|
||||
r#"(?i)(token=)[^&\s"']+"#,
|
||||
// Signed CDN URLs: Qobuz/Akamai `hmac=`, CloudFront `Signature=` /
|
||||
// `Policy=` / `Key-Pair-Id=`. Value = up to the next query separator.
|
||||
r#"(?i)(hmac=)[^&\s"']+"#,
|
||||
r#"(?i)(signature=)[^&\s"']+"#,
|
||||
r#"(?i)(policy=)[^&\s"']+"#,
|
||||
r#"(?i)(key-pair-id=)[^&\s"']+"#,
|
||||
]
|
||||
.iter()
|
||||
.filter_map(|p| Regex::new(p).ok())
|
||||
@@ -74,7 +80,9 @@ pub fn register_secret(value: String) {
|
||||
/// Cheap pre-check: does the line contain any substring that one of the regexes could
|
||||
/// match? Avoids running the whole pattern set on the overwhelming majority of lines.
|
||||
fn has_redaction_candidate(lower: &str) -> bool {
|
||||
const NEEDLES: [&str; 6] = ["token", "secret", "password", "bearer", "auth", "sig"];
|
||||
const NEEDLES: [&str; 9] = [
|
||||
"token", "secret", "password", "bearer", "auth", "sig", "hmac", "policy", "key-pair",
|
||||
];
|
||||
NEEDLES.iter().any(|n| lower.contains(n))
|
||||
}
|
||||
|
||||
@@ -171,6 +179,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacts_signed_cdn_url_params() {
|
||||
let r = redact(
|
||||
"fetch: https://streaming.example/file?eid=1&hmac=HMACSECRET&etsp=1700000000 \
|
||||
and https://cf.example/l.json?Policy=POLICYBLOB&Signature=SIGBLOB&Key-Pair-Id=KPID123",
|
||||
);
|
||||
for leaked in ["HMACSECRET", "POLICYBLOB", "SIGBLOB", "KPID123"] {
|
||||
assert!(!r.contains(leaked), "leaked {leaked}: {r}");
|
||||
}
|
||||
assert!(r.contains("etsp=1700000000"), "non-secret params survive: {r}");
|
||||
assert!(r.contains("eid=1"), "non-secret params survive: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_registry_scrubs_unlabeled_value() {
|
||||
register_secret("LIVE_TOKEN_xyz".into());
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::time::Instant;
|
||||
|
||||
use log::{Log, Metadata, Record};
|
||||
|
||||
use crate::install::FileSink;
|
||||
use crate::line::LogLine;
|
||||
use crate::repeat::ConsecutiveRecords;
|
||||
use crate::{redact, ring};
|
||||
@@ -25,15 +26,23 @@ pub struct TeeLogger {
|
||||
|
||||
struct Output {
|
||||
file: Option<BufWriter<File>>,
|
||||
/// Held for the process lifetime: marks this process as a live writer of
|
||||
/// the log file (see `install::open_log_file_at`).
|
||||
_lock: Option<File>,
|
||||
consecutive: ConsecutiveRecords,
|
||||
}
|
||||
|
||||
impl TeeLogger {
|
||||
pub(crate) fn new(inner: env_logger::Logger, file: Option<BufWriter<File>>) -> Self {
|
||||
pub(crate) fn new(inner: env_logger::Logger, sink: Option<FileSink>) -> Self {
|
||||
let (file, lock) = match sink {
|
||||
Some(sink) => (Some(sink.writer), sink.lock),
|
||||
None => (None, None),
|
||||
};
|
||||
Self {
|
||||
inner,
|
||||
output: Mutex::new(Output {
|
||||
file,
|
||||
_lock: lock,
|
||||
consecutive: ConsecutiveRecords::default(),
|
||||
}),
|
||||
}
|
||||
@@ -140,7 +149,13 @@ mod tests {
|
||||
let inner = env_logger::Builder::new()
|
||||
.filter_level(log::LevelFilter::Info)
|
||||
.build();
|
||||
let logger = TeeLogger::new(inner, Some(BufWriter::new(file)));
|
||||
let logger = TeeLogger::new(
|
||||
inner,
|
||||
Some(FileSink {
|
||||
writer: BufWriter::new(file),
|
||||
lock: None,
|
||||
}),
|
||||
);
|
||||
logger.log(
|
||||
&Record::builder()
|
||||
.level(Level::Info)
|
||||
|
||||
@@ -25,3 +25,8 @@ log = { workspace = true }
|
||||
|
||||
# Error handling
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# The timeout test builds a reqwest client, which panics with "No provider
|
||||
# set" until a process-level rustls CryptoProvider exists (same as qbz-qobuz).
|
||||
rustls = { version = "0.23", features = ["aws_lc_rs"] }
|
||||
@@ -10,6 +10,30 @@ use crate::detection::{spotify, MusicProvider};
|
||||
/// URL hardcoded in the `src-tauri` original. No API keys are embedded here.
|
||||
const QBZ_PROXY_BASE: &str = "https://qbz-api-proxy.blitzkriegfc.workers.dev";
|
||||
|
||||
/// Same budget as `odesli.rs` (`REQUEST_TIMEOUT`). A bare
|
||||
/// `reqwest::Client::new()` has NO timeout, so a black-holed connection hung
|
||||
/// the fast path forever — and since `lib.rs` only falls back to Odesli after
|
||||
/// the fast path returns, the link never resolved.
|
||||
const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// Build the fast-path client with a total deadline of `total`.
|
||||
pub(crate) fn build_client(total: std::time::Duration) -> reqwest::Client {
|
||||
reqwest::Client::builder()
|
||||
.timeout(total)
|
||||
.connect_timeout(CONNECT_TIMEOUT.min(total))
|
||||
.user_agent("QBZ/1.0.0")
|
||||
.build()
|
||||
.expect("reqwest client")
|
||||
}
|
||||
|
||||
/// The one shared client (connection pool + timeouts) for the direct
|
||||
/// platform calls and the QBZ proxy.
|
||||
fn client() -> &'static reqwest::Client {
|
||||
static CLIENT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
|
||||
CLIENT.get_or_init(|| build_client(REQUEST_TIMEOUT))
|
||||
}
|
||||
|
||||
/// Try to get title+artist directly from the platform API.
|
||||
/// Returns None if the platform isn't supported or the request fails.
|
||||
pub(crate) async fn try_direct_platform_metadata(
|
||||
@@ -98,7 +122,7 @@ async fn try_tidal_metadata(url: &str, is_track: bool) -> Option<(String, String
|
||||
);
|
||||
|
||||
log::debug!("Link resolver: Tidal direct API: {}", api_url);
|
||||
let data: serde_json::Value = reqwest::Client::new()
|
||||
let data: serde_json::Value = client()
|
||||
.get(&api_url)
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.send()
|
||||
@@ -134,17 +158,7 @@ async fn try_tidal_metadata(url: &str, is_track: bool) -> Option<(String, String
|
||||
/// Get an OAuth token from the QBZ proxy for the given platform.
|
||||
async fn get_proxy_token(platform: &str) -> Option<String> {
|
||||
let url = format!("{}/{}/token", QBZ_PROXY_BASE, platform);
|
||||
let data: serde_json::Value = reqwest::Client::builder()
|
||||
.default_headers({
|
||||
let mut h = reqwest::header::HeaderMap::new();
|
||||
h.insert(
|
||||
reqwest::header::USER_AGENT,
|
||||
reqwest::header::HeaderValue::from_static("QBZ/1.0.0"),
|
||||
);
|
||||
h
|
||||
})
|
||||
.build()
|
||||
.ok()?
|
||||
let data: serde_json::Value = client()
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
@@ -156,3 +170,37 @@ async fn get_proxy_token(platform: &str) -> Option<String> {
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|v| v.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A silent server (accepts, never answers) must not park the fast path:
|
||||
/// the Odesli fallback only runs after it returns.
|
||||
#[tokio::test]
|
||||
async fn fast_path_client_gives_up_on_a_silent_server() {
|
||||
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}/tidal/token", listener.local_addr().unwrap());
|
||||
let hold = tokio::spawn(async move {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
tokio::time::sleep(Duration::from_secs(30)).await;
|
||||
drop(socket);
|
||||
});
|
||||
|
||||
let started = Instant::now();
|
||||
let err = super::build_client(Duration::from_millis(400))
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(err.is_timeout(), "expected a timeout, got: {err}");
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(5),
|
||||
"took {:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
hold.abort();
|
||||
}
|
||||
}
|
||||
@@ -466,46 +466,6 @@ impl OfflineCacheDb {
|
||||
})
|
||||
}
|
||||
|
||||
/// Get tracks to evict (LRU order) to free up space
|
||||
pub fn get_tracks_for_eviction(
|
||||
&self,
|
||||
bytes_to_free: u64,
|
||||
) -> Result<Vec<(u64, String)>, String> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT track_id, file_path, file_size_bytes FROM cached_tracks
|
||||
WHERE status = 'ready'
|
||||
ORDER BY last_accessed_at ASC",
|
||||
)
|
||||
.map_err(|e| format!("Failed to prepare eviction query: {}", e))?;
|
||||
|
||||
let mut result = Vec::new();
|
||||
let mut freed = 0u64;
|
||||
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
Ok((
|
||||
row.get::<_, i64>(0)? as u64,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, i64>(2)? as u64,
|
||||
))
|
||||
})
|
||||
.map_err(|e| format!("Failed to query for eviction: {}", e))?;
|
||||
|
||||
for row in rows {
|
||||
if freed >= bytes_to_free {
|
||||
break;
|
||||
}
|
||||
let (track_id, file_path, size) =
|
||||
row.map_err(|e| format!("Failed to read row: {}", e))?;
|
||||
result.push((track_id, file_path));
|
||||
freed += size;
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Clear all entries
|
||||
pub fn clear_all(&self) -> Result<Vec<String>, String> {
|
||||
// Get all file paths first
|
||||
|
||||
@@ -393,9 +393,17 @@ fn audio_metadata_from_codec_params(
|
||||
codec: params.codec,
|
||||
});
|
||||
}
|
||||
let sample_rate = params.sample_rate.ok_or("No sample rate in codec params")?;
|
||||
let channels = params.channels.map(|c| c.count() as u16).unwrap_or(2);
|
||||
// Same guard the fully-decoded path applies (`samples.is_empty() ||
|
||||
// sample_rate == 0 || channels == 0`): the streaming sources build
|
||||
// `NonZero` from these with an `unwrap`.
|
||||
if sample_rate == 0 || channels == 0 {
|
||||
return Err("Invalid signal format in codec params (zero sample rate or channel count)".into());
|
||||
}
|
||||
Ok(AudioMetadata {
|
||||
sample_rate: params.sample_rate.ok_or("No sample rate in codec params")?,
|
||||
channels: params.channels.map(|c| c.count() as u16).unwrap_or(2),
|
||||
sample_rate,
|
||||
channels,
|
||||
bit_depth: params.bits_per_sample,
|
||||
codec: params.codec,
|
||||
})
|
||||
@@ -2098,13 +2106,28 @@ impl Player {
|
||||
|
||||
// Initialize loudness analysis system
|
||||
let (analyzer_tx, analyzer_rx) = mpsc::sync_channel::<AnalyzerMessage>(64);
|
||||
// A cache is an accelerator, never a reason to abort: this used to
|
||||
// `panic!` here, which killed the one audio thread for the rest
|
||||
// of the run (every later command failed with "Failed to send")
|
||||
// on a full disk, a read-only profile or a corrupt
|
||||
// loudness_cache.db. Degrade instead.
|
||||
let loudness_cache = match LoudnessCache::new() {
|
||||
Ok(c) => Arc::new(c),
|
||||
Err(e) => {
|
||||
log::error!("Failed to create loudness cache: {}. Normalization will work without caching.", e);
|
||||
// Create a fallback in-memory cache (will be lost on restart)
|
||||
// For now, just panic — this should not fail in practice
|
||||
panic!("LoudnessCache creation failed: {}", e);
|
||||
log::error!(
|
||||
"Failed to open the loudness cache: {e}. Normalization keeps working; \
|
||||
analyses are not persisted this run."
|
||||
);
|
||||
match LoudnessCache::in_memory() {
|
||||
Ok(c) => Arc::new(c),
|
||||
Err(e2) => {
|
||||
log::error!(
|
||||
"In-memory loudness cache failed too: {e2}. \
|
||||
Normalization analyses will not be cached at all."
|
||||
);
|
||||
Arc::new(LoudnessCache::disabled())
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let _analyzer_handle = LoudnessAnalyzer::spawn(analyzer_rx, loudness_cache.clone());
|
||||
@@ -7494,6 +7517,23 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The streaming sources turn these into `NonZero` with an `unwrap` on the
|
||||
/// audio thread; a demuxer reporting `Some(0)` or an empty channel mask
|
||||
/// must fail here instead.
|
||||
#[test]
|
||||
fn codec_params_with_a_zero_rate_or_no_channels_are_rejected_before_nonzero() {
|
||||
use symphonia::core::audio::Channels;
|
||||
use symphonia::core::codecs::{CodecParameters, CODEC_TYPE_FLAC};
|
||||
let mut params = CodecParameters::new();
|
||||
params.for_codec(CODEC_TYPE_FLAC).with_sample_rate(0);
|
||||
assert!(super::audio_metadata_from_codec_params(¶ms).is_err());
|
||||
params.with_sample_rate(44100).with_channels(Channels::empty());
|
||||
assert!(super::audio_metadata_from_codec_params(¶ms).is_err());
|
||||
params.with_channels(Channels::FRONT_LEFT | Channels::FRONT_RIGHT);
|
||||
let meta = super::audio_metadata_from_codec_params(¶ms).unwrap();
|
||||
assert_eq!((meta.sample_rate, meta.channels), (44100, 2));
|
||||
}
|
||||
|
||||
struct FakeDsdSource {
|
||||
words: std::vec::IntoIter<i32>,
|
||||
error: Option<String>,
|
||||
|
||||
@@ -568,7 +568,9 @@ impl PlaybackEngine {
|
||||
is_playing.store(false, Ordering::SeqCst);
|
||||
|
||||
if let Some(handle) = playback_thread.take() {
|
||||
let _ = handle.join();
|
||||
if handle.join().is_err() {
|
||||
log::error!("[{label}] playback thread panicked before stop completed");
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = stream.stop() {
|
||||
@@ -589,7 +591,9 @@ impl PlaybackEngine {
|
||||
should_stop.store(true, Ordering::SeqCst);
|
||||
is_playing.store(false, Ordering::SeqCst);
|
||||
if let Some(handle) = feeder_thread.take() {
|
||||
let _ = handle.join();
|
||||
if handle.join().is_err() {
|
||||
log::error!("[JACK Engine] feeder thread panicked before stop completed");
|
||||
}
|
||||
}
|
||||
// JackStream's Drop deactivates the client + unregisters the ports.
|
||||
}
|
||||
@@ -608,7 +612,9 @@ impl PlaybackEngine {
|
||||
should_stop.store(true, Ordering::SeqCst);
|
||||
is_playing.store(false, Ordering::SeqCst);
|
||||
if let Some(handle) = writer_thread.take() {
|
||||
let _ = handle.join();
|
||||
if handle.join().is_err() {
|
||||
log::error!("[DoP Engine] writer thread panicked before stop completed");
|
||||
}
|
||||
}
|
||||
if let Err(e) = stream.stop() {
|
||||
log::warn!("[DoP Engine] Stop failed: {}", e);
|
||||
|
||||
@@ -459,80 +459,11 @@ fn parsed_request_headers(
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
/// Return a bounded, URL-free diagnostic for a reqwest failure.
|
||||
///
|
||||
/// The raw error and its source chain can contain a signed CDN URL. Inspect the
|
||||
/// chain only to preserve header-limit classification; never copy an arbitrary
|
||||
/// cause into logs or a returned error.
|
||||
pub fn describe_reqwest_error(err: &reqwest::Error) -> String {
|
||||
if error_chain_has_header_limit(err) {
|
||||
return safe_transport_diagnostic("message head is too large").to_string();
|
||||
}
|
||||
|
||||
if err.is_timeout() {
|
||||
"HTTP transport timed out".to_string()
|
||||
} else if err.is_connect() {
|
||||
"HTTP transport connection failed".to_string()
|
||||
} else if err.is_body() {
|
||||
"HTTP response body failed".to_string()
|
||||
} else if err.is_decode() {
|
||||
"HTTP response decode failed".to_string()
|
||||
} else if err.is_status() {
|
||||
"HTTP status rejected".to_string()
|
||||
} else {
|
||||
"HTTP transport request failed".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn error_chain_has_header_limit(err: &reqwest::Error) -> bool {
|
||||
use std::error::Error as _;
|
||||
|
||||
if is_header_flood_error(&err.to_string()) {
|
||||
return true;
|
||||
}
|
||||
let mut source = err.source();
|
||||
while let Some(cause) = source {
|
||||
if is_header_flood_error(&cause.to_string()) {
|
||||
return true;
|
||||
}
|
||||
source = cause.source();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn safe_transport_diagnostic(message: &str) -> &'static str {
|
||||
if is_header_flood_error(message) {
|
||||
"HTTP response header limit exceeded (message head is too large)"
|
||||
} else {
|
||||
"HTTP transport request failed"
|
||||
}
|
||||
}
|
||||
|
||||
/// True when an error message (already chain-expanded by
|
||||
/// [`describe_reqwest_error`]) shows hyper's hard-coded h1 100-header cap.
|
||||
/// Akamai answers SMALL raw-url objects with ~106 headers (the `X-AK-GRN` /
|
||||
/// `X-AK-FWD-ERROR: ERR_POC_FWD_OBJ_TOO_SMALL` flood), so EVERY reqwest fetch
|
||||
/// of such an URL fails this way — streaming probe and full download alike.
|
||||
pub fn is_header_flood_error(message: &str) -> bool {
|
||||
let haystack = message.to_ascii_lowercase();
|
||||
haystack.contains("message head is too large") || haystack.contains("too many headers")
|
||||
}
|
||||
pub use qbz_qobuz::net_diag::{describe_reqwest_error, is_header_flood_error};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
content_range_total, parsed_request_headers, probe_content_length,
|
||||
safe_transport_diagnostic,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn transport_diagnostic_never_echoes_signed_url() {
|
||||
let marker = "https://cdn.example/audio.flac?jwt=secret&request_sig=signed";
|
||||
let diagnostic = safe_transport_diagnostic(marker);
|
||||
assert_eq!(diagnostic, "HTTP transport request failed");
|
||||
assert!(!diagnostic.contains(marker));
|
||||
assert!(!diagnostic.contains("secret"));
|
||||
}
|
||||
use super::{content_range_total, parsed_request_headers, probe_content_length};
|
||||
|
||||
#[test]
|
||||
fn source_request_headers_are_parsed_for_the_http_request() {
|
||||
|
||||
@@ -40,6 +40,7 @@ pub mod error;
|
||||
pub mod forbidden_breaker;
|
||||
pub mod link_resolver;
|
||||
pub mod lyrics;
|
||||
pub mod net_diag;
|
||||
pub mod offline_gate;
|
||||
pub mod performers;
|
||||
pub mod purchases;
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
//! URL-free diagnostics for reqwest failures.
|
||||
//!
|
||||
//! `reqwest::Error`'s `Display` embeds the full request URL, and the URLs this
|
||||
//! crate fetches carry signed, short-lived CDN tokens (`hmac=` on the Qobuz
|
||||
//! file CDN, `Signature=` / `Key-Pair-Id=` on CloudFront). Nothing in a log
|
||||
//! line or a returned error string may carry them. Moved here from
|
||||
//! `qbz-player/src/remote_stream.rs` so the CMAF fetch path
|
||||
//! (`retry::classify_reqwest`) uses the same helper as the legacy stream path.
|
||||
|
||||
/// Return a bounded, URL-free diagnostic for a reqwest failure.
|
||||
///
|
||||
/// The raw error and its source chain can contain a signed CDN URL. Inspect the
|
||||
/// chain only to preserve header-limit classification; never copy an arbitrary
|
||||
/// cause into logs or a returned error.
|
||||
pub fn describe_reqwest_error(err: &reqwest::Error) -> String {
|
||||
if error_chain_has_header_limit(err) {
|
||||
return safe_transport_diagnostic("message head is too large").to_string();
|
||||
}
|
||||
|
||||
if err.is_timeout() {
|
||||
"HTTP transport timed out".to_string()
|
||||
} else if err.is_connect() {
|
||||
"HTTP transport connection failed".to_string()
|
||||
} else if err.is_body() {
|
||||
"HTTP response body failed".to_string()
|
||||
} else if err.is_decode() {
|
||||
"HTTP response decode failed".to_string()
|
||||
} else if err.is_status() {
|
||||
"HTTP status rejected".to_string()
|
||||
} else {
|
||||
"HTTP transport request failed".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn error_chain_has_header_limit(err: &reqwest::Error) -> bool {
|
||||
use std::error::Error as _;
|
||||
|
||||
if is_header_flood_error(&err.to_string()) {
|
||||
return true;
|
||||
}
|
||||
let mut source = err.source();
|
||||
while let Some(cause) = source {
|
||||
if is_header_flood_error(&cause.to_string()) {
|
||||
return true;
|
||||
}
|
||||
source = cause.source();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn safe_transport_diagnostic(message: &str) -> &'static str {
|
||||
if is_header_flood_error(message) {
|
||||
"HTTP response header limit exceeded (message head is too large)"
|
||||
} else {
|
||||
"HTTP transport request failed"
|
||||
}
|
||||
}
|
||||
|
||||
/// True when an error message (already chain-expanded by
|
||||
/// [`describe_reqwest_error`]) shows hyper's hard-coded h1 100-header cap.
|
||||
/// Akamai answers SMALL raw-url objects with ~106 headers (the `X-AK-GRN` /
|
||||
/// `X-AK-FWD-ERROR: ERR_POC_FWD_OBJ_TOO_SMALL` flood), so EVERY reqwest fetch
|
||||
/// of such an URL fails this way — streaming probe and full download alike.
|
||||
pub fn is_header_flood_error(message: &str) -> bool {
|
||||
let haystack = message.to_ascii_lowercase();
|
||||
haystack.contains("message head is too large") || haystack.contains("too many headers")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn transport_diagnostic_never_echoes_signed_url() {
|
||||
let marker = "https://cdn.example/audio.flac?jwt=secret&request_sig=signed";
|
||||
let diagnostic = safe_transport_diagnostic(marker);
|
||||
assert_eq!(diagnostic, "HTTP transport request failed");
|
||||
assert!(!diagnostic.contains(marker));
|
||||
assert!(!diagnostic.contains("secret"));
|
||||
}
|
||||
|
||||
/// The CMAF path: a real reqwest failure (connection refused) whose
|
||||
/// Display embeds the signed URL must classify without it.
|
||||
#[tokio::test]
|
||||
async fn classify_reqwest_never_echoes_the_request_url() {
|
||||
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
|
||||
let port = {
|
||||
let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
probe.local_addr().unwrap().port()
|
||||
}; // dropped: nothing listens on `port` now
|
||||
let url = format!("http://127.0.0.1:{port}/file?eid=1&hmac=SIGNEDSECRET&etsp=1");
|
||||
let err = reqwest::Client::new().get(&url).send().await.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("SIGNEDSECRET"),
|
||||
"precondition: reqwest's Display embeds the url: {err}"
|
||||
);
|
||||
|
||||
assert_eq!(describe_reqwest_error(&err), "HTTP transport connection failed");
|
||||
let classified = crate::retry::classify_reqwest(&err, "fetch").to_string();
|
||||
assert_eq!(classified, "fetch: HTTP transport connection failed");
|
||||
assert!(!classified.contains("SIGNEDSECRET"));
|
||||
assert!(!classified.contains("127.0.0.1"));
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,14 @@ pub fn reqwest_is_transient(e: &reqwest::Error) -> bool {
|
||||
/// are treated as transient — a definitive "gone" answer comes back as a 404
|
||||
/// *status*, not a transport error.
|
||||
pub fn classify_reqwest(e: &reqwest::Error, context: &str) -> FetchError {
|
||||
FetchError::Transient(format!("{}: {}", context, e))
|
||||
// reqwest's Display embeds the full request URL, and CDN URLs carry a
|
||||
// signed token; this string is logged on every retry and bubbles up to
|
||||
// the player's warn lines. Describe the class, never the URL.
|
||||
FetchError::Transient(format!(
|
||||
"{}: {}",
|
||||
context,
|
||||
crate::net_diag::describe_reqwest_error(e)
|
||||
))
|
||||
}
|
||||
|
||||
/// Classify a non-success HTTP status into a `FetchError`. 5xx and 429 are
|
||||
|
||||
@@ -186,8 +186,12 @@ Rectangle {
|
||||
Text {
|
||||
visible: root.arm !== "dismissed"
|
||||
width: parent.width
|
||||
// Unix seconds from the store, formatted in the user's
|
||||
// locale here (the Rust side carries no month names).
|
||||
text: QbzSession.tr("Added {}", QbzSession.trRev)
|
||||
.replace("{}", root.row.addedDisplay || "")
|
||||
.replace("{}", (root.row.addedAt || 0) > 0
|
||||
? Qt.formatDate(new Date(root.row.addedAt * 1000), Locale.LongFormat)
|
||||
: "")
|
||||
color: theme.textMuted
|
||||
font.pixelSize: root.kioskHost
|
||||
? theme.fontLegal * 1.2 : theme.fontLegal
|
||||
|
||||
@@ -132,6 +132,12 @@ Item {
|
||||
if (v === "")
|
||||
return QbzSession.tr("What's new", QbzSession.trRev)
|
||||
var d = root.doc.date || ""
|
||||
// `date` is the release's civil date as written
|
||||
// (YYYY-MM-DD); render it in the user's locale.
|
||||
var m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(d)
|
||||
if (m)
|
||||
d = Qt.formatDate(new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])),
|
||||
Locale.LongFormat)
|
||||
return QbzSession.tr("What's new in v{}", QbzSession.trRev).replace("{}", v)
|
||||
+ (d === "" ? "" : " (" + d + ")")
|
||||
}
|
||||
|
||||
@@ -46,14 +46,18 @@
|
||||
//! the documented follow-up. No RGBA decode in Rust: QML `Image` decodes
|
||||
//! `file://` asynchronously and natively.
|
||||
//!
|
||||
//! ## Cache eviction — scaled derivatives only
|
||||
//! ## Cache eviction — both directories, once per run
|
||||
//!
|
||||
//! [`housekeeping`] bounds `~/.cache/qbz/images/scaled` (this module's OWN
|
||||
//! derivative directory) at [`MAX_SCALED_BYTES`], LRU by mtime, and does the
|
||||
//! one-time `.jpg` orphan sweep the `.png` key change left behind. The PARENT
|
||||
//! `~/.cache/qbz/images` is the SHARED cache and keeps its own policy
|
||||
//! (`qbz_cache::ImageCacheService`, SQLite `last_accessed` + the Slint app's
|
||||
//! 200 MB `evict`) — do NOT add a second one for it from here.
|
||||
//! [`housekeeping`] runs on the blocking pool at boot and bounds BOTH caches:
|
||||
//! the SHARED `~/.cache/qbz/images` (the full-size originals `store` writes;
|
||||
//! `qbz_cache::ImageCacheService`, SQLite `last_accessed` LRU, budget
|
||||
//! [`MAX_SHARED_BYTES`], trimmed in [`EVICT_BATCH_ENTRIES`]-row batches so the
|
||||
//! GUI thread is never parked behind a long unlink loop) and this module's
|
||||
//! OWN derivative directory `images/scaled` ([`MAX_SCALED_BYTES`], LRU by
|
||||
//! mtime, plus the one-time `.jpg` orphan sweep). The shared trim was the
|
||||
//! Slint app's `spawn_evict` (v2.0.2); it was retired with that frontend
|
||||
//! (69ed61207) and 2.1.0/2.1.1 shipped with NO caller of `evict` at all — the
|
||||
//! directory grew without bound.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -1229,6 +1233,38 @@ pub fn scaled_path(path: &str, w: u32, h: u32) -> Option<std::path::PathBuf> {
|
||||
/// order of magnitude under the 260 MB the parent image cache already holds.
|
||||
const MAX_SCALED_BYTES: u64 = 64 * 1024 * 1024;
|
||||
|
||||
/// Byte budget for the SHARED cache (`~/.cache/qbz/images`): the Slint app's
|
||||
/// `MAX_CACHE_BYTES` ("matches the Tauri default"), restored unchanged.
|
||||
const MAX_SHARED_BYTES: u64 = 200 * 1024 * 1024;
|
||||
|
||||
/// Rows deleted per `evict` call; the cache mutex is released between calls.
|
||||
const EVICT_BATCH_ENTRIES: usize = 64;
|
||||
|
||||
/// Trim the shared cache to `max_bytes`, LRU by `last_accessed`, in batches.
|
||||
/// Blocking (SQLite + unlinks) — call from `spawn_blocking`. Returns the
|
||||
/// bytes freed, `None` when the cache could not be opened (already logged).
|
||||
fn evict_shared(max_bytes: u64) -> Option<u64> {
|
||||
let cache = cache()?;
|
||||
let mut freed_total = 0u64;
|
||||
loop {
|
||||
let batch = {
|
||||
let guard = cache.lock().ok()?;
|
||||
match guard.evict(max_bytes, EVICT_BATCH_ENTRIES) {
|
||||
Ok(batch) => batch,
|
||||
Err(e) => {
|
||||
log::warn!("[qbz-qt] image cache eviction failed: {e}");
|
||||
return Some(freed_total);
|
||||
}
|
||||
}
|
||||
};
|
||||
freed_total += batch.freed_bytes;
|
||||
if batch.evicted_entries == 0 {
|
||||
return Some(freed_total);
|
||||
}
|
||||
std::thread::yield_now();
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep `scaled/` bounded: drop the oldest derivatives past
|
||||
/// [`MAX_SCALED_BYTES`]. Mtime order, oldest first — the same shape as
|
||||
/// `icon_tint_qt::prune`, with one deliberate difference: `prune` caps on a
|
||||
@@ -1302,16 +1338,18 @@ fn sweep_orphan_scaled(dir: &Path) -> (usize, u64) {
|
||||
(n, freed)
|
||||
}
|
||||
|
||||
/// Boot-time housekeeping for the derivative cache: the one-time `.jpg`
|
||||
/// orphan sweep, then the byte cap. Blocking (`read_dir` + unlinks) — call
|
||||
/// from `spawn_blocking`.
|
||||
///
|
||||
/// SCOPE: `images/scaled` ONLY. The parent `~/.cache/qbz/images` (260 MB) is
|
||||
/// the SHARED cache owned by `qbz_cache::ImageCacheService` (SQLite
|
||||
/// `last_accessed` + the Slint app's 200 MB `evict`); two processes evicting
|
||||
/// the same directory on different policies is exactly what the memo at the
|
||||
/// top of this file had to be written about.
|
||||
/// Boot-time housekeeping for both image caches — see the module doc
|
||||
/// "Cache eviction". Blocking; call from `spawn_blocking`.
|
||||
pub fn housekeeping() {
|
||||
// 1. The SHARED cache (full-size originals): LRU trim to the budget.
|
||||
if let Some(freed) = evict_shared(MAX_SHARED_BYTES) {
|
||||
if freed > 0 {
|
||||
log::info!(
|
||||
"[qbz-qt][perf] image cache evicted {freed} B (budget {MAX_SHARED_BYTES} B)"
|
||||
);
|
||||
}
|
||||
}
|
||||
// 2. This module's OWN derivative directory: orphan sweep, then byte cap.
|
||||
let Some(dir) = dirs::cache_dir().map(|d| d.join("qbz").join("images").join("scaled")) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -77,8 +77,6 @@ struct ArtistRowDoc {
|
||||
name: String,
|
||||
#[serde(rename = "addedAt")]
|
||||
added_at: i64,
|
||||
#[serde(rename = "addedDisplay")]
|
||||
added_display: String,
|
||||
notes: String,
|
||||
#[serde(rename = "hasNotes")]
|
||||
has_notes: bool,
|
||||
@@ -97,8 +95,6 @@ struct AlbumRowDoc {
|
||||
art_path: String,
|
||||
#[serde(rename = "addedAt")]
|
||||
added_at: i64,
|
||||
#[serde(rename = "addedDisplay")]
|
||||
added_display: String,
|
||||
/// Carried for shape parity with the artist row; the Slint `AlbumRow`
|
||||
/// renders `added-display` in that slot and never the notes.
|
||||
notes: String,
|
||||
@@ -159,47 +155,6 @@ fn set_query_value(q: String) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Date formatting — "%b %-d, %Y" without pulling `chrono` into this crate
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const MONTHS: [&str; 12] = [
|
||||
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
|
||||
];
|
||||
|
||||
/// Format a unix-SECONDS timestamp as `"MMM D, YYYY"` (English — `qbz_i18n` has
|
||||
/// no Rust-side date catalog, same as the reference). Byte-identical to the
|
||||
/// reference's `chrono` `"%b %-d, %Y"` on a UTC timestamp; `qbz-qt` has no
|
||||
/// `chrono` dependency, so the civil-date conversion is inlined below rather
|
||||
/// than adding one for one string.
|
||||
fn format_added(secs: i64) -> String {
|
||||
let days = secs.div_euclid(86_400);
|
||||
// The reference's `DateTime::from_timestamp` yields `None` outside its
|
||||
// range and renders "". Guard the same way for a corrupt row.
|
||||
if !(-100_000_000..=100_000_000).contains(&days) {
|
||||
return String::new();
|
||||
}
|
||||
let (year, month, day) = civil_from_days(days);
|
||||
format!("{} {}, {}", MONTHS[(month - 1) as usize], day, year)
|
||||
}
|
||||
|
||||
/// Howard Hinnant's `civil_from_days`: days since 1970-01-01 -> (year, month,
|
||||
/// day), pure integer arithmetic, valid for the whole proleptic Gregorian
|
||||
/// range. Truncating division with the era adjustment is the algorithm as
|
||||
/// published — do not "simplify" it to `div_euclid`.
|
||||
fn civil_from_days(days: i64) -> (i64, u32, u32) {
|
||||
let z = days + 719_468;
|
||||
let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
|
||||
let doe = z - era * 146_097; // [0, 146096]
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
|
||||
let y = yoe + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
|
||||
let mp = (5 * doy + 2) / 153; // [0, 11]
|
||||
let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
|
||||
(y + i64::from(m <= 2), m as u32, d as u32)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Builders — filtering is entirely Rust-side; QML never filters
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -221,7 +176,6 @@ fn build_artists() -> (Vec<ArtistRowDoc>, i32) {
|
||||
id: a.artist_id.to_string(),
|
||||
name: a.artist_name,
|
||||
added_at: a.added_at,
|
||||
added_display: format_added(a.added_at),
|
||||
has_notes: !notes.is_empty(),
|
||||
notes,
|
||||
}
|
||||
@@ -265,7 +219,6 @@ fn build_albums() -> (Vec<AlbumRowDoc>, i32, Vec<String>) {
|
||||
cover_url: a.cover_url,
|
||||
art_path,
|
||||
added_at: a.added_at,
|
||||
added_display: format_added(a.added_at),
|
||||
has_notes: !notes.is_empty(),
|
||||
notes,
|
||||
}
|
||||
@@ -779,34 +732,3 @@ fn emit_artwork(key: String, path: String) {
|
||||
.library_artwork_ready(QString::from(key.as_str()), QString::from(path.as_str()));
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn format_added_matches_chrono_b_d_y() {
|
||||
// Epoch itself.
|
||||
assert_eq!(format_added(0), "Jan 1, 1970");
|
||||
// No zero padding on the day (%-d), month abbreviated (%b).
|
||||
assert_eq!(format_added(1_751_500_000), "Jul 2, 2025");
|
||||
// Leap day.
|
||||
assert_eq!(format_added(1_709_164_800), "Feb 29, 2024");
|
||||
// A December date, i.e. the mp >= 10 branch of civil_from_days.
|
||||
assert_eq!(format_added(1_735_689_599), "Dec 31, 2024");
|
||||
// Pre-epoch (floor division, not truncation).
|
||||
assert_eq!(format_added(-1), "Dec 31, 1969");
|
||||
// A corrupt value renders empty rather than a bogus date.
|
||||
assert_eq!(format_added(i64::MAX), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn civil_from_days_month_boundaries() {
|
||||
assert_eq!(civil_from_days(0), (1970, 1, 1));
|
||||
// 1972-01-01 is day 730 (two 365-day years); +59 lands on the first
|
||||
// leap day after the epoch, +60 on the day after it.
|
||||
assert_eq!(civil_from_days(730), (1972, 1, 1));
|
||||
assert_eq!(civil_from_days(730 + 59), (1972, 2, 29));
|
||||
assert_eq!(civil_from_days(730 + 60), (1972, 3, 1));
|
||||
}
|
||||
}
|
||||
@@ -3982,6 +3982,11 @@ fn proxy_client() -> &'static reqwest::Client {
|
||||
PROXY_HTTP.get_or_init(|| {
|
||||
reqwest::Client::builder()
|
||||
.connect_timeout(std::time::Duration::from_secs(10))
|
||||
// A source server (Plex / Jellyfin / Subsonic) that stops
|
||||
// answering mid-body used to park the media server's request
|
||||
// thread in `BodyReader::read` forever. Per-read and reset on
|
||||
// progress, so a slow-but-alive stream is never cut.
|
||||
.read_timeout(std::time::Duration::from_secs(30))
|
||||
.build()
|
||||
.unwrap_or_default()
|
||||
})
|
||||
|
||||
@@ -721,11 +721,10 @@ pub(crate) fn on_boot() {
|
||||
});
|
||||
offline_fwd::start_ui_forwarder();
|
||||
|
||||
// Derivative-cache housekeeping, off the Qt thread. Once per run: the
|
||||
// `.jpg` orphan sweep is idempotent (FIX 1 moved the scaled derivatives to
|
||||
// `.png`, so every `.jpg` left in `images/scaled/` is dead weight from a
|
||||
// pre-fix build) and the byte cap is cheap — one `read_dir`, then unlink
|
||||
// the oldest until the directory is back under the ceiling.
|
||||
// Image-cache housekeeping, off the Qt thread, once per run: the shared
|
||||
// `~/.cache/qbz/images` LRU trim (200 MB, batched under the cache mutex)
|
||||
// and the `images/scaled` orphan sweep + byte cap. See artwork_qt.rs
|
||||
// "Cache eviction".
|
||||
spawn(async {
|
||||
let _ = tokio::task::spawn_blocking(artwork_qt::housekeeping).await;
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
//!
|
||||
//! # Divergences from the reference
|
||||
//!
|
||||
//! - `format_release_date` is rewritten WITHOUT chrono (`qbz-qt` has no chrono
|
||||
//! - `release_date_iso` keeps only the civil date; QML formats it (`qbz-qt` has no chrono
|
||||
//! dependency and is not gaining one for a date the GitHub API always emits
|
||||
//! in a fixed RFC3339 shape). Same output, same raw-string fallback.
|
||||
//! - The blocks are plain `Serialize` structs instead of Slint model rows; the
|
||||
@@ -231,7 +231,7 @@ async fn fetch_release_for_version(version: &str) -> Option<FetchedRelease> {
|
||||
|
||||
Some(FetchedRelease {
|
||||
version: normalize_version_tag(&release.tag_name),
|
||||
date: format_release_date(&release.published_at),
|
||||
date: release_date_iso(&release.published_at),
|
||||
body: release.body,
|
||||
})
|
||||
}
|
||||
@@ -240,34 +240,25 @@ fn normalize_version_tag(tag: &str) -> String {
|
||||
tag.trim().trim_start_matches('v').to_string()
|
||||
}
|
||||
|
||||
const MONTHS: [&str; 12] = [
|
||||
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
|
||||
];
|
||||
|
||||
/// Format an RFC3339 timestamp as "Mon D, YYYY" (en-US short). Falls back to
|
||||
/// the raw string on anything malformed.
|
||||
///
|
||||
/// CHRONO-FREE (the reference uses `DateTime::parse_from_rfc3339`, and this
|
||||
/// crate has no chrono dependency). GitHub's `published_at` is always
|
||||
/// `YYYY-MM-DDTHH:MM:SSZ`, and chrono's `year()/month0()/day()` on a parsed
|
||||
/// `DateTime<FixedOffset>` report the date AS WRITTEN in the string — so
|
||||
/// slicing the first ten ASCII bytes is behaviour-identical, offset included.
|
||||
fn format_release_date(iso: &str) -> String {
|
||||
/// Reduce GitHub's RFC3339 `published_at` to its civil date AS WRITTEN
|
||||
/// (`YYYY-MM-DD`, offset ignored — the reference's chrono
|
||||
/// `year()/month0()/day()` on a parsed `DateTime<FixedOffset>` did the same).
|
||||
/// Display formatting happens in QML with `Qt.formatDate(..., Locale.LongFormat)`
|
||||
/// so the header follows the user's locale instead of an English month table.
|
||||
/// Malformed input is echoed verbatim.
|
||||
fn release_date_iso(iso: &str) -> String {
|
||||
let bytes = iso.as_bytes();
|
||||
if bytes.len() < 10 || bytes[4] != b'-' || bytes[7] != b'-' {
|
||||
return iso.to_string();
|
||||
}
|
||||
let num = |a: usize, b: usize| iso[a..b].parse::<u32>().ok();
|
||||
let (Some(year), Some(month), Some(day)) = (num(0, 4), num(5, 7), num(8, 10)) else {
|
||||
let (Some(_year), Some(month), Some(day)) = (num(0, 4), num(5, 7), num(8, 10)) else {
|
||||
return iso.to_string();
|
||||
};
|
||||
let Some(month_name) = month
|
||||
.checked_sub(1)
|
||||
.and_then(|m| MONTHS.get(m as usize).copied())
|
||||
else {
|
||||
if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
|
||||
return iso.to_string();
|
||||
};
|
||||
format!("{month_name} {day}, {year}")
|
||||
}
|
||||
iso[..10].to_string()
|
||||
}
|
||||
|
||||
// ==================== Markdown → blocks + TOC ====================
|
||||
@@ -603,21 +594,17 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_dates_format_like_the_reference_and_fall_back_raw() {
|
||||
assert_eq!(format_release_date("2026-07-04T18:22:01Z"), "Jul 4, 2026");
|
||||
assert_eq!(
|
||||
format_release_date("2026-12-31T00:00:00+02:00"),
|
||||
"Dec 31, 2026"
|
||||
);
|
||||
assert_eq!(format_release_date("2026-01-09T00:00:00Z"), "Jan 9, 2026");
|
||||
fn release_dates_reduce_to_their_civil_date_and_fall_back_raw() {
|
||||
assert_eq!(release_date_iso("2026-07-04T18:22:01Z"), "2026-07-04");
|
||||
// The date AS WRITTEN, offset ignored (chrono's year()/month0()/day()
|
||||
// on a parsed DateTime<FixedOffset> behave the same).
|
||||
assert_eq!(release_date_iso("2026-12-31T00:00:00+02:00"), "2026-12-31");
|
||||
assert_eq!(release_date_iso("2026-01-09T00:00:00Z"), "2026-01-09");
|
||||
// Malformed input is echoed verbatim, never blanked.
|
||||
assert_eq!(format_release_date("not a date"), "not a date");
|
||||
assert_eq!(format_release_date("2026/07/04"), "2026/07/04");
|
||||
assert_eq!(
|
||||
format_release_date("2026-13-04T00:00:00Z"),
|
||||
"2026-13-04T00:00:00Z"
|
||||
);
|
||||
assert_eq!(format_release_date(""), "");
|
||||
assert_eq!(release_date_iso("not a date"), "not a date");
|
||||
assert_eq!(release_date_iso("2026/07/04"), "2026/07/04");
|
||||
assert_eq!(release_date_iso("2026-13-04T00:00:00Z"), "2026-13-04T00:00:00Z");
|
||||
assert_eq!(release_date_iso(""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -136,11 +136,18 @@ pub fn foreign_qbzd(addr: &str) -> String {
|
||||
/// `warning:` — an open LAN renderer (Sonos/Chromecast posture) is the
|
||||
/// intended default, the Origin shield already guards browsers, and this line
|
||||
/// just orients the operator toward the two ways to restrict it further.
|
||||
/// `addr` is the bound `ip:port`.
|
||||
pub fn lan_posture_note(addr: &str) -> String {
|
||||
format!(
|
||||
"control plane listening on {addr} — anyone on your network can control playback (set [server] bind = \"127.0.0.1\" or [server] token in qbzd.toml to restrict)"
|
||||
)
|
||||
/// With `[server] token` set the API is already gated, so the line says that
|
||||
/// instead of nagging. `addr` is the bound `ip:port`.
|
||||
pub fn lan_posture_note(addr: &str, token_set: bool) -> String {
|
||||
if token_set {
|
||||
format!(
|
||||
"control plane listening on {addr} — LAN clients must send the [server] token (Authorization: Bearer)"
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"control plane listening on {addr} — anyone on your network can control playback (set [server] bind = \"127.0.0.1\" or [server] token in qbzd.toml to restrict)"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Version skew — daemon and CLI run different bin semvers (02 §1.6). A warning:
|
||||
@@ -234,11 +241,12 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lan_posture_note_renders_the_verbatim_copy() {
|
||||
fn lan_posture_note_renders_the_verbatim_copy_when_the_api_is_open() {
|
||||
// FB6 (successor to the old LAN-exposure warning) — one INFO line logged
|
||||
// by the daemon at boot when the control API is NOT loopback-only. This
|
||||
// test pins the exact wording so it cannot drift from the spec.
|
||||
let rendered = lan_posture_note("0.0.0.0:6789");
|
||||
// by the daemon at boot when the control API is NOT loopback-only and
|
||||
// no token gates it. This test pins the exact wording so it cannot
|
||||
// drift from the spec.
|
||||
let rendered = lan_posture_note("0.0.0.0:6789", false);
|
||||
assert!(
|
||||
rendered.contains("control plane listening on 0.0.0.0:6789"),
|
||||
"{rendered}"
|
||||
@@ -253,4 +261,18 @@ mod tests {
|
||||
"{rendered}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lan_posture_note_with_a_token_does_not_nag() {
|
||||
let rendered = lan_posture_note("0.0.0.0:6789", true);
|
||||
assert!(
|
||||
rendered.contains("control plane listening on 0.0.0.0:6789"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(rendered.contains("[server] token"), "{rendered}");
|
||||
assert!(
|
||||
!rendered.contains("anyone on your network"),
|
||||
"a gated API must not be described as open: {rendered}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -40,8 +40,9 @@ pub struct BootedRuntime {
|
||||
/// gracefully. Returns the process exit code (0 = clean shutdown). `warns` are
|
||||
/// the unknown-key warnings surfaced by [`QbzdConfig::load`] in `main`.
|
||||
pub async fn run(roots: ProfileRoots, cfg: QbzdConfig, warns: Vec<String>, orbit: bool) -> Result<i32, String> {
|
||||
// 1. argv parse happened in main(). 2. logging:
|
||||
qbz_log::install(&cfg.log.level);
|
||||
// 1. argv parse happened in main(). 2. logging — to its OWN file, never
|
||||
// the desktop app's (a shared qbz.log was rotated from under the GUI):
|
||||
qbz_log::install_named(&cfg.log.level, "qbzd.log");
|
||||
// A headless daemon that dies of a signal leaves even less behind than
|
||||
// the GUI does: no window, no user watching. Same reporter, same reason
|
||||
// (qbz-log/src/fatal.rs).
|
||||
@@ -88,7 +89,15 @@ pub async fn run(roots: ProfileRoots, cfg: QbzdConfig, warns: Vec<String>, orbit
|
||||
// FB6: the default bind is now 0.0.0.0 — LAN-first posture (Sonos/
|
||||
// Chromecast parity), not a misconfiguration. One INFO line, not a
|
||||
// stderr warning; loopback binds stay silent.
|
||||
log::info!("{}", crate::cli::copy::lan_posture_note(&bind_addr.to_string()));
|
||||
let token_set = cfg
|
||||
.server
|
||||
.token
|
||||
.as_deref()
|
||||
.is_some_and(|t| !t.trim().is_empty());
|
||||
log::info!(
|
||||
"{}",
|
||||
crate::cli::copy::lan_posture_note(&bind_addr.to_string(), token_set)
|
||||
);
|
||||
}
|
||||
|
||||
// 6.-9. compose stores + runtime + restore credentials + restore session.
|
||||
|
||||
@@ -82,6 +82,27 @@ budgets exclude active streaming buffers, decoders and offline downloads. The
|
||||
policy applies live without reopening the output device.
|
||||
|
||||
|
||||
## Network access
|
||||
|
||||
By default `qbzd run` listens on `0.0.0.0:8182`: any device on your network
|
||||
can control playback, the queue and your playlists, the same way a Sonos or
|
||||
Chromecast renderer is open on the LAN. Browsers are blocked by an Origin
|
||||
check; other programs are not. The daemon logs one line about this at boot.
|
||||
|
||||
To restrict it, edit `~/.config/qbzd/qbzd.toml`:
|
||||
|
||||
```toml
|
||||
[server]
|
||||
bind = "127.0.0.1" # local clients only
|
||||
# or keep the LAN bind and require a token on every request:
|
||||
token = "choose-a-long-random-string"
|
||||
```
|
||||
|
||||
With a token set, clients send `Authorization: Bearer <token>`; the `qbzd`
|
||||
CLI on the same machine picks it up from `qbzd.toml` automatically (or from
|
||||
`QBZD_TOKEN`). `qbzd setup` has the same field on its Network screen
|
||||
("Access token").
|
||||
|
||||
## OpenRC and runit
|
||||
|
||||
Do not reuse the systemd unit on a non-systemd host. `qbzd` generates a
|
||||
|
||||
+21
-1
@@ -167,7 +167,7 @@ say "gate: account-migration and portable-blacklist suites present and green"
|
||||
# blacklist_portable is the JSON one user hands to another.
|
||||
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-account-migration --lib -- --list 2>/dev/null \
|
||||
| grep -c ': test$' || true)
|
||||
(( n >= 12 )) || { echo "qbz-account-migration has $n tests (expected >= 12)"; exit 1; }
|
||||
(( n >= 13 )) || { echo "qbz-account-migration has $n tests (expected >= 13)"; exit 1; }
|
||||
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-app --lib -- --list blacklist_portable:: 2>/dev/null \
|
||||
| grep -c ': test$' || true)
|
||||
(( n >= 3 )) || { echo "blacklist_portable suite has $n tests (expected >= 3)"; exit 1; }
|
||||
@@ -200,6 +200,26 @@ cargo test --manifest-path crates/Cargo.toml -p qconnect-app --lib -- queue_reso
|
||||
cargo test --manifest-path crates/Cargo.toml -p qconnect-protocol --lib -- decoder::tests::controller_
|
||||
cargo test --manifest-path crates/Cargo.toml -p qbz-log --lib -- repeat::tests::
|
||||
|
||||
say "gate: 2026-09 static-review regressions present (image-cache LRU, loudness-cache degrade, log-rotation lock, URL-free CDN errors + signed-param redaction, link-resolver timeout)"
|
||||
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-cache --lib -- --list image_cache::tests:: 2>/dev/null \
|
||||
| grep -c ': test$' || true)
|
||||
(( n >= 4 )) || { echo "image cache suite has $n tests (expected >= 4)"; exit 1; }
|
||||
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-audio --lib -- --list loudness_cache::tests:: 2>/dev/null \
|
||||
| grep -c ': test$' || true)
|
||||
(( n >= 2 )) || { echo "loudness cache suite has $n tests (expected >= 2)"; exit 1; }
|
||||
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-log --lib -- --list install::tests:: 2>/dev/null \
|
||||
| grep -c ': test$' || true)
|
||||
(( n >= 3 )) || { echo "log rotation suite has $n tests (expected >= 3)"; exit 1; }
|
||||
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-log --lib -- --list redact::tests:: 2>/dev/null \
|
||||
| grep -c ': test$' || true)
|
||||
(( n >= 7 )) || { echo "redaction suite has $n tests (expected >= 7)"; exit 1; }
|
||||
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-qobuz --lib -- --list net_diag::tests:: 2>/dev/null \
|
||||
| grep -c ': test$' || true)
|
||||
(( n >= 2 )) || { echo "net_diag suite has $n tests (expected >= 2)"; exit 1; }
|
||||
n=$(cargo test --manifest-path crates/Cargo.toml -p qbz-music-link --lib -- --list fast_path::tests:: 2>/dev/null \
|
||||
| grep -c ': test$' || true)
|
||||
(( n >= 1 )) || { echo "link-resolver timeout suite has $n tests (expected >= 1)"; exit 1; }
|
||||
|
||||
say "gate: DLNA device-description tolerance present and green (#745)"
|
||||
# The local rupnp patch accepts legacy service URLs without downgrading http.
|
||||
# Invalid/oversized URLs must remain rejected.
|
||||
|
||||
Reference in new issue
Block a user