redseat-api 0.10.1

Rust client for Redseat media servers
Documentation
//! Thumbnail bytes, behind [`ThumbStore`]: files ([`ThumbDir`]) on native targets,
//! `<thumbs>/<library>/<media>`, as the server stores them (still encrypted in an
//! encrypted library). Their sizes and last use are in the [`super::MirrorStore`].

#[cfg(not(target_arch = "wasm32"))]
use std::path::PathBuf;
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::atomic::{AtomicU64, Ordering};

#[cfg(not(target_arch = "wasm32"))]
use crate::error::Error;
use crate::error::Result;
use crate::transport::MaybeSend;

/// Where the mirror keeps thumbnail bytes, by library and media id. It decides
/// nothing: the mirror tells it what to keep and what to remove.
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
pub trait ThumbStore: MaybeSend {
    /// The thumbnail, when it is there.
    async fn read(&self, library: &str, media: &str) -> Option<Vec<u8>>;
    /// Stores the thumbnail whole, replacing an earlier one: a read never gets part of
    /// it. After an error, it is not stored.
    async fn write(&self, library: &str, media: &str, data: &[u8]) -> Result<()>;
    /// Removes the thumbnail. Already gone is fine.
    async fn remove(&self, library: &str, media: &str);
    /// Removes every thumbnail of a library.
    async fn remove_library(&self, library: &str);
}

/// The mirror's thumbnails: their [`ThumbStore`], and the locks that keep a
/// thumbnail and its record together.
pub(super) struct Thumbs {
    store: Arc<dyn ThumbStore>,
    /// Serializes storing a thumbnail with its record, per media (striped by hash).
    publishing: Vec<tokio::sync::Mutex<()>>,
}

const PUBLISH_STRIPES: usize = 64;

impl Thumbs {
    pub(super) fn new(store: Arc<dyn ThumbStore>) -> Self {
        Thumbs {
            store,
            publishing: (0..PUBLISH_STRIPES)
                .map(|_| tokio::sync::Mutex::new(()))
                .collect(),
        }
    }

    /// The lock to hold while storing the thumbnail of `media` with its record.
    pub(super) fn publish_lock(&self, library: &str, media: &str) -> &tokio::sync::Mutex<()> {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        (library, media).hash(&mut hasher);
        &self.publishing[hasher.finish() as usize % PUBLISH_STRIPES]
    }

    pub(super) async fn read(&self, library: &str, media: &str) -> Option<Vec<u8>> {
        self.store.read(library, media).await
    }

    /// Callers hold [`Self::publish_lock`] with the record.
    pub(super) async fn write(&self, library: &str, media: &str, data: &[u8]) -> Result<()> {
        self.store.write(library, media, data).await
    }

    pub(super) async fn remove(&self, library: &str, media: &str) {
        self.store.remove(library, media).await;
    }

    pub(super) async fn remove_library(&self, library: &str) {
        self.store.remove_library(library).await;
    }
}

/// [`ThumbStore`] in a folder: one file per thumbnail, `<dir>/<library>/<media>`. Its
/// file work runs on the tokio runtime it was made in, so it can be awaited from any
/// executor.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone)]
pub struct ThumbDir {
    dir: PathBuf,
    runtime: Option<tokio::runtime::Handle>,
}

