5.1 KiB · text History 6c56e6c
//! Scrobbles waiting for a backend, in SQLite
//! (`~/.local/state/scropple/queue.sqlite`), so a laptop that's offline, or a
//! server that's down, loses nothing: each play is kept per backend until
//! that backend takes it, retried with backoff. final_track ignores a play it
//! already has, so a retry after a lost response does no harm.

use anyhow::Result;
use rusqlite::{Connection, params};
use std::path::Path;

use crate::backend::Play;

/// Most plays sent in one request (final_track takes 500).
pub const BATCH: usize = 50;

pub struct Queue {
    db: Connection,
}

#[derive(Debug)]
pub struct Pending {
    pub id: i64,
    pub play: Play,
    pub attempts: u32,
}

impl Queue {
    pub fn open(path: &Path) -> Result<Self> {
        if let Some(dir) = path.parent() {
            std::fs::create_dir_all(dir)?;
        }
        Self::init(Connection::open(path)?)
    }

    pub fn in_memory() -> Result<Self> {
        Self::init(Connection::open_in_memory()?)
    }

    fn init(db: Connection) -> Result<Self> {
        db.execute_batch(
            "CREATE TABLE IF NOT EXISTS pending (
               id INTEGER PRIMARY KEY,
               backend TEXT NOT NULL,
               play TEXT NOT NULL,
               attempts INTEGER NOT NULL DEFAULT 0,
               next_attempt INTEGER NOT NULL DEFAULT 0
             );
             CREATE INDEX IF NOT EXISTS pending_due ON pending (backend, next_attempt);",
        )?;
        Ok(Self { db })
    }

    pub fn push(&self, backend: &str, play: &Play) -> Result<()> {
        self.db.execute(
            "INSERT INTO pending (backend, play) VALUES (?1, ?2)",
            params![backend, serde_json::to_string(play)?],
        )?;
        Ok(())
    }

    /// Up to [`BATCH`] plays due for `backend` at `now` (Unix seconds), oldest first.
    pub fn due(&self, backend: &str, now: i64) -> Result<Vec<Pending>> {
        let mut stmt = self.db.prepare(
            "SELECT id, play, attempts FROM pending
             WHERE backend = ?1 AND next_attempt <= ?2 ORDER BY id LIMIT ?3",
        )?;
        let rows = stmt.query_map(params![backend, now, BATCH as i64], |r| {
            Ok((
                r.get::<_, i64>(0)?,
                r.get::<_, String>(1)?,
                r.get::<_, u32>(2)?,
            ))
        })?;
        let mut out = vec![];
        for row in rows {
            let (id, json, attempts) = row?;
            match serde_json::from_str(&json) {
                Ok(play) => out.push(Pending { id, play, attempts }),
                // Unreadable (from some future version?): don't wedge the queue.
                Err(_) => self.remove(&[id])?,
            }
        }
        Ok(out)
    }

    pub fn remove(&self, ids: &[i64]) -> Result<()> {
        for id in ids {
            self.db
                .execute("DELETE FROM pending WHERE id = ?1", params![id])?;
        }
        Ok(())
    }

    /// Try these again later: 1 minute after the first failure, doubling, at
    /// most 6 hours.
    pub fn defer(&self, pending: &[Pending], now: i64) -> Result<()> {
        for p in pending {
            let attempts = p.attempts + 1;
            self.db.execute(
                "UPDATE pending SET attempts = ?2, next_attempt = ?3 WHERE id = ?1",
                params![p.id, attempts, now + backoff(attempts)],
            )?;
        }
        Ok(())
    }

    /// How many plays wait, per backend.
    pub fn counts(&self) -> Result<Vec<(String, i64)>> {
        let mut stmt = self
            .db
            .prepare("SELECT backend, count(*) FROM pending GROUP BY backend ORDER BY backend")?;
        let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
        Ok(rows.collect::<rusqlite::Result<_>>()?)
    }
}

pub fn backoff(attempts: u32) -> i64 {
    (60i64 << attempts.saturating_sub(1).min(16)).min(6 * 3600)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn play(track: &str) -> Play {
        Play {
            artist: "Pink Floyd".into(),
            track: track.into(),
            album: None,
            album_artist: None,
            duration_sec: Some(413),
            timestamp: Some(1_000),
        }
    }

    #[test]
    fn per_backend_due_remove_defer() {
        let q = Queue::in_memory().unwrap();
        q.push("a", &play("Time")).unwrap();
        q.push("a", &play("Money")).unwrap();
        q.push("b", &play("Time")).unwrap();

        let due = q.due("a", 0).unwrap();
        assert_eq!(
            due.iter()
                .map(|p| p.play.track.as_str())
                .collect::<Vec<_>>(),
            ["Time", "Money"]
        );

        q.remove(&[due[0].id]).unwrap();
        q.defer(&due[1..], 100).unwrap();
        assert!(q.due("a", 100).unwrap().is_empty()); // deferred 60s
        assert_eq!(q.due("a", 160).unwrap()[0].attempts, 1);
        assert_eq!(
            q.counts().unwrap(),
            [("a".to_string(), 1), ("b".to_string(), 1)]
        );
    }

    #[test]
    fn backoff_doubles_and_caps() {
        assert_eq!(backoff(1), 60);
        assert_eq!(backoff(2), 120);
        assert_eq!(backoff(3), 240);
        assert_eq!(backoff(30), 6 * 3600);
    }
}