Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

6.1 KB
Raw Blame
//! Decoupled L3 Scratch Disk backend trait & pure-Rust implementations.
//!
//! `crates/ink-engine` has zero Tauri dependencies: the desktop host (`src-tauri`)
//! supplies an in-process adapter directly wrapping `src-tauri/src/scratch_disk.rs`
//! (zero Tauri IPC!), while pure unit/headless tests use [`InMemoryScratchBackend`]
//! or [`FileScratchBackend`].

use parking_lot::RwLock;
use std::collections::HashMap;
use std::path::PathBuf;

/// Single uncompressed tile payload written to L3 scratch storage.
#[derive(Debug, Clone)]
pub struct ScratchTileWrite {
    pub layer_key: String,
    pub tx: i32,
    pub ty: i32,
    pub data: Vec<u8>,
}

/// Thread-safe, synchronous in-process L3 scratch disk storage contract.
pub trait ScratchBackend: Send + Sync {
    fn init_session(&self, session_id: &str) -> Result<(), String>;
    fn write_tiles(&self, session_id: &str, tiles: Vec<ScratchTileWrite>) -> Result<usize, String>;
    fn read_tile(
        &self,
        session_id: &str,
        layer_key: &str,
        tx: i32,
        ty: i32,
    ) -> Result<Vec<u8>, String>;
    fn clear_session(&self, session_id: &str) -> Result<(), String>;
}

type ScratchTileKey = (String, String, i32, i32);

/// Fast in-memory LZ4-backed scratch disk used by unit tests and headless engine instances.
#[derive(Default)]
pub struct InMemoryScratchBackend {
    /// `(session_id, layer_key, tx, ty) -> lz4_flex::compress_prepend_size(raw)`
    store: RwLock<HashMap<ScratchTileKey, Vec<u8>>>,
}

impl InMemoryScratchBackend {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn tile_count(&self) -> usize {
        self.store.read().len()
    }

    pub fn compressed_bytes(&self) -> usize {
        self.store.read().values().map(|v| v.len()).sum()
    }
}

impl ScratchBackend for InMemoryScratchBackend {
    fn init_session(&self, _session_id: &str) -> Result<(), String> {
        Ok(())
    }

    fn write_tiles(&self, session_id: &str, tiles: Vec<ScratchTileWrite>) -> Result<usize, String> {
        let count = tiles.len();
        let mut guard = self.store.write();
        for t in tiles {
            let compressed = lz4_flex::compress_prepend_size(&t.data);
            guard.insert((session_id.to_string(), t.layer_key, t.tx, t.ty), compressed);
        }
        Ok(count)
    }

    fn read_tile(
        &self,
        session_id: &str,
        layer_key: &str,
        tx: i32,
        ty: i32,
    ) -> Result<Vec<u8>, String> {
        let guard = self.store.read();
        let compressed = guard
            .get(&(session_id.to_string(), layer_key.to_string(), tx, ty))
            .ok_or_else(|| {
                format!(
                    "Tile not found in InMemoryScratchBackend (session={session_id}, layer={layer_key}, [{tx},{ty}])"
                )
            })?;
        lz4_flex::decompress_size_prepended(compressed)
            .map_err(|e| format!("Failed to decompress scratch tile: {e}"))
    }

    fn clear_session(&self, session_id: &str) -> Result<(), String> {
        let mut guard = self.store.write();
        guard.retain(|(sid, _, _, _), _| sid != session_id);
        Ok(())
    }
}

/// Standalone filesystem-backed scratch disk for pure-Rust / non-Tauri hosts.
pub struct FileScratchBackend {
    base_dir: PathBuf,
    use_lz4: bool,
}

impl FileScratchBackend {
    pub fn new(base_dir: PathBuf, use_lz4: bool) -> Self {
        Self { base_dir, use_lz4 }
    }

    fn sanitize(raw: &str) -> String {
        let s: String = raw
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                    c
                } else {
                    '_'
                }
            })
            .collect();
        if s.is_empty() {
            "default".to_string()
        } else {
            s
        }
    }

    fn tile_path(&self, session_id: &str, layer_key: &str, tx: i32, ty: i32) -> PathBuf {
        self.base_dir
            .join(Self::sanitize(session_id))
            .join(format!("{}_{}_{}.tile", Self::sanitize(layer_key), tx, ty))
    }
}

impl ScratchBackend for FileScratchBackend {
    fn init_session(&self, session_id: &str) -> Result<(), String> {
        let dir = self.base_dir.join(Self::sanitize(session_id));
        std::fs::create_dir_all(&dir)
            .map_err(|e| format!("Failed to create scratch session dir: {e}"))
    }

    fn write_tiles(&self, session_id: &str, tiles: Vec<ScratchTileWrite>) -> Result<usize, String> {
        self.init_session(session_id)?;
        let count = tiles.len();
        for t in tiles {
            let path = self.tile_path(session_id, &t.layer_key, t.tx, t.ty);
            let mut payload = Vec::with_capacity(t.data.len() + 1);
            if self.use_lz4 {
                payload.push(1);
                payload.extend_from_slice(&lz4_flex::compress_prepend_size(&t.data));
            } else {
                payload.push(0);
                payload.extend_from_slice(&t.data);
            }
            std::fs::write(&path, &payload)
                .map_err(|e| format!("Failed to write scratch tile {}: {e}", path.display()))?;
        }
        Ok(count)
    }

    fn read_tile(
        &self,
        session_id: &str,
        layer_key: &str,
        tx: i32,
        ty: i32,
    ) -> Result<Vec<u8>, String> {
        let path = self.tile_path(session_id, layer_key, tx, ty);
        let bytes = std::fs::read(&path)
            .map_err(|e| format!("Failed to read scratch tile {}: {e}", path.display()))?;
        let (&flag, rest) = bytes
            .split_first()
            .ok_or_else(|| "Corrupt empty scratch tile file".to_string())?;
        if flag == 1 {
            lz4_flex::decompress_size_prepended(rest)
                .map_err(|e| format!("Failed to LZ4-decompress scratch tile: {e}"))
        } else {
            Ok(rest.to_vec())
        }
    }

    fn clear_session(&self, session_id: &str) -> Result<(), String> {
        let dir = self.base_dir.join(Self::sanitize(session_id));
        if dir.exists() {
            std::fs::remove_dir_all(&dir)
                .map_err(|e| format!("Failed to remove scratch dir {}: {e}", dir.display()))?;
        }
        Ok(())
    }
}