Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
The library opens, is rebuilt, or says why — never a panic at launch
Yashwanth Kamireddie736b7e8fde3
diff --git a/Cargo.lock b/Cargo.lockindex 7685fd8..337cffa 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3871,6 +3871,7 @@ dependencies = ["quince-media","quince-vfs","reqwest 0.12.28",+ "rfd","serde","serde_json","sha2",diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rsindex 6c28e52..890ca5d 100644--- a/crates/quince-core/src/lib.rs+++ b/crates/quince-core/src/lib.rs@@ -23,10 +23,62 @@ use std::path::Path;#[derive(Debug, thiserror::Error)]pub enum Error {- #[error("the local library couldn't be opened: {0}")]+ /// Any SQLite error, on opening or on any read or write after: "couldn't be opened" was+ /// said for a full disk on a write and for a broken constraint alike, and misled.+ #[error("the local library couldn't be read or saved: {0}")]Sqlite(#[from] rusqlite::Error),#[error(transparent)]Io(#[from] std::io::Error),+ /// The library was last opened by a newer Skykeep, whose schema this one does not know:+ /// written to by this one, its tables and triggers could break for both.+ #[error(+ "this library was made by a newer version of Skykeep (library version {found}; this \+ version knows up to {known}). Install the newer version again to open it"+ )]+ Newer { found: u32, known: u32 },+}++/// What stands in the way of a library that will not open, where it is the computer's.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Trouble {+ /// No space left on the disk.+ Full,+ /// The folder, or the disk it is on, cannot be written to.+ ReadOnly,+ /// Another program holds the library's lock.+ Busy,+}++impl Error {+ /// The computer's part in this error, if it is one a person can fix there.+ #[must_use]+ pub fn trouble(&self) -> Option<Trouble> {+ use rusqlite::ErrorCode;+ match self {+ Error::Sqlite(rusqlite::Error::SqliteFailure(f, _)) => match f.code {+ ErrorCode::DiskFull => Some(Trouble::Full),+ ErrorCode::ReadOnly | ErrorCode::PermissionDenied | ErrorCode::CannotOpen => {+ Some(Trouble::ReadOnly)+ }+ ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked => Some(Trouble::Busy),+ _ => None,+ },+ Error::Io(e) => io_trouble(e),+ Error::Sqlite(_) | Error::Newer { .. } => None,+ }+ }++ /// The library file is damaged or not a database at all: set aside and made again+ /// ([`Library::open_or_recover`]), never written over.+ #[must_use]+ pub fn is_corrupt(&self) -> bool {+ use rusqlite::ErrorCode::{DatabaseCorrupt, NotADatabase};+ matches!(+ self,+ Error::Sqlite(rusqlite::Error::SqliteFailure(e, _))+ if matches!(e.code, DatabaseCorrupt | NotADatabase)+ )+ }}pub type Result<T> = std::result::Result<T, Error>;@@ -47,18 +99,39 @@ fn account_tables(conn: &Connection) -> Result<Vec<String>> {Ok(rows.collect::<std::result::Result<_, _>>()?)}+/// Ids as one JSON array, for `x NOT IN (SELECT value FROM json_each(?))`: one parameter+/// however many there are. A parameter each passed SQLite's limit of 32,766 on a Drive folder+/// or an address book that large, and its store failed on every pass.+pub(crate) fn id_list(ids: &[&str]) -> String {+ serde_json::to_string(ids).unwrap_or_else(|_| "[]".into())+}++/// A migration's part that SQL cannot do, run in the same transaction as the migration whose+/// number it carries.+pub type Fixup = (u32, fn(&rusqlite::Transaction<'_>) -> Result<()>);+/// Run every migration past the library's version, each with its version bump as one/// transaction: a migration that fails part way, or a crash in the middle of one, leaves the/// library at the version before it with none of it applied — never half a schema change/// that the next open would try to make again over itself, nor a change made whose version/// was never written.-fn migrate_with(conn: &mut Connection, migrations: &[&str]) -> Result<()> {+fn migrate_with(conn: &mut Connection, migrations: &[&str], fixups: &[Fixup]) -> Result<()> {let current: u32 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;+ let known = u32::try_from(migrations.len()).unwrap_or(u32::MAX);+ if current > known {+ return Err(Error::Newer {+ found: current,+ known,+ });+ }for (version, sql) in migrations.iter().enumerate() {let target = u32::try_from(version).unwrap_or(u32::MAX) + 1;if current < target {let tx = conn.transaction()?;tx.execute_batch(sql)?;+ for (_, fixup) in fixups.iter().filter(|(at, _)| *at == target) {+ fixup(&tx)?;+ }// `user_version` lives in the database header, written inside the transaction.tx.pragma_update(None, "user_version", i64::from(target))?;tx.commit()?;@@ -67,9 +140,71 @@ fn migrate_with(conn: &mut Connection, migrations: &[&str]) -> Result<()> {Ok(())}+/// [`Error::trouble`] for a failure of the file system itself.+#[must_use]+pub fn io_trouble(e: &std::io::Error) -> Option<Trouble> {+ use std::io::ErrorKind;+ match e.kind() {+ ErrorKind::StorageFull | ErrorKind::QuotaExceeded => Some(Trouble::Full),+ ErrorKind::PermissionDenied | ErrorKind::ReadOnlyFilesystem => Some(Trouble::ReadOnly),+ _ => None,+ }+}++/// Fold a library's log into the library itself, so the one file holds every commit: before+/// the file is moved. Answers whether that was done in full.+#[must_use]+pub fn checkpoint(db: &Path) -> bool {+ let Ok(conn) = Connection::open(db) else {+ return false;+ };+ let _ = conn.busy_timeout(std::time::Duration::from_secs(5));+ conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| {+ r.get::<_, i64>(0)+ })+ .is_ok_and(|busy| busy == 0)+}++/// A library opened by [`Library::open_or_recover`]: where a damaged one was set aside, and+/// how many of its rows were carried over.+pub struct Opened {+ pub library: Library,+ pub set_aside: Option<std::path::PathBuf>,+ pub salvaged: usize,+}++/// Move a damaged `library.db`, and its `-wal` and `-shm` beside it, to+/// `library.corrupt-<time>.db…`: out of the way of a new one, and kept for whatever can be+/// got out of it. Answers the set-aside database's path.+fn set_aside(dir: &Path) -> Result<std::path::PathBuf> {+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| d.as_secs());+ let mut name = format!("library.corrupt-{stamp}.db");+ let mut n = 1;+ while dir.join(&name).exists() {+ name = format!("library.corrupt-{stamp}-{n}.db");+ n += 1;+ }+ let aside = dir.join(&name);+ // The log and its index first: a database moved without them would be read, under its+ // old name, by the next open as a new library's.+ for suffix in ["-wal", "-shm"] {+ let from = dir.join(format!("library.db{suffix}"));+ if from.exists() {+ std::fs::rename(&from, dir.join(format!("{name}{suffix}")))?;+ }+ }+ std::fs::rename(dir.join("library.db"), &aside)?;+ Ok(aside)+}+/// A handle to the local library.pub struct Library {conn: Connection,+ /// The zone all-day and floating events are read and stored in: this computer's, asked+ /// each time (`None`), so a change of zone is seen at once — or one given, for tests.+ zone: Option<jiff::tz::TimeZone>,}impl Library {@@ -79,6 +214,102 @@ impl Library {Self::from_connection(Connection::open(dir.join("library.db"))?)}+ /// [`Library::open`], and when the file is damaged — a power cut on a cheap disk, a bad+ /// sector, a sync tool that touched the folder — set it aside under a new name (kept,+ /// never deleted), make the library again, and carry over what exists nowhere else: the+ /// changes waiting for Apple, the uploads waiting to go, and this computer's settings, as+ /// far as they can still be read. Everything else is Apple's and comes back with the next+ /// pass. Any other failure — a full disk, a folder that can't be written, a library from+ /// a newer Skykeep — is returned as it is, for the person to be told.+ pub fn open_or_recover(dir: &Path) -> Result<Opened> {+ match Self::open(dir) {+ Ok(library) => Ok(Opened {+ library,+ set_aside: None,+ salvaged: 0,+ }),+ Err(e) if e.is_corrupt() => {+ let aside = set_aside(dir)?;+ let mut library = Self::open(dir)?;+ let salvaged = library.salvage(&aside);+ Ok(Opened {+ library,+ set_aside: Some(aside),+ salvaged,+ })+ }+ Err(e) => Err(e),+ }+ }++ /// Copy what only this computer holds out of a set-aside library: every row that can+ /// still be read, stopping at the first that can't. Answers how many came over.+ fn salvage(&mut self, from: &Path) -> usize {+ use rusqlite::OpenFlags;+ let Ok(old) = Connection::open_with_flags(from, OpenFlags::SQLITE_OPEN_READ_ONLY) else {+ return 0;+ };+ let computer = format!("SELECT * FROM app_state WHERE {COMPUTER_KEYS}");+ let mut moved = 0;+ for (table, select) in [+ ("outbox", "SELECT * FROM outbox ORDER BY id".to_string()),+ ("photo_uploads", "SELECT * FROM photo_uploads".to_string()),+ ("app_state", computer),+ ] {+ moved += self.carry_over(&old, table, &select);+ }+ moved+ }++ /// Rows of `select` on `old` into this library's `table`, by the columns both have.+ fn carry_over(&mut self, old: &Connection, table: &str, select: &str) -> usize {+ let Ok(mut stmt) = old.prepare(select) else {+ return 0;+ };+ let theirs: Vec<String> = stmt+ .column_names()+ .iter()+ .map(|c| (*c).to_string())+ .collect();+ let ours: Vec<String> = self+ .conn+ .prepare(&format!("SELECT * FROM {table} LIMIT 0"))+ .map(|s| s.column_names().iter().map(|c| (*c).to_string()).collect())+ .unwrap_or_default();+ let shared: Vec<(usize, &String)> = theirs+ .iter()+ .enumerate()+ .filter(|(_, c)| ours.contains(c))+ .collect();+ if shared.is_empty() {+ return 0;+ }+ let names: Vec<&str> = shared.iter().map(|(_, c)| c.as_str()).collect();+ let marks = vec!["?"; names.len()].join(", ");+ let insert = format!(+ "INSERT OR REPLACE INTO {table} ({}) VALUES ({marks})",+ names.join(", ")+ );+ let Ok(mut rows) = stmt.query([]) else {+ return 0;+ };+ let mut moved = 0;+ // Each row as it is read: a damaged page part way keeps every row before it.+ while let Ok(Some(row)) = rows.next() {+ let values: rusqlite::Result<Vec<rusqlite::types::Value>> =+ shared.iter().map(|(i, _)| row.get(*i)).collect();+ let Ok(values) = values else { break };+ if self+ .conn+ .execute(&insert, rusqlite::params_from_iter(values))+ .is_ok()+ {+ moved += 1;+ }+ }+ moved+ }+/// A second, read-only handle on the library under `dir`, which must already be open (and/// migrated) through [`Library::open`]: WAL lets it read while the one that writes holds its/// lock through a sync pass, so a search never waits behind one. It sees what was@@ -91,7 +322,7 @@ impl Library {)?;conn.pragma_update(None, "query_only", true)?;conn.busy_timeout(std::time::Duration::from_millis(250))?;- Ok(Self { conn })+ Ok(Self { conn, zone: None })}/// An in-memory library. Tests, and nothing else.@@ -100,20 +331,26 @@ impl Library {}fn from_connection(conn: Connection) -> Result<Self> {+ // Another handle holding the write lock — a reader checkpointing, a second Skykeep+ // starting as the first ends — is waited out rather than failed on at once: with no+ // wait, a launch that met it failed to open the library at all.+ conn.busy_timeout(std::time::Duration::from_secs(5))?;// WAL lets the sync engine write while the interface reads, which is the normal- // state of this app. NORMAL is the right durability trade for a cache that can- // always be refetched from Apple.+ // state of this app. FULL, not NORMAL: most of the library is a cache Apple can give+ // again, but the outbox and the uploads waiting are changes made here that exist+ // nowhere else, and under NORMAL the last commits before a power cut can be rolled+ // back. In WAL, FULL is one sync per commit — nothing at the pace edits are made.conn.pragma_update(None, "journal_mode", "WAL")?;- conn.pragma_update(None, "synchronous", "NORMAL")?;+ conn.pragma_update(None, "synchronous", "FULL")?;conn.pragma_update(None, "foreign_keys", "ON")?;- let mut library = Self { conn };+ let mut library = Self { conn, zone: None };library.migrate()?;Ok(library)}/// Bring the schema up to date. Idempotent, and safe to call on every open.fn migrate(&mut self) -> Result<()> {- migrate_with(&mut self.conn, schema::MIGRATIONS)+ migrate_with(&mut self.conn, schema::MIGRATIONS, schema::FIXUPS)}/// Run `apply` as one change to the library: everything it stores lands, or — if it@@ -300,6 +537,136 @@ impl Library {mod tests {use super::*;+ /// A damaged library is set aside — kept — and made again, with the changes still+ /// waiting for Apple and this computer's settings carried over. It used to stop the app+ /// at launch with no word at all.+ #[test]+ fn a_damaged_library_is_set_aside_and_its_waiting_changes_kept() {+ let dir = tempfile::tempdir().unwrap();+ {+ let mut lib = Library::open(dir.path()).unwrap();+ lib.outbox_push("reminders", "R1", "done", r#"{"done":true,"at":1}"#)+ .unwrap();+ lib.set_state("settings.alerts", "on").unwrap();+ lib.set_state("account", "someone").unwrap();+ }+ // Damaged after the header: SQLite's first read of the schema fails.+ let db = dir.path().join("library.db");+ let mut bytes = std::fs::read(&db).unwrap();+ let page = 4096.min(bytes.len());+ for b in &mut bytes[100..page] {+ *b = 0xA5;+ }+ std::fs::write(&db, &bytes).unwrap();+ assert!(Library::open(dir.path())+ .err()+ .is_some_and(|e| e.is_corrupt()));++ let opened = Library::open_or_recover(dir.path()).unwrap();+ let aside = opened.set_aside.expect("set aside");+ assert!(aside.exists(), "the damaged library is kept");+ assert_eq!(std::fs::read(&aside).unwrap(), bytes, "exactly as it was");+ let mut lib = opened.library;+ // Damage to the schema page leaves nothing readable here; what could be read is kept+ // (below). Either way the new library opens and works.+ lib.outbox_push("reminders", "R2", "done", "{}").unwrap();+ }++ #[test]+ fn what_can_still_be_read_is_carried_over() {+ let dir = tempfile::tempdir().unwrap();+ let old = dir.path().join("old.db");+ {+ let mut lib = Library::from_connection(Connection::open(&old).unwrap()).unwrap();+ lib.outbox_push("reminders", "R1", "done", r#"{"done":true,"at":1}"#)+ .unwrap();+ lib.set_state("settings.alerts", "on").unwrap();+ lib.set_state("account", "someone").unwrap();+ lib.conn+ .execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")+ .unwrap();+ }+ let mut fresh = Library::in_memory().unwrap();+ assert_eq!(fresh.salvage(&old), 2, "the change waiting and the setting");+ assert_eq!(fresh.outbox_count().unwrap(), 1);+ assert_eq!(+ fresh.state("settings.alerts").unwrap().as_deref(),+ Some("on")+ );+ assert_eq!(+ fresh.state("account").unwrap(),+ None,+ "the account's own is not"+ );+ }++ /// A library from a newer Skykeep is refused, untouched, rather than written to by a+ /// version that does not know its tables.+ #[test]+ fn a_library_from_a_newer_version_is_refused_untouched() {+ let dir = tempfile::tempdir().unwrap();+ drop(Library::open(dir.path()).unwrap());+ let newer = u32::try_from(schema::MIGRATIONS.len()).unwrap() + 2;+ Connection::open(dir.path().join("library.db"))+ .unwrap()+ .pragma_update(None, "user_version", newer)+ .unwrap();+ let err = Library::open_or_recover(dir.path()).err().unwrap();+ assert!(+ matches!(err, Error::Newer { found, .. } if found == newer),+ "{err}"+ );+ assert!(err.to_string().contains("newer version of Skykeep"));+ let still: u32 = Connection::open(dir.path().join("library.db"))+ .unwrap()+ .query_row("PRAGMA user_version", [], |r| r.get(0))+ .unwrap();+ assert_eq!(still, newer);+ }++ #[test]+ fn a_full_disk_and_a_folder_that_cannot_be_written_are_named() {+ let code = |c| {+ Error::Sqlite(rusqlite::Error::SqliteFailure(+ rusqlite::ffi::Error::new(c),+ None,+ ))+ };+ assert_eq!(+ code(rusqlite::ffi::SQLITE_FULL).trouble(),+ Some(Trouble::Full)+ );+ assert_eq!(+ code(rusqlite::ffi::SQLITE_READONLY).trouble(),+ Some(Trouble::ReadOnly)+ );+ assert_eq!(+ code(rusqlite::ffi::SQLITE_BUSY).trouble(),+ Some(Trouble::Busy)+ );+ let io = Error::Io(std::io::ErrorKind::ReadOnlyFilesystem.into());+ assert_eq!(io.trouble(), Some(Trouble::ReadOnly));+ assert!(code(rusqlite::ffi::SQLITE_CORRUPT).is_corrupt());+ }++ /// The writer waits for a lock another handle holds, rather than failing at once; and+ /// commits are synced in full, for the changes that exist only here.+ #[test]+ fn the_writer_waits_for_the_lock_and_syncs_in_full() {+ let dir = tempfile::tempdir().unwrap();+ let lib = Library::open(dir.path()).unwrap();+ let wait: i64 = lib+ .conn+ .query_row("PRAGMA busy_timeout", [], |r| r.get(0))+ .unwrap();+ assert!(wait >= 5_000, "{wait}");+ let sync: i64 = lib+ .conn+ .query_row("PRAGMA synchronous", [], |r| r.get(0))+ .unwrap();+ assert_eq!(sync, 2, "FULL");+ }+/// Another account signing in finds nothing of the last one's, and this computer's own/// choices still where they were.#[test]@@ -363,7 +730,7 @@ mod tests {let good = "CREATE TABLE a (x INTEGER);";// The first statement would succeed on its own; the second fails.let bad = "CREATE TABLE b (x INTEGER); INSERT INTO nowhere VALUES (1);";- assert!(migrate_with(&mut conn, &[good, bad]).is_err());+ assert!(migrate_with(&mut conn, &[good, bad], &[]).is_err());let version: u32 = conn.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap();@@ -379,7 +746,7 @@ mod tests {assert!(has(&conn, "a"), "the migration before it stays");assert!(!has(&conn, "b"), "nothing of the failed one persists");let fixed = "CREATE TABLE b (x INTEGER);";- migrate_with(&mut conn, &[good, fixed]).unwrap();+ migrate_with(&mut conn, &[good, fixed], &[]).unwrap();assert!(has(&conn, "b"));let version: u32 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))@@ -400,6 +767,7 @@ mod tests {"CREATE TABLE a (x INTEGER);","ALTER TABLE a ADD COLUMN y INTEGER; SELECT RAISE(ABORT, 'boom');",],+ &[],);}let conn = Connection::open(&path).unwrap();diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex ede8bc3..87a7367 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -29,6 +29,8 @@ jiff = "0.2.37"uuid.workspace = truebase64 = "0.22"tauri-plugin-dialog = "2.7.3"+# The one dialog shown before the window can be: a library that will not open.+rfd = { version = "0.16", default-features = false }tauri-plugin-opener = "2"notify-rust = "4"tauri-plugin-single-instance = "2"diff --git a/src-tauri/src/library_lock.rs b/src-tauri/src/library_lock.rsindex 9a815c4..d8830b7 100644--- a/src-tauri/src/library_lock.rs+++ b/src-tauri/src/library_lock.rs@@ -346,3 +346,64 @@ mod tests {use std::time::Duration;}++/// The one Skykeep that has this library, as long as it runs: an exclusive lock on+/// `skykeep.lock` beside it (`flock` on Linux, a file opened shared with nobody on Windows), let+/// go of by the system however the process ends.+///+/// The single-instance plugin finds a running Skykeep on the session bus, and with no session+/// bus (over SSH, after `su`, some kiosks) it found none and a second one ran: both sending+/// what waits for Apple — the same change twice — both mounting the folders, and each one's+/// writes failing on the other's lock. `None`: another Skykeep holds it.+pub fn hold(dir: &Path) -> std::io::Result<Option<std::fs::File>> {+ std::fs::create_dir_all(dir)?;+ let mut options = std::fs::OpenOptions::new();+ options.create(true).truncate(false).write(true);+ // Windows: opened shared with nobody, which is the lock — a second open is refused with a+ // sharing violation until this handle closes.+ #[cfg(windows)]+ {+ use std::os::windows::fs::OpenOptionsExt;+ options.share_mode(0);+ }+ let file = match options.open(dir.join("skykeep.lock")) {+ Ok(file) => file,+ #[cfg(windows)]+ Err(e) if e.raw_os_error() == Some(32) => return Ok(None),+ Err(e) => return Err(e),+ };+ #[cfg(unix)]+ {+ use std::os::unix::io::AsRawFd;+ // SAFETY: flock on a descriptor this function owns; nothing else is touched.+ if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {+ let e = std::io::Error::last_os_error();+ return if e.raw_os_error() == Some(libc::EWOULDBLOCK) {+ Ok(None)+ } else {+ Err(e)+ };+ }+ }+ Ok(Some(file))+}++#[cfg(test)]+mod hold_tests {+ use super::*;++ #[test]+ fn only_one_holds_the_library() {+ let dir = tempfile::tempdir().unwrap();+ let first = hold(dir.path()).unwrap().expect("the first holds it");+ assert!(+ hold(dir.path()).unwrap().is_none(),+ "a second is turned away"+ );+ drop(first);+ assert!(+ hold(dir.path()).unwrap().is_some(),+ "free again once the first is gone"+ );+ }+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 345383d..6632a53 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -971,10 +971,66 @@ fn keep_private(dir: &std::path::Path) {}}+/// The library could not be opened: said in a window of its own, with where it is, and the app+/// ends — never a panic. A release build on Windows has no console, so a launch that failed+/// here showed nothing at all, every time.+fn cannot_start(dir: &std::path::Path, why: &str) -> ! {+ let text = format!(+ "{why}\n\nNothing in it has been changed or removed. Your library is in:\n{}",+ dir.display()+ );+ eprintln!("Skykeep couldn’t start: {text}");+ let _ = rfd::MessageDialog::new()+ .set_level(rfd::MessageLevel::Error)+ .set_title("Skykeep couldn’t open your library")+ .set_description(&text)+ .set_buttons(rfd::MessageButtons::Ok)+ .show();+ std::process::exit(1)+}++/// Why the library would not open, as a person can act on it.+fn library_problem(e: &quince_core::Error) -> String {+ e.trouble().map_or_else(|| e.to_string(), trouble_words)+}++/// [`library_problem`] for the folder itself.+fn folder_problem(e: &std::io::Error) -> String {+ quince_core::io_trouble(e).map_or_else(+ || format!("Skykeep’s folder couldn’t be used: {e}"),+ trouble_words,+ )+}++fn trouble_words(t: quince_core::Trouble) -> String {+ match t {+ quince_core::Trouble::Full => "The disk is full. Free some space, then open Skykeep again.",+ quince_core::Trouble::ReadOnly => {+ "Skykeep can’t write to its folder. Check that the folder below, and the disk it is \+ on, can be written to, then open Skykeep again."+ }+ quince_core::Trouble::Busy => {+ "Another program is holding the library — most likely another Skykeep still \+ closing. Wait a moment, then open Skykeep again."+ }+ }+ .to_string()+}+fn state_dir(app: &tauri::AppHandle) -> PathBuf {- app.path()+ let roaming = app+ .path().app_data_dir()- .unwrap_or_else(|_| PathBuf::from(".").join("quince"))+ .unwrap_or_else(|_| PathBuf::from(".").join("quince"));+ // Windows: Local app data, once the library has moved there (migrate::to_local); still+ // Roaming while a move could not be made.+ #[cfg(windows)]+ if let Ok(local) = app.path().app_local_data_dir() {+ if local.join("library.db").exists() || !roaming.join("library.db").exists() {+ return local;+ }+ }+ roaming}#[tauri::command]@@ -5913,7 +5969,25 @@ fn main() {video::serve(app.handle().clone());let dir = state_dir(app.handle());keep_private(&dir);- let client = Client::new(&dir)?;+ // A second Skykeep the session bus could not stop (there is none): it ends here,+ // before it touches the library, sends anything or mounts a folder.+ static HELD: std::sync::OnceLock<std::fs::File> = std::sync::OnceLock::new();+ match library_lock::hold(&dir) {+ Ok(Some(lock)) => {+ let _ = HELD.set(lock);+ }+ Ok(None) => {+ eprintln!("Skykeep is already running.");+ std::process::exit(0);+ }+ // Somewhere a lock can't be taken (a share that refuses them): run as before.+ Err(e) => quiet!("the library's lock could not be taken: {e}"),+ }+ let client = match Client::new(&dir) {+ Ok(client) => client,+ Err(quince_auth::Error::Io(e)) => cannot_start(&dir, &folder_problem(&e)),+ Err(e) => cannot_start(&dir, &e.to_string()),+ };let known = std::sync::Mutex::new(SessionFacts::of(&client));let client = Arc::new(Mutex::new(client));app.manage(Auth {@@ -5923,7 +5997,18 @@ fn main() {});// The local library. Opened once at startup so every command shares one// connection and the WAL behaves.- let mut library = Library::open(&dir)?;+ let opened = match Library::open_or_recover(&dir) {+ Ok(opened) => opened,+ Err(e) => cannot_start(&dir, &library_problem(&e)),+ };+ if let Some(aside) = &opened.set_aside {+ quiet!(+ "the library was damaged: set aside at {} and made again ({} rows kept)",+ aside.display(),+ opened.salvaged+ );+ }+ let mut library = opened.library;timing::mark("library open");adopt_writer(&mut library);app.manage(Data(library_lock::LibraryLock::new(@@ -6617,3 +6702,91 @@ mod tests {assert!(again.try_lock().is_ok());}}++#[cfg(test)]+mod start_tests {+ use super::*;++ #[test]+ fn a_library_that_will_not_open_is_explained() {+ let io = std::io::Error::from(std::io::ErrorKind::ReadOnlyFilesystem);+ assert!(folder_problem(&io).contains("can’t write to its folder"));+ let full = quince_core::Error::Io(std::io::ErrorKind::StorageFull.into());+ assert!(library_problem(&full).starts_with("The disk is full"));+ let newer = quince_core::Error::Newer {+ found: 99,+ known: 48,+ };+ assert!(library_problem(&newer).contains("newer version of Skykeep"));+ }++ /// A picture is written whole or not at all, and a contact keeps only its newest.+ #[tokio::test]+ async fn pictures_are_written_whole_and_one_face_is_kept() {+ let dir = tempfile::tempdir().unwrap();+ let guid = "0D8D2C3B-6C1E-4C9B-9E57-3A1B2C3D4E5F";+ let other = "1D8D2C3B-6C1E-4C9B-9E57-3A1B2C3D4E5F";+ let old = photo_path(dir.path(), guid, "first");+ let theirs = photo_path(dir.path(), other, "x");+ std::fs::create_dir_all(old.parent().unwrap()).unwrap();+ write_whole(&old, b"before").await.unwrap();+ write_whole(&theirs, b"someone else").await.unwrap();+ let new = photo_path(dir.path(), guid, "second");+ write_whole(&new, b"after").await.unwrap();+ forget_older_faces(&new);+ assert!(!old.exists(), "the older picture goes");+ assert_eq!(std::fs::read(&new).unwrap(), b"after");+ assert!(theirs.exists(), "another contact's stays");+ let left: Vec<_> = std::fs::read_dir(new.parent().unwrap()).unwrap().collect();+ assert_eq!(left.len(), 2, "no part files left behind");+ // A write that cannot land leaves nothing, not a cut-off file.+ let nowhere = dir.path().join("missing").join("x");+ assert!(write_whole(&nowhere, b"z").await.is_err());+ assert!(!nowhere.exists());+ }++ /// After a lapse the heartbeat waits for a new sign-in, and keeps that one warm.+ #[test]+ fn the_heartbeat_comes_back_for_the_next_sign_in() {+ let old = Some("old".to_string());+ assert!(worth_a_ping(true, &old, None));+ assert!(+ !worth_a_ping(true, &old, Some(&old)),+ "the lapsed one rests"+ );+ assert!(+ worth_a_ping(true, &Some("new".into()), Some(&old)),+ "a new one is kept warm"+ );+ assert!(!worth_a_ping(false, &None, None));+ }++ /// Every folder of one account's pictures goes with the account: a reminder's too, which+ /// stayed behind for the next person to sign in on this computer.+ #[test]+ fn an_accounts_reminder_pictures_go_with_it() {+ assert!(ACCOUNT_FILES.contains(&"reminder-media"));+ }++ /// The packages say what the binary needs, so an older system is refused at install with+ /// the package manager's message, not at launch with `GLIBC_2.39 not found`.+ #[test]+ fn the_packages_declare_the_floor_they_are_built_for() {+ let conf: serde_json::Value =+ serde_json::from_str(include_str!("../tauri.conf.json")).unwrap();+ let depends = |kind: &str| -> Vec<String> {+ conf["bundle"]["linux"][kind]["depends"]+ .as_array()+ .unwrap()+ .iter()+ .map(|d| d.as_str().unwrap().to_string())+ .collect()+ };+ let deb = depends("deb");+ assert!(deb.contains(&"libc6 (>= 2.39)".to_string()), "{deb:?}");+ assert!(deb.contains(&"libheif1 (>= 1.17)".to_string()), "{deb:?}");+ let rpm = depends("rpm");+ assert!(rpm.contains(&"glibc >= 2.39".to_string()), "{rpm:?}");+ assert!(rpm.iter().any(|d| d.contains("libheif >= 1.17")), "{rpm:?}");+ }+}