Skip to main content

smriti/services/
cache_location.rs

1//! Where a library's rebuildable caches live: by default inside the library
2//! (`<library>/.photovault/thumbnails` and `.../faces`), or on this computer.
3//!
4//! A library on an external hard drive keeps tens of thousands of small
5//! thumbnail and face-crop files, and spinning disks are slow at exactly
6//! that. Those files can always be rebuilt from the photos, so this
7//! computer may keep them on its own (usually much faster) disk instead.
8//! The database stays with the photos, so the library remains portable.
9//!
10//! The choice belongs to the computer, not the library: it is kept in this
11//! computer's settings under the library's id. Another computer simply uses
12//! the copies inside the library, or rebuilds missing ones.
13//!
14//! Stored paths never change (`.photovault/thumbnails/...`); they are
15//! resolved here, so every reader and writer that goes through
16//! [`crate::services::path_util::safe_join_relative`],
17//! [`thumbnails_dir`] or [`faces_dir`] follows the choice.
18
19use std::collections::HashMap;
20use std::path::{Component, Path, PathBuf};
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::RwLock;
23
24use rusqlite::{params, Connection, OptionalExtension};
25
26use crate::db::LIBRARY_METADATA_DIR;
27
28/// The caches that may move: rebuildable, many small files.
29pub const MOVABLE: [&str; 2] = ["thumbnails", "faces"];
30
31/// Open libraries whose caches are on this computer: library root -> the
32/// folder holding `thumbnails/` and `faces/`.
33static PLACED: std::sync::LazyLock<RwLock<HashMap<PathBuf, PathBuf>>> =
34    std::sync::LazyLock::new(Default::default);
35
36/// Keep `root`'s caches in `base` from now on, or (with `None`) inside the
37/// library again.
38pub fn place(root: &Path, base: Option<PathBuf>) {
39    let mut placed = PLACED.write().unwrap_or_else(|e| e.into_inner());
40    match base {
41        Some(base) => placed.insert(root.to_path_buf(), base),
42        None => placed.remove(root),
43    };
44}
45
46/// The folder on this computer holding `root`'s caches, if they moved.
47pub fn local_base(root: &Path) -> Option<PathBuf> {
48    PLACED
49        .read()
50        .unwrap_or_else(|e| e.into_inner())
51        .get(root)
52        .cloned()
53}
54
55/// Where thumbnails are written for this library.
56pub fn thumbnails_dir(root: &Path) -> PathBuf {
57    cache_dir(root, "thumbnails")
58}
59
60/// Where face crops are written for this library.
61pub fn faces_dir(root: &Path) -> PathBuf {
62    cache_dir(root, "faces")
63}
64
65fn cache_dir(root: &Path, which: &str) -> PathBuf {
66    match local_base(root) {
67        Some(base) => base.join(which),
68        None => root.join(LIBRARY_METADATA_DIR).join(which),
69    }
70}
71
72/// Resolve a clean, library-relative path. Cache files go to this
73/// computer's copy when the caches moved; one not copied yet is read from
74/// the library until it is.
75pub(crate) fn resolve(root: &Path, clean: &Path) -> PathBuf {
76    let in_library = root.join(clean);
77    let Some(rest) = movable_rest(clean) else {
78        return in_library;
79    };
80    let Some(base) = local_base(root) else {
81        return in_library;
82    };
83    let local = base.join(rest);
84    if local.exists() || !in_library.exists() {
85        local
86    } else {
87        in_library
88    }
89}
90
91/// For `.photovault/<movable>/...`, the part after `.photovault/`.
92fn movable_rest(clean: &Path) -> Option<&Path> {
93    let mut parts = clean.components();
94    match (parts.next(), parts.next()) {
95        (Some(Component::Normal(meta)), Some(Component::Normal(cache)))
96            if meta == LIBRARY_METADATA_DIR && MOVABLE.iter().any(|m| cache == *m) =>
97        {
98            clean.strip_prefix(meta).ok()
99        }
100        _ => None,
101    }
102}
103
104/// This library's id, made on first use. It names the library in this
105/// computer's settings even when its drive letter or mount point changes.
106pub fn library_id(conn: &Connection) -> rusqlite::Result<String> {
107    if let Some(id) = conn
108        .query_row(
109            "SELECT value FROM library_meta WHERE key = 'library.id'",
110            [],
111            |row| row.get::<_, String>(0),
112        )
113        .optional()?
114        .filter(|id| !id.is_empty())
115    {
116        return Ok(id);
117    }
118    let id = new_id();
119    conn.execute(
120        "INSERT INTO library_meta (key, value) VALUES ('library.id', ?1)
121         ON CONFLICT(key) DO NOTHING",
122        params![id],
123    )?;
124    // Another writer may have won the race; theirs stands.
125    conn.query_row(
126        "SELECT value FROM library_meta WHERE key = 'library.id'",
127        [],
128        |row| row.get(0),
129    )
130}
131
132fn new_id() -> String {
133    use std::hash::{BuildHasher, Hasher};
134    let nanos = std::time::SystemTime::now()
135        .duration_since(std::time::UNIX_EPOCH)
136        .map(|d| d.as_nanos())
137        .unwrap_or_default();
138    let mut out = String::new();
139    for salt in 0..2u64 {
140        let mut h = std::collections::hash_map::RandomState::new().build_hasher();
141        h.write_u128(nanos);
142        h.write_u64(salt ^ u64::from(std::process::id()));
143        out.push_str(&format!("{:016x}", h.finish()));
144    }
145    out
146}
147
148/// Where this computer keeps a library's caches unless the user picks
149/// another folder.
150pub fn default_base(library_id: &str) -> Option<PathBuf> {
151    dirs::data_local_dir().map(|d| d.join("smriti").join("cache").join(library_id))
152}
153
154/// Progress through a copy: files done so far, and the total.
155pub type CopyProgress<'a> = dyn FnMut(u64, u64) + 'a;
156
157/// Copy the movable caches from `from` to `to` (each holding `thumbnails/`
158/// and `faces/`), skipping files already there at the same size. Stops
159/// early, without error, when `cancel` is set. Returns files copied.
160pub fn copy_caches(
161    from: &Path,
162    to: &Path,
163    cancel: &AtomicBool,
164    progress: &mut CopyProgress<'_>,
165) -> std::io::Result<u64> {
166    let files: Vec<(PathBuf, u64)> = MOVABLE
167        .iter()
168        .flat_map(|which| walkdir::WalkDir::new(from.join(which)).into_iter())
169        .filter_map(Result::ok)
170        .filter(|e| e.file_type().is_file())
171        .map(|e| {
172            let len = e.metadata().map(|m| m.len()).unwrap_or(0);
173            (e.into_path(), len)
174        })
175        .collect();
176    let total = files.len() as u64;
177    let mut copied = 0;
178    for (done, (file, len)) in files.into_iter().enumerate() {
179        if cancel.load(Ordering::Relaxed) {
180            break;
181        }
182        let Ok(rel) = file.strip_prefix(from) else {
183            continue;
184        };
185        let target = to.join(rel);
186        let same = std::fs::metadata(&target).is_ok_and(|m| m.len() == len);
187        if !same {
188            if let Some(parent) = target.parent() {
189                std::fs::create_dir_all(parent)?;
190            }
191            std::fs::copy(&file, &target)?;
192            copied += 1;
193        }
194        if done % 200 == 0 {
195            progress(done as u64, total);
196        }
197    }
198    progress(total, total);
199    Ok(copied)
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn only_thumbnails_and_faces_follow_the_choice() {
208        let root = PathBuf::from("/lib-under-test");
209        let base = PathBuf::from("/local-cache-under-test");
210        place(&root, Some(base.clone()));
211        assert_eq!(
212            resolve(&root, Path::new(".photovault/thumbnails/small/v2/ab/x.jpg")),
213            base.join("thumbnails/small/v2/ab/x.jpg")
214        );
215        assert_eq!(
216            resolve(&root, Path::new(".photovault/faces/7.jpg")),
217            base.join("faces/7.jpg")
218        );
219        assert_eq!(
220            resolve(&root, Path::new(".photovault/photovault.db")),
221            root.join(".photovault/photovault.db")
222        );
223        assert_eq!(
224            resolve(&root, Path::new("2019/goa.jpg")),
225            root.join("2019/goa.jpg")
226        );
227        assert_eq!(faces_dir(&root), base.join("faces"));
228        place(&root, None);
229        assert_eq!(faces_dir(&root), root.join(".photovault/faces"));
230    }
231
232    #[test]
233    fn a_file_not_copied_yet_is_read_from_the_library() {
234        let lib = tempfile::tempdir().unwrap();
235        let local = tempfile::tempdir().unwrap();
236        let rel = Path::new(".photovault/faces/1.jpg");
237        std::fs::create_dir_all(lib.path().join(".photovault/faces")).unwrap();
238        std::fs::write(lib.path().join(rel), b"x").unwrap();
239        place(lib.path(), Some(local.path().to_path_buf()));
240        assert_eq!(resolve(lib.path(), rel), lib.path().join(rel));
241        // A new file is written to this computer.
242        assert_eq!(
243            resolve(lib.path(), Path::new(".photovault/faces/2.jpg")),
244            local.path().join("faces/2.jpg")
245        );
246        place(lib.path(), None);
247    }
248
249    #[test]
250    fn copying_skips_files_already_there() {
251        let from = tempfile::tempdir().unwrap();
252        let to = tempfile::tempdir().unwrap();
253        for f in ["thumbnails/small/a.jpg", "faces/1.jpg", "other/skip.txt"] {
254            let p = from.path().join(f);
255            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
256            std::fs::write(p, b"data").unwrap();
257        }
258        let cancel = AtomicBool::new(false);
259        let copied = copy_caches(from.path(), to.path(), &cancel, &mut |_, _| {}).unwrap();
260        assert_eq!(copied, 2);
261        assert!(to.path().join("faces/1.jpg").exists());
262        assert!(!to.path().join("other").exists());
263        let again = copy_caches(from.path(), to.path(), &cancel, &mut |_, _| {}).unwrap();
264        assert_eq!(again, 0);
265    }
266
267    #[test]
268    fn a_library_keeps_its_id() {
269        let conn = Connection::open_in_memory().unwrap();
270        conn.execute_batch("CREATE TABLE library_meta (key TEXT PRIMARY KEY, value TEXT)")
271            .unwrap();
272        let id = library_id(&conn).unwrap();
273        assert_eq!(id.len(), 32);
274        assert_eq!(library_id(&conn).unwrap(), id);
275    }
276}