/// A file name for an id: the id itself when it is plain, else its hex form.
#[cfg(not(target_arch = "wasm32"))]
fn file_name(id: &str) -> String {
    let plain = !id.is_empty()
        && id.len() <= 100
        && !id.starts_with('.')
        && id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.');
    if plain {
        id.to_owned()
    } else {
        let hex: String = id.bytes().map(|b| format!("{b:02x}")).collect();
        format!("x{hex}")
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl ThumbDir {
    pub fn new(dir: impl Into<PathBuf>) -> Self {
        ThumbDir {
            dir: dir.into(),
            runtime: tokio::runtime::Handle::try_current().ok(),
        }
    }

    /// Runs file work on the blocking threads of the folder's runtime.
    async fn blocking<T: Send + Default + 'static>(
        &self,
        work: impl FnOnce() -> T + Send + 'static,
    ) -> T {
        (super::runtime::blocking(self.runtime.as_ref(), work).await).unwrap_or_default()
    }

    fn library_dir(&self, library: &str) -> PathBuf {
        self.dir.join(file_name(library))
    }

    fn path(&self, library: &str, media: &str) -> PathBuf {
        self.library_dir(library).join(file_name(media))
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[async_trait::async_trait]
impl ThumbStore for ThumbDir {
    async fn read(&self, library: &str, media: &str) -> Option<Vec<u8>> {
        let path = self.path(library, media);
        self.blocking(move || std::fs::read(path).ok()).await
    }

    /// Writes the file whole: to a temporary file of its own, then renamed over the
    /// cached one. A failed replacement is an error, so no record is written for bytes
    /// that are not there.
    async fn write(&self, library: &str, media: &str, data: &[u8]) -> Result<()> {
        static NEXT: AtomicU64 = AtomicU64::new(0);
        let path = self.path(library, media);
        let folder = self.library_dir(library);
        let data = data.to_vec();
        let written = self.blocking(move || -> Option<std::io::Result<()>> {
            let write = || {
                std::fs::create_dir_all(folder)?;
                let mut temporary = path.clone().into_os_string();
                temporary.push(format!(
                    ".{}-{}.part",
                    std::process::id(),
                    NEXT.fetch_add(1, Ordering::Relaxed)
                ));
                let replaced = std::fs::write(&temporary, &data)
                    .and_then(|()| std::fs::rename(&temporary, &path));
                if replaced.is_err() {
                    let _ = std::fs::remove_file(&temporary);
                }
                replaced
            };
            Some(write())
        });
        match written.await {
            Some(Ok(())) => Ok(()),
            Some(Err(e)) => Err(Error::storage(format!("thumbnail cache: {e}"))),
            None => Err(Error::storage("thumbnail cache: the write was stopped")),
        }
    }

    async fn remove(&self, library: &str, media: &str) {
        // Already gone is fine.
        let path = self.path(library, media);
        self.blocking(move || {
            let _ = std::fs::remove_file(path);
        })
        .await;
    }

    async fn remove_library(&self, library: &str) {
        let folder = self.library_dir(library);
        self.blocking(move || {
            let _ = std::fs::remove_dir_all(folder);
        })
        .await;
    }
}

#[cfg(test)]
mod tests {
    use super::{ThumbDir, Thumbs, file_name};

    #[tokio::test]
    async fn writes_of_one_thumbnail_under_its_lock_all_succeed() {
        let dir = std::env::temp_dir().join(format!(
            "redseat-thumbs-test-{}-{}",
            std::process::id(),
            line!()
        ));
        let files =
            std::sync::Arc::new(Thumbs::new(std::sync::Arc::new(ThumbDir::new(dir.clone()))));
        let data = vec![7u8; 64 * 1024];
        let writes: Vec<_> = (0..16)
            .map(|_| {
                let files = files.clone();
                let data = data.clone();
                tokio::spawn(async move {
                    let _publishing = files.publish_lock("lib", "media").lock().await;
                    files.write("lib", "media", &data).await
                })
            })
            .collect();
        for write in writes {
            write.await.unwrap().unwrap();
        }
        assert_eq!(files.read("lib", "media").await, Some(data));
        // No temporary file is left behind.
        let mut entries = tokio::fs::read_dir(dir.join("lib")).await.unwrap();
        let mut names = Vec::new();
        while let Some(entry) = entries.next_entry().await.unwrap() {
            names.push(entry.file_name());
        }
        assert_eq!(names, ["media"]);
        let _ = tokio::fs::remove_dir_all(dir).await;
    }

    #[test]
    fn keeps_plain_ids_and_encodes_others() {
        assert_eq!(file_name("abc-DEF_1"), "abc-DEF_1");
        assert_eq!(file_name("a/b"), "x612f62");
        assert_eq!(file_name(".."), "x2e2e");
        assert_eq!(file_name(""), "x");
    }
}