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
Phase 1: the local library
Yashwanth Kamireddid49126e9c8a5
diff --git a/Cargo.lock b/Cargo.lockindex 88d4510..b28ef18 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8,6 +8,18 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"+[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "once_cell",+ "version_check",+ "zerocopy",+]+[[package]]name = "aho-corasick"version = "1.1.5"@@ -895,6 +907,18 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "fallible-iterator"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"++[[package]]+name = "fallible-streaming-iterator"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"+[[package]]name = "fastrand"version = "2.5.0"@@ -1394,12 +1418,30 @@ version = "0.12.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"+[[package]]+name = "hashbrown"+version = "0.14.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"+dependencies = [+ "ahash",+]+[[package]]name = "hashbrown"version = "0.17.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+[[package]]+name = "hashlink"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"+dependencies = [+ "hashbrown 0.14.5",+]+[[package]]name = "heck"version = "0.4.1"@@ -1977,6 +2019,17 @@ dependencies = ["libc",]+[[package]]+name = "libsqlite3-sys"+version = "0.30.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"+dependencies = [+ "cc",+ "pkg-config",+ "vcpkg",+]+[[package]]name = "linux-keyutils"version = "0.2.5"@@ -2749,6 +2802,16 @@ dependencies = ["wiremock",]+[[package]]+name = "quince-core"+version = "0.1.0"+dependencies = [+ "rusqlite",+ "serde",+ "tempfile",+ "thiserror 2.0.20",+]+[[package]]name = "quince-probe"version = "0.0.0"@@ -3088,6 +3151,20 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "rusqlite"+version = "0.32.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"+dependencies = [+ "bitflags 2.13.2",+ "fallible-iterator",+ "fallible-streaming-iterator",+ "hashlink",+ "libsqlite3-sys",+ "smallvec",+]+[[package]]name = "rustc-hash"version = "2.1.3"@@ -4414,6 +4491,12 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"+[[package]]name = "version-compare"version = "0.2.1"diff --git a/Cargo.toml b/Cargo.tomlindex ab7e7d5..5a6088c 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[workspace]resolver = "2"-members = ["probe", "crates/quince-auth", "src-tauri"]+members = ["probe", "crates/quince-auth", "crates/quince-core", "src-tauri"][workspace.package]edition = "2021"diff --git a/crates/quince-core/Cargo.toml b/crates/quince-core/Cargo.tomlnew file mode 100644index 0000000..88e43ae--- /dev/null+++ b/crates/quince-core/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "quince-core"+version = "0.1.0"+edition.workspace = true+rust-version.workspace = true+license.workspace = true++[dependencies]+rusqlite = { version = "0.32", features = ["bundled"] }+serde.workspace = true+thiserror = "2"++[dev-dependencies]+tempfile = "3"diff --git a/crates/quince-core/src/calendar.rs b/crates/quince-core/src/calendar.rsnew file mode 100644index 0000000..4dc8dde--- /dev/null+++ b/crates/quince-core/src/calendar.rs@@ -0,0 +1,332 @@+//! Calendars and events in the local library.+//!+//! Writes are upserts inside a transaction: a sync either lands whole or not at all, so an+//! interrupted refresh can never leave the interface showing half a calendar.++use crate::{Library, Result};+use rusqlite::params;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct Calendar {+ pub guid: String,+ pub title: String,+ pub colour: Option<String>,+ /// Apple's collection tag. Unchanged means nothing inside moved.+ pub ctag: Option<String>,+ pub sort_order: i64,+ pub enabled: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct Event {+ pub guid: String,+ pub calendar_guid: String,+ pub title: String,+ pub location: Option<String>,+ /// Unix seconds, UTC.+ pub starts_at: i64,+ pub ends_at: i64,+ pub all_day: bool,+ pub timezone: Option<String>,+ pub url: Option<String>,+ pub notes: Option<String>,+ pub etag: Option<String>,+}++fn now() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))+}++impl Library {+ /// Replace the set of calendars, dropping any Apple no longer reports.+ ///+ /// Removal cascades to their events, which is what should happen when a calendar is+ /// deleted on another device.+ pub fn put_calendars(&mut self, calendars: &[Calendar]) -> Result<()> {+ let tx = self.conn.transaction()?;+ {+ let mut stmt = tx.prepare(+ "INSERT INTO calendars (guid, title, colour, ctag, sort_order, enabled, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)+ ON CONFLICT(guid) DO UPDATE SET+ title = excluded.title,+ colour = excluded.colour,+ ctag = excluded.ctag,+ sort_order = excluded.sort_order,+ enabled = excluded.enabled,+ updated_at = excluded.updated_at",+ )?;+ let stamp = now();+ for c in calendars {+ stmt.execute(params![+ c.guid,+ c.title,+ c.colour,+ c.ctag,+ c.sort_order,+ i64::from(c.enabled),+ stamp+ ])?;+ }++ // Anything Apple stopped reporting was deleted elsewhere.+ let keep: Vec<&str> = calendars.iter().map(|c| c.guid.as_str()).collect();+ if keep.is_empty() {+ tx.execute("DELETE FROM calendars", [])?;+ } else {+ let placeholders = vec!["?"; keep.len()].join(",");+ tx.execute(+ &format!("DELETE FROM calendars WHERE guid NOT IN ({placeholders})"),+ rusqlite::params_from_iter(keep),+ )?;+ }+ }+ tx.commit()?;+ Ok(())+ }++ /// Upsert events. Existing rows for the same guid are updated in place.+ pub fn put_events(&mut self, events: &[Event]) -> Result<()> {+ let tx = self.conn.transaction()?;+ {+ let mut stmt = tx.prepare(+ "INSERT INTO events (guid, calendar_guid, title, location, starts_at, ends_at,+ all_day, timezone, url, notes, etag, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)+ ON CONFLICT(guid) DO UPDATE SET+ calendar_guid = excluded.calendar_guid,+ title = excluded.title,+ location = excluded.location,+ starts_at = excluded.starts_at,+ ends_at = excluded.ends_at,+ all_day = excluded.all_day,+ timezone = excluded.timezone,+ url = excluded.url,+ notes = excluded.notes,+ etag = excluded.etag,+ updated_at = excluded.updated_at",+ )?;+ let stamp = now();+ for e in events {+ stmt.execute(params![+ e.guid,+ e.calendar_guid,+ e.title,+ e.location,+ e.starts_at,+ e.ends_at,+ i64::from(e.all_day),+ e.timezone,+ e.url,+ e.notes,+ e.etag,+ stamp+ ])?;+ }+ }+ tx.commit()?;+ Ok(())+ }++ pub fn calendars(&self) -> Result<Vec<Calendar>> {+ let mut stmt = self.conn.prepare(+ "SELECT guid, title, colour, ctag, sort_order, enabled+ FROM calendars ORDER BY sort_order, title",+ )?;+ let rows = stmt.query_map([], |row| {+ Ok(Calendar {+ guid: row.get(0)?,+ title: row.get(1)?,+ colour: row.get(2)?,+ ctag: row.get(3)?,+ sort_order: row.get(4)?,+ enabled: row.get::<_, i64>(5)? != 0,+ })+ })?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }++ /// Events overlapping `[from, to)`, from enabled calendars only.+ ///+ /// Overlap rather than containment: a meeting that started before the window but is+ /// still running belongs in today's view.+ pub fn events_between(&self, from: i64, to: i64) -> Result<Vec<Event>> {+ let mut stmt = self.conn.prepare(+ "SELECT e.guid, e.calendar_guid, e.title, e.location, e.starts_at, e.ends_at,+ e.all_day, e.timezone, e.url, e.notes, e.etag+ FROM events e+ JOIN calendars c ON c.guid = e.calendar_guid+ WHERE c.enabled = 1 AND e.starts_at < ?2 AND e.ends_at > ?1+ ORDER BY e.starts_at, e.title",+ )?;+ let rows = stmt.query_map(params![from, to], |row| {+ Ok(Event {+ guid: row.get(0)?,+ calendar_guid: row.get(1)?,+ title: row.get(2)?,+ location: row.get(3)?,+ starts_at: row.get(4)?,+ ends_at: row.get(5)?,+ all_day: row.get::<_, i64>(6)? != 0,+ timezone: row.get(7)?,+ url: row.get(8)?,+ notes: row.get(9)?,+ etag: row.get(10)?,+ })+ })?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }++ /// Record that a service synced successfully.+ pub fn mark_synced(&self, service: &str, token: Option<&str>) -> Result<()> {+ self.conn.execute(+ "INSERT INTO sync_state (service, token, last_synced_at, last_error)+ VALUES (?1, ?2, ?3, NULL)+ ON CONFLICT(service) DO UPDATE SET+ token = excluded.token,+ last_synced_at = excluded.last_synced_at,+ last_error = NULL",+ params![service, token, now()],+ )?;+ Ok(())+ }++ /// When a service last synced, if it ever has.+ pub fn last_synced(&self, service: &str) -> Result<Option<i64>> {+ let found = self+ .conn+ .query_row(+ "SELECT last_synced_at FROM sync_state WHERE service = ?1",+ params![service],+ |row| row.get::<_, Option<i64>>(0),+ )+ .ok()+ .flatten();+ Ok(found)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn calendar(guid: &str, title: &str) -> Calendar {+ Calendar {+ guid: guid.into(),+ title: title.into(),+ colour: Some("#C8912A".into()),+ ctag: Some("ctag-1".into()),+ sort_order: 0,+ enabled: true,+ }+ }++ fn event(guid: &str, cal: &str, starts_at: i64, ends_at: i64) -> Event {+ Event {+ guid: guid.into(),+ calendar_guid: cal.into(),+ title: format!("Event {guid}"),+ location: None,+ starts_at,+ ends_at,+ all_day: false,+ timezone: Some("Asia/Kolkata".into()),+ url: None,+ notes: None,+ etag: None,+ }+ }++ fn seeded() -> Library {+ let mut lib = Library::in_memory().unwrap();+ lib.put_calendars(&[calendar("cal-1", "Work"), calendar("cal-2", "Home")])+ .unwrap();+ lib+ }++ #[test]+ fn calendars_round_trip_and_stay_ordered() {+ let lib = seeded();+ let found = lib.calendars().unwrap();+ assert_eq!(found.len(), 2);+ assert_eq!(+ found[0].title, "Home",+ "ordering is by sort order then title"+ );+ assert_eq!(found[0].colour.as_deref(), Some("#C8912A"));+ }++ /// A calendar deleted on another device must disappear here, with its events.+ #[test]+ fn calendars_apple_stops_reporting_are_removed() {+ let mut lib = seeded();+ lib.put_events(&[event("ev-1", "cal-2", 100, 200)]).unwrap();++ lib.put_calendars(&[calendar("cal-1", "Work")]).unwrap();++ assert_eq!(lib.calendars().unwrap().len(), 1);+ assert!(+ lib.events_between(0, 1_000).unwrap().is_empty(),+ "events of a removed calendar must go with it"+ );+ }++ /// Overlap, not containment: a meeting already under way belongs in the view.+ #[test]+ fn the_range_query_includes_events_already_running() {+ let mut lib = seeded();+ lib.put_events(&[+ event("before", "cal-1", 0, 50), // ends before the window+ event("straddling", "cal-1", 50, 150), // started earlier, still running+ event("inside", "cal-1", 110, 120),+ event("after", "cal-1", 300, 400), // starts after the window+ ])+ .unwrap();++ let found = lib.events_between(100, 200).unwrap();+ let guids: Vec<&str> = found.iter().map(|e| e.guid.as_str()).collect();+ assert_eq!(guids, vec!["straddling", "inside"]);+ }++ #[test]+ fn disabled_calendars_are_hidden_from_the_view() {+ let mut lib = seeded();+ lib.put_events(&[event("ev-1", "cal-1", 100, 200)]).unwrap();+ assert_eq!(lib.events_between(0, 1_000).unwrap().len(), 1);++ let mut hidden = calendar("cal-1", "Work");+ hidden.enabled = false;+ lib.put_calendars(&[hidden, calendar("cal-2", "Home")])+ .unwrap();++ assert!(lib.events_between(0, 1_000).unwrap().is_empty());+ }++ #[test]+ fn re_syncing_updates_events_rather_than_duplicating_them() {+ let mut lib = seeded();+ lib.put_events(&[event("ev-1", "cal-1", 100, 200)]).unwrap();++ let mut moved = event("ev-1", "cal-1", 500, 600);+ moved.title = "Moved".into();+ lib.put_events(&[moved]).unwrap();++ let all = lib.events_between(0, 10_000).unwrap();+ assert_eq!(all.len(), 1);+ assert_eq!(all[0].title, "Moved");+ assert_eq!(all[0].starts_at, 500);+ }++ #[test]+ fn sync_state_is_recorded() {+ let lib = seeded();+ assert!(lib.last_synced("calendar").unwrap().is_none());+ lib.mark_synced("calendar", Some("token-1")).unwrap();+ assert!(lib.last_synced("calendar").unwrap().is_some());+ }+}diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rsnew file mode 100644index 0000000..8a7cb4c--- /dev/null+++ b/crates/quince-core/src/lib.rs@@ -0,0 +1,162 @@+//! The local library: SQLite, and the only thing the UI ever reads.+//!+//! iCloud.com is slow because every scroll is a network round trip. Quince never renders+//! from the network — the sync engine reconciles into this database, and the interface reads+//! it. That is the whole reason the app can be instant and work offline.++pub mod calendar;+pub mod schema;++use rusqlite::Connection;+use std::path::Path;++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error("the local library couldn't be opened: {0}")]+ Sqlite(#[from] rusqlite::Error),+ #[error(transparent)]+ Io(#[from] std::io::Error),+}++pub type Result<T> = std::result::Result<T, Error>;++/// A handle to the local library.+pub struct Library {+ conn: Connection,+}++impl Library {+ /// Open (creating if needed) the library under `dir`, applying any pending migrations.+ pub fn open(dir: &Path) -> Result<Self> {+ std::fs::create_dir_all(dir)?;+ Self::from_connection(Connection::open(dir.join("library.db"))?)+ }++ /// An in-memory library. Tests, and nothing else.+ pub fn in_memory() -> Result<Self> {+ Self::from_connection(Connection::open_in_memory()?)+ }++ fn from_connection(conn: Connection) -> Result<Self> {+ // 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.+ conn.pragma_update(None, "journal_mode", "WAL")?;+ conn.pragma_update(None, "synchronous", "NORMAL")?;+ conn.pragma_update(None, "foreign_keys", "ON")?;+ let library = Self { conn };+ library.migrate()?;+ Ok(library)+ }++ /// Bring the schema up to date. Idempotent, and safe to call on every open.+ fn migrate(&self) -> Result<()> {+ let current: u32 = self+ .conn+ .query_row("PRAGMA user_version", [], |row| row.get(0))?;+ for (version, sql) in schema::MIGRATIONS.iter().enumerate() {+ let target = u32::try_from(version).unwrap_or(u32::MAX) + 1;+ if current < target {+ self.conn.execute_batch(sql)?;+ self.conn+ .pragma_update(None, "user_version", i64::from(target))?;+ }+ }+ Ok(())+ }++ pub fn schema_version(&self) -> Result<u32> {+ Ok(self+ .conn+ .query_row("PRAGMA user_version", [], |row| row.get(0))?)+ }++ pub fn conn(&self) -> &Connection {+ &self.conn+ }++ pub fn conn_mut(&mut self) -> &mut Connection {+ &mut self.conn+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_new_library_is_migrated_to_the_latest_schema() {+ let library = Library::in_memory().unwrap();+ assert_eq!(+ library.schema_version().unwrap() as usize,+ schema::MIGRATIONS.len()+ );+ }++ #[test]+ fn opening_twice_does_not_re_run_migrations() {+ let dir = tempfile::tempdir().unwrap();+ let first = Library::open(dir.path()).unwrap();+ let version = first.schema_version().unwrap();+ drop(first);++ // A second open must be a no-op, not an error and not a reset.+ let second = Library::open(dir.path()).unwrap();+ assert_eq!(second.schema_version().unwrap(), version);+ }++ #[test]+ fn deleting_a_calendar_takes_its_events_with_it() {+ let library = Library::in_memory().unwrap();+ let conn = library.conn();+ conn.execute(+ "INSERT INTO calendars (guid, title, updated_at) VALUES ('cal-1', 'Work', 0)",+ [],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO events (guid, calendar_guid, title, starts_at, ends_at, updated_at)+ VALUES ('ev-1', 'cal-1', 'Standup', 100, 200, 0)",+ [],+ )+ .unwrap();++ conn.execute("DELETE FROM calendars WHERE guid = 'cal-1'", [])+ .unwrap();++ let orphans: i64 = conn+ .query_row("SELECT count(*) FROM events", [], |row| row.get(0))+ .unwrap();+ assert_eq!(orphans, 0, "events must not outlive their calendar");+ }++ /// Re-syncing the same event must update it, not duplicate it.+ #[test]+ fn upserting_an_event_replaces_it() {+ let library = Library::in_memory().unwrap();+ let conn = library.conn();+ conn.execute(+ "INSERT INTO calendars (guid, title, updated_at) VALUES ('cal-1', 'Work', 0)",+ [],+ )+ .unwrap();++ for title in ["Standup", "Standup (moved)"] {+ conn.execute(+ "INSERT INTO events (guid, calendar_guid, title, starts_at, ends_at, updated_at)+ VALUES ('ev-1', 'cal-1', ?1, 100, 200, 0)+ ON CONFLICT(guid) DO UPDATE SET title = excluded.title",+ [title],+ )+ .unwrap();+ }++ let (count, title): (i64, String) = conn+ .query_row("SELECT count(*), max(title) FROM events", [], |row| {+ Ok((row.get(0)?, row.get(1)?))+ })+ .unwrap();+ assert_eq!(count, 1, "a re-sync must not duplicate rows");+ assert_eq!(title, "Standup (moved)");+ }+}diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rsnew file mode 100644index 0000000..dcb0007--- /dev/null+++ b/crates/quince-core/src/schema.rs@@ -0,0 +1,51 @@+//! Schema migrations, applied in order and tracked by SQLite's `user_version`.+//!+//! Append only. Editing a shipped migration would leave existing installs on a schema that+//! no longer matches what the code expects.++/// Every migration, oldest first. The index plus one is the `user_version` it produces.+pub const MIGRATIONS: &[&str] = &[+ // 1 — calendars and events.+ r#"+ CREATE TABLE calendars (+ guid TEXT PRIMARY KEY,+ title TEXT NOT NULL,+ colour TEXT,+ -- Apple's collection tag. Unchanged ctag means nothing in this calendar moved, so+ -- the whole collection can be skipped on the next sync.+ ctag TEXT,+ sort_order INTEGER NOT NULL DEFAULT 0,+ enabled INTEGER NOT NULL DEFAULT 1,+ updated_at INTEGER NOT NULL+ ) STRICT;++ CREATE TABLE events (+ guid TEXT PRIMARY KEY,+ calendar_guid TEXT NOT NULL REFERENCES calendars(guid) ON DELETE CASCADE,+ title TEXT NOT NULL,+ location TEXT,+ -- Unix seconds, UTC. The originating zone is kept separately so an all-day event or+ -- a meeting booked in another timezone still renders the way Apple shows it.+ starts_at INTEGER NOT NULL,+ ends_at INTEGER NOT NULL,+ all_day INTEGER NOT NULL DEFAULT 0,+ timezone TEXT,+ url TEXT,+ notes TEXT,+ etag TEXT,+ updated_at INTEGER NOT NULL+ ) STRICT;++ -- The calendar view is always "what is happening between these two instants".+ CREATE INDEX events_by_start ON events (starts_at);+ CREATE INDEX events_by_calendar ON events (calendar_guid, starts_at);++ -- Where each service got to, so a sync resumes instead of refetching everything.+ CREATE TABLE sync_state (+ service TEXT PRIMARY KEY,+ token TEXT,+ last_synced_at INTEGER,+ last_error TEXT+ ) STRICT;+ "#,+];