feat(app): shared offline-mode engine with connectivity actor and grace gate
New qbz_app::offline_mode (frontend-agnostic, ADR-006): three-state mode machine (Online / RealOffline session-scoped / InducedOffline persisted), Tauri-compatible offline_settings.db store with the issue #279 stream_first_track snapshot, and a layered connectivity actor (default-route signal on Linux, audio liveness window, IP-literal + vendor-diverse strict probes, asymmetric hysteresis with confirmation burst, captive-portal and suspend/resume handling). qbz-qobuz gains the process-wide offline_gate and ApiError::OfflineMode (the single Qobuz choke point; HTTP funnel wiring lands next). SubscriptionStateStore gains offline_playback_allowed: binary 30-day-grace playback gate for the offline cache, never a preview-degradation path. cc
This commit is contained in:
10 files changed
+1416
No files matched your search
@@ -1,4 +1,5 @@
|
||||
pub mod boot_watchdog;
|
||||
pub mod offline_mode;
|
||||
pub mod graphics_autoconfig;
|
||||
pub mod graphics_detection;
|
||||
pub mod playback_context;
|
||||
|
||||
@@ -0,0 +1,598 @@
|
||||
//! Connectivity actor — the robust replacement for Tauri's poll-only checker.
|
||||
//!
|
||||
//! Tauri's checker (issue #467 era) raced three hostname-based generate_204
|
||||
//! probes from a frontend `setInterval`, with a process-global 2-consecutive-
|
||||
//! failure counter. Its residual false-offline vectors (review report 02 §4):
|
||||
//! every probe needs DNS, two of three endpoints are Google infra (Pi-hole),
|
||||
//! unspaced counting defeats the hysteresis, nothing resets on suspend/resume,
|
||||
//! and captive-portal redirects count as ONLINE.
|
||||
//!
|
||||
//! This actor is Rust-owned and layered (spec §3.2):
|
||||
//!
|
||||
//! 1. **OS route signal (Linux)** — no IPv4/IPv6 default route ⇒ `Down`
|
||||
//! immediately, no probe needed (pulling the cable / wifi off detects in
|
||||
//! one tick instead of two failed 8s probes). Sandbox-safe `/proc` reads.
|
||||
//! 2. **Passive liveness** — audio bytes flowing within the last 45 s ⇒ `Up`
|
||||
//! by definition (`qbz_audio::network_throttle`), no probe traffic while
|
||||
//! streaming. Same rule as #467's Fix E.
|
||||
//! 3. **Hardened probe set** — one IP-LITERAL probe (DNS-independent — the
|
||||
//! DNS-hiccup false-offline vector dies here), vendor diversity (Cloudflare
|
||||
//! / Google / Microsoft), strict response validation, and redirects count
|
||||
//! as CAPTIVE PORTAL, never as success.
|
||||
//! 4. **Asymmetric hysteresis** — one confirmed success flips `Up` instantly;
|
||||
//! flipping `Down` from `Up` requires a fresh CONFIRMATION BURST (immediate
|
||||
//! short re-probes) so a single lost race never declares offline, and the
|
||||
//! confirmation is time-bounded (stale failures don't count).
|
||||
//! 5. **Suspend/resume guard** — a wall-clock jump without matching monotonic
|
||||
//! progress discards accumulated failures before judging.
|
||||
//!
|
||||
//! State broadcasts over a `tokio::sync::watch` channel; the offline-mode
|
||||
//! engine subscribes and derives the app mode from it.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Raw connectivity verdict, independent of the app's offline MODE.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Connectivity {
|
||||
Up,
|
||||
Down,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ConnectivitySnapshot {
|
||||
pub state: Connectivity,
|
||||
/// A probe was answered by a redirect — typical captive portal. Surfaced
|
||||
/// as a hint; the state is still `Down` (D3: a portal cannot reach Qobuz).
|
||||
pub captive_portal: bool,
|
||||
}
|
||||
|
||||
impl Default for ConnectivitySnapshot {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
state: Connectivity::Unknown,
|
||||
captive_portal: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a single probe endpoint decides success. Strict on purpose: Tauri
|
||||
/// accepted any 2xx/3xx, which read captive portals as online.
|
||||
enum ProbeExpect {
|
||||
/// Exactly HTTP 204, empty-ish body (generate_204 contract).
|
||||
Status204,
|
||||
/// HTTP 200 and the body contains the marker.
|
||||
BodyContains(&'static str),
|
||||
}
|
||||
|
||||
struct ProbeEndpoint {
|
||||
url: &'static str,
|
||||
expect: ProbeExpect,
|
||||
}
|
||||
|
||||
/// Vendor-diverse probe set. The first entry is IP-literal: it works with
|
||||
/// DNS completely broken, which was the most likely residual false-offline
|
||||
/// vector after #467 (all three old endpoints were hostname-based).
|
||||
const PROBES: &[ProbeEndpoint] = &[
|
||||
ProbeEndpoint {
|
||||
url: "https://1.1.1.1/cdn-cgi/trace",
|
||||
expect: ProbeExpect::BodyContains("ip="),
|
||||
},
|
||||
ProbeEndpoint {
|
||||
url: "https://connectivitycheck.gstatic.com/generate_204",
|
||||
expect: ProbeExpect::Status204,
|
||||
},
|
||||
ProbeEndpoint {
|
||||
url: "https://www.msftconnecttest.com/connecttest.txt",
|
||||
expect: ProbeExpect::BodyContains("Microsoft Connect Test"),
|
||||
},
|
||||
];
|
||||
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(8);
|
||||
/// Seconds of audio-segment silence within which we are online by definition.
|
||||
const LIVENESS_WINDOW_SECS: u64 = 45;
|
||||
/// Regular evaluation cadence while nothing changes.
|
||||
const POLL_INTERVAL: Duration = Duration::from_secs(30);
|
||||
/// Confirmation burst delays after a failed probe while `Up` (verify before
|
||||
/// flipping down — replaces Tauri's "2 polls ~60 s" with ~10 s of focused
|
||||
/// re-checking that can't be gamed by unspaced extra polls).
|
||||
const CONFIRM_DELAYS: [Duration; 2] = [Duration::from_secs(3), Duration::from_secs(7)];
|
||||
/// A wall-clock jump this much larger than monotonic progress = we slept.
|
||||
const RESUME_JUMP: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProbeOutcome {
|
||||
Success,
|
||||
/// All endpoints failed (timeout / error / wrong payload).
|
||||
Failure,
|
||||
/// At least one endpoint answered with a redirect and none succeeded.
|
||||
CaptivePortal,
|
||||
}
|
||||
|
||||
/// Pure decision core — injected outcomes, no sockets. Unit-testable.
|
||||
#[derive(Debug)]
|
||||
pub struct ConnectivityJudge {
|
||||
snapshot: ConnectivitySnapshot,
|
||||
/// Pending down-confirmation: how many burst steps are left.
|
||||
confirm_steps_left: usize,
|
||||
/// When the failing streak started (time-bounds the confirmation).
|
||||
first_failure_at: Option<Instant>,
|
||||
}
|
||||
|
||||
/// What the actor should do after feeding the judge.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum JudgeAction {
|
||||
/// Nothing pending — sleep until the next regular tick.
|
||||
Idle,
|
||||
/// Re-probe after the given delay (confirmation burst step).
|
||||
ConfirmAfter(Duration),
|
||||
}
|
||||
|
||||
impl ConnectivityJudge {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
snapshot: ConnectivitySnapshot::default(),
|
||||
confirm_steps_left: 0,
|
||||
first_failure_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> ConnectivitySnapshot {
|
||||
self.snapshot
|
||||
}
|
||||
|
||||
/// A definitive OS-level signal: no default route at all.
|
||||
pub fn on_no_route(&mut self) {
|
||||
self.confirm_steps_left = 0;
|
||||
self.first_failure_at = None;
|
||||
self.snapshot = ConnectivitySnapshot {
|
||||
state: Connectivity::Down,
|
||||
captive_portal: false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Audio bytes (or other Qobuz traffic) observed recently.
|
||||
pub fn on_liveness(&mut self) {
|
||||
self.confirm_steps_left = 0;
|
||||
self.first_failure_at = None;
|
||||
self.snapshot = ConnectivitySnapshot {
|
||||
state: Connectivity::Up,
|
||||
captive_portal: false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Discard any failing streak (suspend/resume, manual mode change).
|
||||
pub fn reset_streak(&mut self) {
|
||||
self.confirm_steps_left = 0;
|
||||
self.first_failure_at = None;
|
||||
}
|
||||
|
||||
pub fn on_probe(&mut self, outcome: ProbeOutcome, now: Instant) -> JudgeAction {
|
||||
match outcome {
|
||||
ProbeOutcome::Success => {
|
||||
// Asymmetric: one confirmed success flips Up instantly.
|
||||
self.confirm_steps_left = 0;
|
||||
self.first_failure_at = None;
|
||||
self.snapshot = ConnectivitySnapshot {
|
||||
state: Connectivity::Up,
|
||||
captive_portal: false,
|
||||
};
|
||||
JudgeAction::Idle
|
||||
}
|
||||
ProbeOutcome::Failure | ProbeOutcome::CaptivePortal => {
|
||||
let captive = outcome == ProbeOutcome::CaptivePortal;
|
||||
match self.snapshot.state {
|
||||
Connectivity::Up => {
|
||||
// Was up: never flip on one loss — start/advance the
|
||||
// confirmation burst.
|
||||
match self.first_failure_at {
|
||||
None => {
|
||||
self.first_failure_at = Some(now);
|
||||
self.confirm_steps_left = CONFIRM_DELAYS.len();
|
||||
}
|
||||
Some(start) => {
|
||||
// Time-bound: a stale streak (e.g. ticks that
|
||||
// straddled a suspend) restarts instead of
|
||||
// accumulating.
|
||||
if now.duration_since(start) > Duration::from_secs(120) {
|
||||
self.first_failure_at = Some(now);
|
||||
self.confirm_steps_left = CONFIRM_DELAYS.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.confirm_steps_left > 0 {
|
||||
let idx = CONFIRM_DELAYS.len() - self.confirm_steps_left;
|
||||
self.confirm_steps_left -= 1;
|
||||
JudgeAction::ConfirmAfter(CONFIRM_DELAYS[idx])
|
||||
} else {
|
||||
// Burst exhausted and still failing: confirmed down.
|
||||
self.snapshot = ConnectivitySnapshot {
|
||||
state: Connectivity::Down,
|
||||
captive_portal: captive,
|
||||
};
|
||||
self.first_failure_at = None;
|
||||
JudgeAction::Idle
|
||||
}
|
||||
}
|
||||
Connectivity::Down | Connectivity::Unknown => {
|
||||
// Already down (or first-ever verdict): no burst needed.
|
||||
self.snapshot = ConnectivitySnapshot {
|
||||
state: Connectivity::Down,
|
||||
captive_portal: captive,
|
||||
};
|
||||
JudgeAction::Idle
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ConnectivityJudge {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== OS route signal (Linux) =====================
|
||||
|
||||
/// Parse `/proc/net/route` content: any non-loopback entry with destination
|
||||
/// 00000000 is an IPv4 default route.
|
||||
fn ipv4_has_default_route(content: &str) -> bool {
|
||||
content.lines().skip(1).any(|line| {
|
||||
let mut cols = line.split_whitespace();
|
||||
let iface = cols.next().unwrap_or("");
|
||||
let dest = cols.next().unwrap_or("");
|
||||
iface != "lo" && dest == "00000000"
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse `/proc/net/ipv6_route` content: any non-loopback entry with
|
||||
/// destination ::/0 (32 zero hex chars, prefix length 00) is a default route.
|
||||
fn ipv6_has_default_route(content: &str) -> bool {
|
||||
content.lines().any(|line| {
|
||||
let cols: Vec<&str> = line.split_whitespace().collect();
|
||||
if cols.len() < 10 {
|
||||
return false;
|
||||
}
|
||||
let dest = cols[0];
|
||||
let prefix_len = cols[1];
|
||||
let iface = cols[9];
|
||||
iface != "lo"
|
||||
&& prefix_len == "00"
|
||||
&& dest.len() == 32
|
||||
&& dest.bytes().all(|b| b == b'0')
|
||||
})
|
||||
}
|
||||
|
||||
/// `Some(true)` = at least one default route exists; `Some(false)` = readable
|
||||
/// and definitely none; `None` = signal unavailable (non-Linux or read error)
|
||||
/// — the caller falls back to probes only.
|
||||
pub fn has_default_route() -> Option<bool> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let v4 = std::fs::read_to_string("/proc/net/route")
|
||||
.map(|c| ipv4_has_default_route(&c))
|
||||
.ok();
|
||||
let v6 = std::fs::read_to_string("/proc/net/ipv6_route")
|
||||
.map(|c| ipv6_has_default_route(&c))
|
||||
.ok();
|
||||
match (v4, v6) {
|
||||
(None, None) => None,
|
||||
(a, b) => Some(a.unwrap_or(false) || b.unwrap_or(false)),
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== Probing =====================
|
||||
|
||||
async fn probe_endpoint(client: &reqwest::Client, ep: &ProbeEndpoint) -> ProbeOutcome {
|
||||
match client.get(ep.url).send().await {
|
||||
Ok(response) => {
|
||||
let status = response.status();
|
||||
if status.is_redirection() {
|
||||
return ProbeOutcome::CaptivePortal;
|
||||
}
|
||||
match ep.expect {
|
||||
ProbeExpect::Status204 => {
|
||||
if status.as_u16() == 204 {
|
||||
ProbeOutcome::Success
|
||||
} else {
|
||||
ProbeOutcome::Failure
|
||||
}
|
||||
}
|
||||
ProbeExpect::BodyContains(marker) => {
|
||||
if status.as_u16() != 200 {
|
||||
return ProbeOutcome::Failure;
|
||||
}
|
||||
match response.text().await {
|
||||
Ok(body) if body.contains(marker) => ProbeOutcome::Success,
|
||||
_ => ProbeOutcome::Failure,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => ProbeOutcome::Failure,
|
||||
}
|
||||
}
|
||||
|
||||
/// Race the probe set; first validated success wins. Redirect answers are
|
||||
/// remembered: all-fail + any-redirect = captive portal.
|
||||
pub async fn probe_all(client: &reqwest::Client) -> ProbeOutcome {
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
for ep in PROBES {
|
||||
let client = client.clone();
|
||||
set.spawn(async move { probe_endpoint(&client, ep).await });
|
||||
}
|
||||
|
||||
let mut saw_captive = false;
|
||||
while let Some(joined) = set.join_next().await {
|
||||
match joined {
|
||||
Ok(ProbeOutcome::Success) => {
|
||||
set.abort_all();
|
||||
return ProbeOutcome::Success;
|
||||
}
|
||||
Ok(ProbeOutcome::CaptivePortal) => saw_captive = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if saw_captive {
|
||||
ProbeOutcome::CaptivePortal
|
||||
} else {
|
||||
ProbeOutcome::Failure
|
||||
}
|
||||
}
|
||||
|
||||
fn audio_liveness_recent() -> bool {
|
||||
qbz_audio::network_throttle::state()
|
||||
.seconds_since_download()
|
||||
.map(|secs| secs <= LIVENESS_WINDOW_SECS)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
// ===================== Actor =====================
|
||||
|
||||
/// Handle to the running actor: subscribe to state, poke a recheck.
|
||||
pub struct ConnectivityActor {
|
||||
rx: watch::Receiver<ConnectivitySnapshot>,
|
||||
recheck: tokio::sync::mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
impl ConnectivityActor {
|
||||
/// Spawn the actor loop on the current tokio runtime.
|
||||
pub fn spawn() -> Self {
|
||||
let (tx, rx) = watch::channel(ConnectivitySnapshot::default());
|
||||
let (recheck_tx, mut recheck_rx) = tokio::sync::mpsc::channel::<()>(4);
|
||||
|
||||
tokio::spawn(async move {
|
||||
let client = match reqwest::Client::builder()
|
||||
.timeout(PROBE_TIMEOUT)
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
{
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::error!("[Connectivity] probe client build failed: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let mut judge = ConnectivityJudge::new();
|
||||
let mut next_delay = Duration::from_millis(10); // first verdict ASAP
|
||||
let mut last_tick_wall = SystemTime::now();
|
||||
let mut last_tick_mono = Instant::now();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(next_delay) => {}
|
||||
poke = recheck_rx.recv() => {
|
||||
if poke.is_none() { return; }
|
||||
judge.reset_streak();
|
||||
}
|
||||
}
|
||||
|
||||
// Suspend/resume guard: wall-clock advanced much further than
|
||||
// the monotonic clock ⇒ we slept; discard the streak.
|
||||
let wall_delta = SystemTime::now()
|
||||
.duration_since(last_tick_wall)
|
||||
.unwrap_or_default();
|
||||
let mono_delta = last_tick_mono.elapsed();
|
||||
if wall_delta > mono_delta + RESUME_JUMP {
|
||||
log::info!("[Connectivity] resume detected, resetting failure streak");
|
||||
judge.reset_streak();
|
||||
}
|
||||
last_tick_wall = SystemTime::now();
|
||||
last_tick_mono = Instant::now();
|
||||
|
||||
// Layer 1: OS route signal — definitive Down.
|
||||
if has_default_route() == Some(false) {
|
||||
judge.on_no_route();
|
||||
let _ = tx.send_if_modified(|s| {
|
||||
let changed = *s != judge.snapshot();
|
||||
*s = judge.snapshot();
|
||||
changed
|
||||
});
|
||||
next_delay = Duration::from_secs(3); // cheap; watch for the route to return
|
||||
continue;
|
||||
}
|
||||
|
||||
// Layer 2: passive liveness — definitive Up, zero traffic.
|
||||
if audio_liveness_recent() {
|
||||
judge.on_liveness();
|
||||
let _ = tx.send_if_modified(|s| {
|
||||
let changed = *s != judge.snapshot();
|
||||
*s = judge.snapshot();
|
||||
changed
|
||||
});
|
||||
next_delay = POLL_INTERVAL;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Layer 3: probe + hysteresis.
|
||||
let outcome = probe_all(&client).await;
|
||||
let action = judge.on_probe(outcome, Instant::now());
|
||||
let _ = tx.send_if_modified(|s| {
|
||||
let changed = *s != judge.snapshot();
|
||||
*s = judge.snapshot();
|
||||
changed
|
||||
});
|
||||
next_delay = match action {
|
||||
JudgeAction::ConfirmAfter(delay) => delay,
|
||||
JudgeAction::Idle => POLL_INTERVAL,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
rx,
|
||||
recheck: recheck_tx,
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscribe to connectivity state changes.
|
||||
pub fn subscribe(&self) -> watch::Receiver<ConnectivitySnapshot> {
|
||||
self.rx.clone()
|
||||
}
|
||||
|
||||
/// Current snapshot without subscribing.
|
||||
pub fn snapshot(&self) -> ConnectivitySnapshot {
|
||||
*self.rx.borrow()
|
||||
}
|
||||
|
||||
/// Force an immediate re-evaluation (Settings "Check now", resume hooks,
|
||||
/// mode changes). Also clears any failing streak first.
|
||||
pub fn request_recheck(&self) {
|
||||
let _ = self.recheck.try_send(());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn now() -> Instant {
|
||||
Instant::now()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_success_goes_up_immediately() {
|
||||
let mut judge = ConnectivityJudge::new();
|
||||
assert_eq!(judge.on_probe(ProbeOutcome::Success, now()), JudgeAction::Idle);
|
||||
assert_eq!(judge.snapshot().state, Connectivity::Up);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_failure_while_up_does_not_flip_down() {
|
||||
let mut judge = ConnectivityJudge::new();
|
||||
judge.on_probe(ProbeOutcome::Success, now());
|
||||
|
||||
let action = judge.on_probe(ProbeOutcome::Failure, now());
|
||||
assert!(matches!(action, JudgeAction::ConfirmAfter(_)));
|
||||
assert_eq!(
|
||||
judge.snapshot().state,
|
||||
Connectivity::Up,
|
||||
"must stay Up during the confirmation burst"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exhausted_confirmation_burst_flips_down() {
|
||||
let mut judge = ConnectivityJudge::new();
|
||||
judge.on_probe(ProbeOutcome::Success, now());
|
||||
|
||||
// burst steps: CONFIRM_DELAYS.len() ConfirmAfter actions, then Down.
|
||||
let mut flips = 0;
|
||||
for _ in 0..(CONFIRM_DELAYS.len() + 1) {
|
||||
if judge.on_probe(ProbeOutcome::Failure, now()) == JudgeAction::Idle {
|
||||
flips += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(flips, 1);
|
||||
assert_eq!(judge.snapshot().state, Connectivity::Down);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_mid_burst_cancels_the_flip() {
|
||||
let mut judge = ConnectivityJudge::new();
|
||||
judge.on_probe(ProbeOutcome::Success, now());
|
||||
judge.on_probe(ProbeOutcome::Failure, now());
|
||||
judge.on_probe(ProbeOutcome::Success, now());
|
||||
assert_eq!(judge.snapshot().state, Connectivity::Up);
|
||||
|
||||
// The next failure starts a FRESH burst (streak was reset).
|
||||
let action = judge.on_probe(ProbeOutcome::Failure, now());
|
||||
assert!(matches!(action, JudgeAction::ConfirmAfter(_)));
|
||||
assert_eq!(judge.snapshot().state, Connectivity::Up);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn down_recovers_on_single_success() {
|
||||
let mut judge = ConnectivityJudge::new();
|
||||
judge.on_probe(ProbeOutcome::Failure, now());
|
||||
assert_eq!(judge.snapshot().state, Connectivity::Down);
|
||||
|
||||
judge.on_probe(ProbeOutcome::Success, now());
|
||||
assert_eq!(judge.snapshot().state, Connectivity::Up);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captive_portal_is_down_with_hint() {
|
||||
let mut judge = ConnectivityJudge::new();
|
||||
judge.on_probe(ProbeOutcome::CaptivePortal, now());
|
||||
assert_eq!(judge.snapshot().state, Connectivity::Down);
|
||||
assert!(judge.snapshot().captive_portal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_route_is_immediate_down() {
|
||||
let mut judge = ConnectivityJudge::new();
|
||||
judge.on_probe(ProbeOutcome::Success, now());
|
||||
judge.on_no_route();
|
||||
assert_eq!(judge.snapshot().state, Connectivity::Down);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn liveness_is_immediate_up_and_clears_streak() {
|
||||
let mut judge = ConnectivityJudge::new();
|
||||
judge.on_probe(ProbeOutcome::Success, now());
|
||||
judge.on_probe(ProbeOutcome::Failure, now()); // burst started
|
||||
judge.on_liveness();
|
||||
assert_eq!(judge.snapshot().state, Connectivity::Up);
|
||||
|
||||
// Fresh burst required again.
|
||||
let action = judge.on_probe(ProbeOutcome::Failure, now());
|
||||
assert!(matches!(action, JudgeAction::ConfirmAfter(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipv4_route_parse() {
|
||||
let with_default = "Iface\tDestination\tGateway\tFlags\n\
|
||||
wlan0\t00000000\t0102A8C0\t0003\n\
|
||||
wlan0\t0002A8C0\t00000000\t0001\n";
|
||||
let without_default = "Iface\tDestination\tGateway\tFlags\n\
|
||||
wlan0\t0002A8C0\t00000000\t0001\n";
|
||||
let lo_only = "Iface\tDestination\tGateway\tFlags\n\
|
||||
lo\t00000000\t00000000\t0001\n";
|
||||
assert!(ipv4_has_default_route(with_default));
|
||||
assert!(!ipv4_has_default_route(without_default));
|
||||
assert!(!ipv4_has_default_route(lo_only));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipv6_route_parse() {
|
||||
// dest(32) prefix(2) src(32) srcprefix(2) nexthop(32) metric refcnt use flags iface
|
||||
let with_default = "00000000000000000000000000000000 00 00000000000000000000000000000000 00 fe800000000000000000000000000001 00000400 00000000 00000000 00000003 wlan0\n";
|
||||
let non_default = "20010db8000000000000000000000000 40 00000000000000000000000000000000 00 00000000000000000000000000000000 00000400 00000000 00000000 00000001 wlan0\n";
|
||||
let lo_default = "00000000000000000000000000000000 00 00000000000000000000000000000000 00 00000000000000000000000000000000 00000400 00000000 00000000 00000003 lo\n";
|
||||
assert!(ipv6_has_default_route(with_default));
|
||||
assert!(!ipv6_has_default_route(non_default));
|
||||
assert!(!ipv6_has_default_route(lo_default));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
//! Offline MODE engine (frontend-agnostic, ADR-006).
|
||||
//!
|
||||
//! The app operating without Qobuz — NOT the offline cache. Spec:
|
||||
//! `qbz-nix-docs/offline-mode/2026-06-09-offline-mode-slint-port-spec.md`.
|
||||
//!
|
||||
//! Three states (D1):
|
||||
//! - `Online` — connectivity up, Qobuz services available.
|
||||
//! - `RealOffline` — detected connectivity loss, or a session started via
|
||||
//! "Start offline" with no Qobuz auth. SESSION-SCOPED: never persisted.
|
||||
//! - `InducedOffline` — the user's persisted opt-in from Settings.
|
||||
//!
|
||||
//! Invariants:
|
||||
//! - Offline (either flavor) ⇒ ZERO Qobuz services (D3). The engine owns the
|
||||
//! process-wide `qbz_qobuz::offline_gate`, flipping it on every transition.
|
||||
//! - Induced wins over real for display; the raw connectivity rides along in
|
||||
//! the status so the UI can render the recovery banner logic (D2).
|
||||
//! - Exiting induced offline is ALWAYS allowed (no probe gate — Tauri's
|
||||
//! trap is not ported); the state simply re-evaluates afterwards.
|
||||
//! - Entering induced offline snapshots `audio_settings.stream_first_track`
|
||||
//! and forces it false; exiting restores it (issue #279 parity).
|
||||
|
||||
pub mod connectivity;
|
||||
pub mod store;
|
||||
|
||||
pub use connectivity::{Connectivity, ConnectivityActor, ConnectivitySnapshot};
|
||||
pub use store::{OfflineModeSettings, OfflineModeStore};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use tokio::sync::watch;
|
||||
|
||||
use qbz_audio::settings::AudioSettingsStore;
|
||||
|
||||
/// The app-level offline mode (derived; see [`OfflineModeEngine`]).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OfflineMode {
|
||||
Online,
|
||||
RealOffline,
|
||||
InducedOffline,
|
||||
}
|
||||
|
||||
/// Full status broadcast to UIs on every change.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OfflineStatus {
|
||||
pub mode: OfflineMode,
|
||||
/// Raw connectivity, independent of the mode (the banner shows when an
|
||||
/// offline SESSION is active but connectivity is back).
|
||||
pub connectivity: Connectivity,
|
||||
/// Captive-portal hint from the prober.
|
||||
pub captive_portal: bool,
|
||||
/// The persisted induced flag (mirrors Settings).
|
||||
pub induced: bool,
|
||||
/// Session was started without Qobuz auth ("Start offline" from login).
|
||||
pub offline_session: bool,
|
||||
}
|
||||
|
||||
impl OfflineStatus {
|
||||
pub fn is_offline(&self) -> bool {
|
||||
self.mode != OfflineMode::Online
|
||||
}
|
||||
|
||||
/// D2: show the one-click login banner — an unauthenticated offline
|
||||
/// session while connectivity is actually up (and the user did not opt
|
||||
/// into induced offline).
|
||||
pub fn show_recovery_banner(&self) -> bool {
|
||||
self.offline_session && !self.induced && self.connectivity == Connectivity::Up
|
||||
}
|
||||
}
|
||||
|
||||
fn default_status() -> OfflineStatus {
|
||||
OfflineStatus {
|
||||
mode: OfflineMode::Online,
|
||||
connectivity: Connectivity::Unknown,
|
||||
captive_portal: false,
|
||||
induced: false,
|
||||
offline_session: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine. One per process; frontends hold it in an `Arc`.
|
||||
pub struct OfflineModeEngine {
|
||||
store: Mutex<Option<OfflineModeStore>>,
|
||||
induced: AtomicBool,
|
||||
offline_session: AtomicBool,
|
||||
status_tx: watch::Sender<OfflineStatus>,
|
||||
connectivity: Mutex<ConnectivitySnapshot>,
|
||||
}
|
||||
|
||||
impl OfflineModeEngine {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
store: Mutex::new(None),
|
||||
induced: AtomicBool::new(false),
|
||||
offline_session: AtomicBool::new(false),
|
||||
status_tx: watch::channel(default_status()).0,
|
||||
connectivity: Mutex::new(ConnectivitySnapshot::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the per-user settings store and load the persisted induced flag.
|
||||
/// Call on session activation (online or offline).
|
||||
pub fn init_for_user(&self, base_dir: &Path) -> Result<(), String> {
|
||||
let store = OfflineModeStore::new_at(base_dir)?;
|
||||
let induced = store.get_settings()?.manual_offline_mode;
|
||||
{
|
||||
let mut guard = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|e| format!("offline store lock poisoned: {}", e))?;
|
||||
*guard = Some(store);
|
||||
}
|
||||
self.induced.store(induced, Ordering::Relaxed);
|
||||
self.recompute();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drop the per-user store (logout). The induced flag cache is kept until
|
||||
/// the next `init_for_user` — the gate state must survive the transition.
|
||||
pub fn teardown(&self) {
|
||||
if let Ok(mut guard) = self.store.lock() {
|
||||
*guard = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscribe to status changes (UI listeners, QConnect suppressor, ...).
|
||||
pub fn subscribe(&self) -> watch::Receiver<OfflineStatus> {
|
||||
self.status_tx.subscribe()
|
||||
}
|
||||
|
||||
/// Current status snapshot.
|
||||
pub fn status(&self) -> OfflineStatus {
|
||||
*self.status_tx.borrow()
|
||||
}
|
||||
|
||||
/// Convenience: is ANY offline flavor active?
|
||||
pub fn is_offline(&self) -> bool {
|
||||
self.status().is_offline()
|
||||
}
|
||||
|
||||
/// Read the persisted settings (Settings view).
|
||||
pub fn settings(&self) -> Result<OfflineModeSettings, String> {
|
||||
let guard = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|e| format!("offline store lock poisoned: {}", e))?;
|
||||
let store = guard.as_ref().ok_or("No active session")?;
|
||||
store.get_settings()
|
||||
}
|
||||
|
||||
pub fn set_show_network_folders(&self, enabled: bool) -> Result<(), String> {
|
||||
let guard = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|e| format!("offline store lock poisoned: {}", e))?;
|
||||
let store = guard.as_ref().ok_or("No active session")?;
|
||||
store.set_show_network_folders_in_manual_offline(enabled)
|
||||
}
|
||||
|
||||
/// Flip induced offline (Settings toggle). Always succeeds in either
|
||||
/// direction; persists the flag, handles the #279 snapshot/restore, then
|
||||
/// recomputes the mode (which flips the Qobuz gate).
|
||||
///
|
||||
/// `audio` is best-effort: pre-login there may be no audio store yet.
|
||||
pub fn set_induced(
|
||||
&self,
|
||||
enabled: bool,
|
||||
audio: Option<&AudioSettingsStore>,
|
||||
) -> Result<OfflineStatus, String> {
|
||||
let was = {
|
||||
let guard = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|e| format!("offline store lock poisoned: {}", e))?;
|
||||
let store = guard.as_ref().ok_or("No active session")?;
|
||||
let was = store.get_settings()?.manual_offline_mode;
|
||||
store.set_manual_offline_mode(enabled)?;
|
||||
|
||||
if let Some(audio_store) = audio {
|
||||
if enabled && !was {
|
||||
// Entering: stash the current preference, force false.
|
||||
if let Ok(settings) = audio_store.get_settings() {
|
||||
let _ = store
|
||||
.set_pre_offline_stream_first_track(Some(settings.stream_first_track));
|
||||
if settings.stream_first_track {
|
||||
let _ = audio_store.set_stream_first_track(false);
|
||||
log::info!(
|
||||
"[OfflineMode] stream_first_track snapshot=true; forced false while offline (#279)"
|
||||
);
|
||||
}
|
||||
}
|
||||
} else if !enabled && was {
|
||||
// Exiting: restore the stash, clear it.
|
||||
if let Ok(Some(snapshot)) = store.get_pre_offline_stream_first_track() {
|
||||
let _ = audio_store.set_stream_first_track(snapshot);
|
||||
let _ = store.set_pre_offline_stream_first_track(None);
|
||||
log::info!("[OfflineMode] stream_first_track restored to {} (#279)", snapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
was
|
||||
};
|
||||
let _ = was;
|
||||
|
||||
self.induced.store(enabled, Ordering::Relaxed);
|
||||
self.recompute();
|
||||
Ok(self.status())
|
||||
}
|
||||
|
||||
/// Mark/unmark the session as an unauthenticated offline session
|
||||
/// ("Start offline" from the login screen). Session-scoped (D1): callers
|
||||
/// set it on `enter_shell_offline` and clear it after a successful login.
|
||||
pub fn set_offline_session(&self, active: bool) {
|
||||
self.offline_session.store(active, Ordering::Relaxed);
|
||||
self.recompute();
|
||||
}
|
||||
|
||||
/// Feed a fresh connectivity snapshot (the engine's listener task calls
|
||||
/// this on every actor broadcast).
|
||||
pub fn on_connectivity(&self, snapshot: ConnectivitySnapshot) {
|
||||
if let Ok(mut guard) = self.connectivity.lock() {
|
||||
*guard = snapshot;
|
||||
}
|
||||
self.recompute();
|
||||
}
|
||||
|
||||
/// Spawn the listener wiring an actor subscription into the engine.
|
||||
/// Returns immediately; the task lives for the process lifetime.
|
||||
pub fn attach_connectivity(self: &std::sync::Arc<Self>, actor: &ConnectivityActor) {
|
||||
let mut rx = actor.subscribe();
|
||||
let engine = std::sync::Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
if rx.changed().await.is_err() {
|
||||
return;
|
||||
}
|
||||
let snapshot = *rx.borrow();
|
||||
engine.on_connectivity(snapshot);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Derive the mode, flip the Qobuz gate, broadcast on change.
|
||||
fn recompute(&self) {
|
||||
let induced = self.induced.load(Ordering::Relaxed);
|
||||
let offline_session = self.offline_session.load(Ordering::Relaxed);
|
||||
let connectivity = self
|
||||
.connectivity
|
||||
.lock()
|
||||
.map(|guard| *guard)
|
||||
.unwrap_or_default();
|
||||
|
||||
let mode = if induced {
|
||||
OfflineMode::InducedOffline
|
||||
} else if offline_session || connectivity.state == Connectivity::Down {
|
||||
OfflineMode::RealOffline
|
||||
} else {
|
||||
OfflineMode::Online
|
||||
};
|
||||
|
||||
let status = OfflineStatus {
|
||||
mode,
|
||||
connectivity: connectivity.state,
|
||||
captive_portal: connectivity.captive_portal,
|
||||
induced,
|
||||
offline_session,
|
||||
};
|
||||
|
||||
// D3: the single Qobuz choke point follows the mode.
|
||||
qbz_qobuz::offline_gate::set_offline(mode != OfflineMode::Online);
|
||||
|
||||
let _ = self.status_tx.send_if_modified(|current| {
|
||||
if *current != status {
|
||||
log::info!(
|
||||
"[OfflineMode] {:?} -> {:?} (connectivity {:?}, induced {}, offline_session {})",
|
||||
current.mode,
|
||||
status.mode,
|
||||
status.connectivity,
|
||||
status.induced,
|
||||
status.offline_session
|
||||
);
|
||||
*current = status;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for OfflineModeEngine {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
|
||||
|
||||
fn unique_test_dir(name: &str) -> std::path::PathBuf {
|
||||
static NONCE: AtomicU64 = AtomicU64::new(0);
|
||||
let nonce = NONCE.fetch_add(1, AtomicOrdering::Relaxed);
|
||||
std::env::temp_dir().join(format!("qbz-app-{name}-{}-{nonce}", std::process::id()))
|
||||
}
|
||||
|
||||
/// The engine flips the PROCESS-GLOBAL `qbz_qobuz::offline_gate`; these
|
||||
/// tests must not run concurrently or the gate assertions race.
|
||||
static GATE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn serialize() -> std::sync::MutexGuard<'static, ()> {
|
||||
GATE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
fn up() -> ConnectivitySnapshot {
|
||||
ConnectivitySnapshot {
|
||||
state: Connectivity::Up,
|
||||
captive_portal: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn down() -> ConnectivitySnapshot {
|
||||
ConnectivitySnapshot {
|
||||
state: Connectivity::Down,
|
||||
captive_portal: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starts_online_with_unknown_connectivity() {
|
||||
let _gate = serialize();
|
||||
let engine = OfflineModeEngine::new();
|
||||
let status = engine.status();
|
||||
assert_eq!(status.mode, OfflineMode::Online);
|
||||
assert_eq!(status.connectivity, Connectivity::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connectivity_down_is_real_offline_and_back() {
|
||||
let _gate = serialize();
|
||||
let engine = OfflineModeEngine::new();
|
||||
engine.on_connectivity(down());
|
||||
assert_eq!(engine.status().mode, OfflineMode::RealOffline);
|
||||
assert!(qbz_qobuz::offline_gate::is_offline());
|
||||
|
||||
engine.on_connectivity(up());
|
||||
assert_eq!(engine.status().mode, OfflineMode::Online);
|
||||
assert!(!qbz_qobuz::offline_gate::is_offline());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn induced_wins_over_connectivity() {
|
||||
let _gate = serialize();
|
||||
let dir = unique_test_dir("engine-induced");
|
||||
let engine = OfflineModeEngine::new();
|
||||
engine.init_for_user(&dir).unwrap();
|
||||
|
||||
engine.on_connectivity(up());
|
||||
engine.set_induced(true, None).unwrap();
|
||||
assert_eq!(engine.status().mode, OfflineMode::InducedOffline);
|
||||
assert!(engine.status().induced);
|
||||
assert!(qbz_qobuz::offline_gate::is_offline());
|
||||
|
||||
// Exit always allowed; connectivity Up => back Online.
|
||||
engine.set_induced(false, None).unwrap();
|
||||
assert_eq!(engine.status().mode, OfflineMode::Online);
|
||||
assert!(!qbz_qobuz::offline_gate::is_offline());
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn induced_flag_is_persisted_and_reloaded() {
|
||||
let _gate = serialize();
|
||||
let dir = unique_test_dir("engine-persist");
|
||||
{
|
||||
let engine = OfflineModeEngine::new();
|
||||
engine.init_for_user(&dir).unwrap();
|
||||
engine.set_induced(true, None).unwrap();
|
||||
}
|
||||
{
|
||||
let engine = OfflineModeEngine::new();
|
||||
engine.init_for_user(&dir).unwrap();
|
||||
assert_eq!(engine.status().mode, OfflineMode::InducedOffline);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offline_session_is_real_offline_even_with_connectivity_up() {
|
||||
let _gate = serialize();
|
||||
let engine = OfflineModeEngine::new();
|
||||
engine.on_connectivity(up());
|
||||
engine.set_offline_session(true);
|
||||
|
||||
let status = engine.status();
|
||||
assert_eq!(status.mode, OfflineMode::RealOffline);
|
||||
assert!(status.show_recovery_banner(), "banner: session offline but net is back");
|
||||
|
||||
engine.set_offline_session(false);
|
||||
assert_eq!(engine.status().mode, OfflineMode::Online);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_banner_while_connectivity_down_or_induced() {
|
||||
let _gate = serialize();
|
||||
let dir = unique_test_dir("engine-banner");
|
||||
let engine = OfflineModeEngine::new();
|
||||
engine.init_for_user(&dir).unwrap();
|
||||
|
||||
engine.set_offline_session(true);
|
||||
engine.on_connectivity(down());
|
||||
assert!(!engine.status().show_recovery_banner());
|
||||
|
||||
engine.on_connectivity(up());
|
||||
engine.set_induced(true, None).unwrap();
|
||||
assert!(!engine.status().show_recovery_banner());
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_first_snapshot_is_stashed_and_restored() {
|
||||
let _gate = serialize();
|
||||
let dir = unique_test_dir("engine-279");
|
||||
let audio_dir = unique_test_dir("engine-279-audio");
|
||||
std::fs::create_dir_all(&audio_dir).unwrap();
|
||||
let audio = AudioSettingsStore::new_at(&audio_dir).unwrap();
|
||||
audio.set_stream_first_track(true).unwrap();
|
||||
|
||||
let engine = OfflineModeEngine::new();
|
||||
engine.init_for_user(&dir).unwrap();
|
||||
|
||||
engine.set_induced(true, Some(&audio)).unwrap();
|
||||
assert!(!audio.get_settings().unwrap().stream_first_track, "#279: forced false");
|
||||
|
||||
engine.set_induced(false, Some(&audio)).unwrap();
|
||||
assert!(audio.get_settings().unwrap().stream_first_track, "#279: restored");
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(audio_dir);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn watch_broadcasts_on_change() {
|
||||
let _gate = serialize();
|
||||
let engine = std::sync::Arc::new(OfflineModeEngine::new());
|
||||
let mut rx = engine.subscribe();
|
||||
|
||||
engine.on_connectivity(down());
|
||||
rx.changed().await.unwrap();
|
||||
assert_eq!(rx.borrow().mode, OfflineMode::RealOffline);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! Per-user offline-mode settings store.
|
||||
//!
|
||||
//! Opens the SAME `offline_settings.db` Tauri's `src-tauri/src/offline/mod.rs`
|
||||
//! uses (identical creation SQL + additive migrations), so the file stays
|
||||
//! frontend-portable like `library.db`/`index.db`. This shared store exposes
|
||||
//! only the subset the offline-MODE port consumes:
|
||||
//!
|
||||
//! - `manual_offline_mode` — the induced-offline flag (persisted; D1).
|
||||
//! - `show_network_folders_in_manual_offline` — network-mount policy (D9).
|
||||
//! - `pre_offline_stream_first_track` — the issue #279 snapshot of
|
||||
//! `audio_settings.stream_first_track` taken on entering induced offline.
|
||||
//!
|
||||
//! The legacy columns/tables (cast/scrobbling flags, `pending_playlist_sync`,
|
||||
//! `scrobble_queue`, `cache_limit_bytes`) are still CREATED for byte-level
|
||||
//! compatibility with the Tauri schema, but get no API here: the dead toggles
|
||||
//! are not ported (spec §1) and offline playlist creation is replaced by
|
||||
//! first-class local playlists (D7/D8).
|
||||
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
|
||||
/// The offline-mode settings the port consumes.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OfflineModeSettings {
|
||||
pub manual_offline_mode: bool,
|
||||
pub show_network_folders_in_manual_offline: bool,
|
||||
}
|
||||
|
||||
pub struct OfflineModeStore {
|
||||
conn: Connection,
|
||||
}
|
||||
|
||||
impl OfflineModeStore {
|
||||
/// Open (or create) `offline_settings.db` under `base_dir` — the per-user
|
||||
/// data directory, same location Tauri's `OfflineState::init_at` uses.
|
||||
pub fn new_at(base_dir: &Path) -> Result<Self, String> {
|
||||
std::fs::create_dir_all(base_dir)
|
||||
.map_err(|e| format!("Failed to create data directory: {}", e))?;
|
||||
let db_path = base_dir.join("offline_settings.db");
|
||||
|
||||
let conn = Connection::open(&db_path)
|
||||
.map_err(|e| format!("Failed to open offline settings database: {}", e))?;
|
||||
|
||||
conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;")
|
||||
.map_err(|e| format!("Failed to enable WAL for offline settings database: {}", e))?;
|
||||
|
||||
// Base tables — kept IDENTICAL to the Tauri module so both frontends
|
||||
// can open the same per-user file.
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS offline_settings (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
manual_offline_mode INTEGER NOT NULL DEFAULT 0,
|
||||
show_partial_playlists INTEGER NOT NULL DEFAULT 1
|
||||
);
|
||||
INSERT OR IGNORE INTO offline_settings (id, manual_offline_mode, show_partial_playlists)
|
||||
VALUES (1, 0, 1);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pending_playlist_sync (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
is_public INTEGER NOT NULL DEFAULT 0,
|
||||
track_ids TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
synced INTEGER NOT NULL DEFAULT 0,
|
||||
qobuz_playlist_id INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_pending_playlist_synced ON pending_playlist_sync(synced);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS scrobble_queue (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
artist TEXT NOT NULL,
|
||||
track TEXT NOT NULL,
|
||||
album TEXT,
|
||||
timestamp INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
sent INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_scrobble_queue_sent ON scrobble_queue(sent);",
|
||||
)
|
||||
.map_err(|e| format!("Failed to create offline settings table: {}", e))?;
|
||||
|
||||
// Additive migrations — same list as Tauri's; errors ignored because
|
||||
// the column may already exist.
|
||||
let migrations = [
|
||||
"ALTER TABLE offline_settings ADD COLUMN allow_cast_while_offline INTEGER NOT NULL DEFAULT 0",
|
||||
"ALTER TABLE offline_settings ADD COLUMN allow_immediate_scrobbling INTEGER NOT NULL DEFAULT 0",
|
||||
"ALTER TABLE offline_settings ADD COLUMN allow_accumulated_scrobbling INTEGER NOT NULL DEFAULT 1",
|
||||
"ALTER TABLE offline_settings ADD COLUMN show_network_folders_in_manual_offline INTEGER NOT NULL DEFAULT 0",
|
||||
"ALTER TABLE offline_settings ADD COLUMN pre_offline_stream_first_track INTEGER",
|
||||
"ALTER TABLE pending_playlist_sync ADD COLUMN local_track_ids TEXT",
|
||||
"ALTER TABLE pending_playlist_sync ADD COLUMN local_track_paths TEXT",
|
||||
"ALTER TABLE offline_settings ADD COLUMN cache_limit_bytes INTEGER",
|
||||
];
|
||||
for migration in migrations {
|
||||
let _ = conn.execute(migration, []);
|
||||
}
|
||||
|
||||
Ok(Self { conn })
|
||||
}
|
||||
|
||||
pub fn get_settings(&self) -> Result<OfflineModeSettings, String> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT manual_offline_mode,
|
||||
COALESCE(show_network_folders_in_manual_offline, 0)
|
||||
FROM offline_settings WHERE id = 1",
|
||||
[],
|
||||
|row| {
|
||||
Ok(OfflineModeSettings {
|
||||
manual_offline_mode: row.get::<_, i64>(0)? != 0,
|
||||
show_network_folders_in_manual_offline: row.get::<_, i64>(1)? != 0,
|
||||
})
|
||||
},
|
||||
)
|
||||
.map_err(|e| format!("Failed to get offline settings: {}", e))
|
||||
}
|
||||
|
||||
pub fn set_manual_offline_mode(&self, enabled: bool) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE offline_settings SET manual_offline_mode = ?1 WHERE id = 1",
|
||||
params![enabled as i64],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set manual offline mode: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_show_network_folders_in_manual_offline(&self, enabled: bool) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE offline_settings SET show_network_folders_in_manual_offline = ?1 WHERE id = 1",
|
||||
params![enabled as i64],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set show network folders in manual offline: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Issue #279 snapshot: the user's `stream_first_track` preference stashed
|
||||
/// when entering induced offline. `None` = no snapshot active.
|
||||
pub fn get_pre_offline_stream_first_track(&self) -> Result<Option<bool>, String> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT pre_offline_stream_first_track FROM offline_settings WHERE id = 1",
|
||||
[],
|
||||
|row| row.get::<_, Option<i64>>(0),
|
||||
)
|
||||
.map(|opt| opt.map(|v| v != 0))
|
||||
.map_err(|e| format!("Failed to read pre_offline_stream_first_track: {}", e))
|
||||
}
|
||||
|
||||
/// Store (`Some`) on entering induced offline, clear (`None`) on exit.
|
||||
pub fn set_pre_offline_stream_first_track(&self, value: Option<bool>) -> Result<(), String> {
|
||||
let param: Option<i64> = value.map(|v| v as i64);
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE offline_settings SET pre_offline_stream_first_track = ?1 WHERE id = 1",
|
||||
params![param],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set pre_offline_stream_first_track: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
fn unique_test_dir(name: &str) -> std::path::PathBuf {
|
||||
static NONCE: AtomicU64 = AtomicU64::new(0);
|
||||
let nonce = NONCE.fetch_add(1, Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!("qbz-app-{name}-{}-{nonce}", std::process::id()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_are_online_and_no_network_folders() {
|
||||
let dir = unique_test_dir("offline-store-defaults");
|
||||
let store = OfflineModeStore::new_at(&dir).unwrap();
|
||||
|
||||
let settings = store.get_settings().unwrap();
|
||||
assert!(!settings.manual_offline_mode);
|
||||
assert!(!settings.show_network_folders_in_manual_offline);
|
||||
assert_eq!(store.get_pre_offline_stream_first_track().unwrap(), None);
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_flag_round_trips() {
|
||||
let dir = unique_test_dir("offline-store-manual");
|
||||
let store = OfflineModeStore::new_at(&dir).unwrap();
|
||||
|
||||
store.set_manual_offline_mode(true).unwrap();
|
||||
assert!(store.get_settings().unwrap().manual_offline_mode);
|
||||
store.set_manual_offline_mode(false).unwrap();
|
||||
assert!(!store.get_settings().unwrap().manual_offline_mode);
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_folders_flag_round_trips() {
|
||||
let dir = unique_test_dir("offline-store-netfolders");
|
||||
let store = OfflineModeStore::new_at(&dir).unwrap();
|
||||
|
||||
store.set_show_network_folders_in_manual_offline(true).unwrap();
|
||||
assert!(
|
||||
store
|
||||
.get_settings()
|
||||
.unwrap()
|
||||
.show_network_folders_in_manual_offline
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_first_snapshot_round_trips() {
|
||||
let dir = unique_test_dir("offline-store-snapshot");
|
||||
let store = OfflineModeStore::new_at(&dir).unwrap();
|
||||
|
||||
store.set_pre_offline_stream_first_track(Some(true)).unwrap();
|
||||
assert_eq!(store.get_pre_offline_stream_first_track().unwrap(), Some(true));
|
||||
store.set_pre_offline_stream_first_track(None).unwrap();
|
||||
assert_eq!(store.get_pre_offline_stream_first_track().unwrap(), None);
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopens_tauri_era_database_without_data_loss() {
|
||||
// Simulate a DB created by the original Tauri schema (pre-migration
|
||||
// base tables only), then reopen with this store: migrations must be
|
||||
// additive and the existing flag must survive.
|
||||
let dir = unique_test_dir("offline-store-compat");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
{
|
||||
let conn = Connection::open(dir.join("offline_settings.db")).unwrap();
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE offline_settings (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
manual_offline_mode INTEGER NOT NULL DEFAULT 0,
|
||||
show_partial_playlists INTEGER NOT NULL DEFAULT 1
|
||||
);
|
||||
INSERT INTO offline_settings (id, manual_offline_mode, show_partial_playlists)
|
||||
VALUES (1, 1, 1);",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let store = OfflineModeStore::new_at(&dir).unwrap();
|
||||
let settings = store.get_settings().unwrap();
|
||||
assert!(settings.manual_offline_mode, "Tauri-era flag must survive");
|
||||
assert!(!settings.show_network_folders_in_manual_offline);
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,24 @@ impl SubscriptionStateStore {
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// D4 playback gate: may the offline cache serve FULL tracks right now?
|
||||
///
|
||||
/// Binary by design — within the grace window the cache plays complete
|
||||
/// tracks; past it, playback is refused outright. There is NO degraded
|
||||
/// 30-second-preview path (the owner's explicit requirement: Qobuz's
|
||||
/// preview behavior must never appear here).
|
||||
///
|
||||
/// `invalid_since == None` (never observed invalid, including the
|
||||
/// never-checked default) ⇒ allowed: the grace clock only starts when a
|
||||
/// login verdict explicitly reports the account ineligible.
|
||||
pub fn offline_playback_allowed(&self, now: i64) -> Result<bool, String> {
|
||||
let state = self.get_state()?;
|
||||
let Some(invalid_since) = state.invalid_since else {
|
||||
return Ok(true);
|
||||
};
|
||||
Ok(now - invalid_since < GRACE_PERIOD_SECS)
|
||||
}
|
||||
}
|
||||
|
||||
pub type SubscriptionStateState = Arc<Mutex<Option<SubscriptionStateStore>>>;
|
||||
@@ -238,6 +256,31 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offline_playback_allowed_within_grace_refused_after() {
|
||||
let dir = unique_test_dir("subscription-playback-gate");
|
||||
let store = SubscriptionStateStore::new_at(&dir).unwrap();
|
||||
|
||||
// Never observed invalid (default): allowed.
|
||||
assert!(store.offline_playback_allowed(0).unwrap());
|
||||
|
||||
store.mark_invalid(100).unwrap();
|
||||
assert!(store
|
||||
.offline_playback_allowed(100 + GRACE_PERIOD_SECS - 1)
|
||||
.unwrap());
|
||||
assert!(!store
|
||||
.offline_playback_allowed(100 + GRACE_PERIOD_SECS)
|
||||
.unwrap());
|
||||
|
||||
// A valid login verdict re-opens playback.
|
||||
store.mark_valid(100 + GRACE_PERIOD_SECS + 10).unwrap();
|
||||
assert!(store
|
||||
.offline_playback_allowed(100 + GRACE_PERIOD_SECS + 20)
|
||||
.unwrap());
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscription_mark_valid_clears_invalid_since() {
|
||||
let dir = unique_test_dir("subscription-valid");
|
||||
|
||||
Reference in new issue
Block a user