Skip to main content

capsule_library/library/
open.rs

1use std::path::Path;
2
3use capsule_core::sidecar::library_version::CURRENT_LIBRARY_VERSION;
4
5use crate::db::{DatabaseDriver, MigrationError};
6use crate::library::error::LibraryError;
7use crate::library::library::Library;
8use crate::library::lock;
9use crate::library::scrub::startup_scrub;
10use crate::sidecar_io::{read_library_config, read_library_version, write_library_config};
11
12/// Open an existing Capsule library at `root`.
13///
14/// Validates the version file, acquires the lock, runs a startup scrub if
15/// needed, and updates `last_opened_at`.
16pub fn open_library(root: &Path) -> Result<Library, LibraryError> {
17    // 1. Read and validate version.
18    let version_path = root.join(".library/version.cbor");
19    let version = read_library_version(&version_path)
20        .map_err(|e| LibraryError::CorruptVersion(e.to_string()))?;
21
22    if version.version != CURRENT_LIBRARY_VERSION {
23        return Err(LibraryError::VersionMismatch {
24            found: version.version,
25            expected: CURRENT_LIBRARY_VERSION,
26        });
27    }
28
29    // 2. Acquire lock.
30    lock::try_acquire(root)?;
31
32    // 3. Open DB (release lock on failure). A catalog stamped newer than this build is the
33    //    one open failure with its own recovery (update the app), so it keeps its type.
34    let db_path = root.join("index/library.sqlite");
35    let db = DatabaseDriver::open_typed(&db_path).map_err(|e| {
36        let _ = lock::release(root);
37        match e {
38            MigrationError::CatalogTooNew { found, supported } => {
39                LibraryError::CatalogTooNew { found, supported }
40            }
41            other => LibraryError::Db(other.into()),
42        }
43    })?;
44
45    // 4. Read config (release lock on failure).
46    let config_path = root.join(".library/config.cbor");
47    let mut config = read_library_config(&config_path).map_err(|e| {
48        let _ = lock::release(root);
49        LibraryError::Cbor(e.to_string())
50    })?;
51
52    // 5. Startup scrub (release lock on failure).
53    startup_scrub(root, &mut config).inspect_err(|_e| {
54        let _ = lock::release(root);
55    })?;
56
57    // 6. Update last_opened_at.
58    config.last_opened_at = now_secs();
59    write_library_config(&config_path, &config).map_err(|e| {
60        let _ = lock::release(root);
61        LibraryError::Cbor(e.to_string())
62    })?;
63
64    Ok(Library::new(root.to_path_buf(), db, config))
65}
66
67fn now_secs() -> i64 {
68    std::time::SystemTime::now()
69        .duration_since(std::time::UNIX_EPOCH)
70        .unwrap_or_default()
71        .as_secs() as i64
72}
73
74#[cfg(test)]
75mod tests;