π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
fix(rust): Fix incremental sync to properly track per-collection timestamps
Manav Rathi7eda60a49374
diff --git a/rust/src/storage/schema.rs b/rust/src/storage/schema.rsindex 06f16cd2de..2cea42550c 100644--- a/rust/src/storage/schema.rs+++ b/rust/src/storage/schema.rs@@ -113,6 +113,19 @@ pub fn create_tables(conn: &Connection) -> Result<()> {[],)?;+ // Collection sync state table - stores per-collection sync timestamps+ conn.execute(+ "CREATE TABLE IF NOT EXISTS collection_sync_state (+ user_id INTEGER NOT NULL,+ collection_id INTEGER NOT NULL,+ last_sync_time INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ PRIMARY KEY (user_id, collection_id),+ FOREIGN KEY (collection_id) REFERENCES collections(collection_id) ON DELETE CASCADE+ )",+ [],+ )?;+// Create indices for better performanceconn.execute("CREATE INDEX IF NOT EXISTS idx_files_collection@@ -144,5 +157,11 @@ pub fn create_tables(conn: &Connection) -> Result<()> {[],)?;+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_collection_sync_state+ ON collection_sync_state(user_id, collection_id)",+ [],+ )?;+Ok(())}diff --git a/rust/src/storage/sync.rs b/rust/src/storage/sync.rsindex 9c601b0429..a302723137 100644--- a/rust/src/storage/sync.rs+++ b/rust/src/storage/sync.rs@@ -151,14 +151,23 @@ impl<'a> SyncStore<'a> {/// Update sync statepub fn update_sync_state(&self, user_id: i64, sync_type: &str, timestamp: i64) -> Result<()> {- // For per-collection sync, store as generic key-value+ // For per-collection sync, store in collection_sync_state tableif sync_type.starts_with("collection_") {- // Use a more generic approach for per-collection sync- // Note: We're assuming photos app for now - might need app parameter in future+ // Extract collection_id from sync_type (format: "collection_{id}_files")+ let collection_id = sync_type+ .strip_prefix("collection_")+ .and_then(|s| s.strip_suffix("_files"))+ .and_then(|s| s.parse::<i64>().ok())+ .ok_or_else(|| {+ crate::Error::InvalidInput(format!("Invalid sync type: {}", sync_type))+ })?;++ let now = chrono::Utc::now().timestamp_micros();self.conn.execute(- "INSERT OR REPLACE INTO sync_state (user_id, app, last_file_sync) VALUES (?1, 'photos', ?2)- ON CONFLICT(user_id, app) DO UPDATE SET last_file_sync = MAX(last_file_sync, ?2)",- params![user_id, timestamp],+ "INSERT OR REPLACE INTO collection_sync_state+ (user_id, collection_id, last_sync_time, updated_at)+ VALUES (?1, ?2, ?3, ?4)",+ params![user_id, collection_id, timestamp, now],)?;return Ok(());}@@ -182,9 +191,28 @@ impl<'a> SyncStore<'a> {/// Get last sync timestamppub fn get_last_sync(&self, user_id: i64, sync_type: &str) -> Result<Option<i64>> {- // For per-collection sync, just return 0 for now+ // For per-collection sync, retrieve from collection_sync_state tableif sync_type.starts_with("collection_") {- return Ok(Some(0));+ // Extract collection_id from sync_type (format: "collection_{id}_files")+ let collection_id = sync_type+ .strip_prefix("collection_")+ .and_then(|s| s.strip_suffix("_files"))+ .and_then(|s| s.parse::<i64>().ok())+ .ok_or_else(|| {+ crate::Error::InvalidInput(format!("Invalid sync type: {}", sync_type))+ })?;++ let timestamp = self+ .conn+ .query_row(+ "SELECT last_sync_time FROM collection_sync_state+ WHERE user_id = ?1 AND collection_id = ?2",+ params![user_id, collection_id],+ |row| row.get::<_, i64>(0),+ )+ .optional()?;++ return Ok(timestamp);}let column = match sync_type {@@ -219,10 +247,17 @@ impl<'a> SyncStore<'a> {/// Clear sync state for an account (for full sync)pub fn clear_sync_state(&self, user_id: i64) -> Result<()> {+ // Clear both sync_state and collection_sync_stateself.conn.execute("DELETE FROM sync_state WHERE user_id = ?1 AND app = 'photos'",params![user_id],)?;++ self.conn.execute(+ "DELETE FROM collection_sync_state WHERE user_id = ?1",+ params![user_id],+ )?;+Ok(())}diff --git a/rust/src/sync/engine.rs b/rust/src/sync/engine.rsindex 69a8920a38..ec35a5fc92 100644--- a/rust/src/sync/engine.rs+++ b/rust/src/sync/engine.rs@@ -92,13 +92,19 @@ impl SyncEngine {// Count as new or updated based on updation timeif collection.updation_time > last_sync {- // We don't have creation_time in API response, so count as updated- if collection.updation_time > last_sync {+ if last_sync == 0 {+ // First sync - count as newresult.new += 1;} else {+ // Incremental sync - count as updatedresult.updated += 1;}}++ // Track deleted collections+ if collection.is_deleted {+ result.deleted += 1;+ }}// Update sync timestamp@@ -137,17 +143,41 @@ impl SyncEngine {);// Get last sync time for this collection's files- let mut last_sync = sync_store+ let initial_sync = sync_store.get_last_sync(self.account.user_id,&format!("collection_{}_files", collection.id),)?.unwrap_or(0);+ let mut last_sync = initial_sync;+ let is_first_sync = initial_sync == 0;++ // Log sync status+ if is_first_sync {+ log::info!(+ "Initial sync for collection: {} ({})",+ collection.name,+ collection.id+ );+ } else {+ let last_sync_time = chrono::DateTime::from_timestamp_micros(initial_sync)+ .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())+ .unwrap_or_else(|| "unknown".to_string());+ log::info!(+ "Incremental sync for collection: {} ({}) since {}",+ collection.name,+ collection.id,+ last_sync_time+ );+ }+let mut has_more = true;+ let mut batch_count = 0;while has_more {log::debug!(- "Fetching files for collection {}, since_time: {}",+ "Fetching batch {} for collection {}, since_time: {}",+ batch_count + 1,collection.id,last_sync);@@ -156,8 +186,10 @@ impl SyncEngine {.get_collection_files(account_id, collection.id, last_sync).await?;has_more = more;+ batch_count += 1;if files.is_empty() {+ log::debug!("No more files to sync for collection {}", collection.id);break;}@@ -206,13 +238,26 @@ impl SyncEngine {}),};+ // Skip deleted files on first sync+ if is_first_sync && file.is_deleted {+ log::trace!("Skipping deleted file {} on initial sync", file.id);+ continue;+ }+// Upsert file (insert or update)sync_store.upsert_file(&remote_file)?;- // Count as new or updated- if file.updation_time > last_sync {- // We don't have creation_time in API response, count as updated- result.updated += 1;+ // Count as new, updated or deleted+ if file.is_deleted {+ result.deleted += 1;+ } else if file.updation_time > last_sync {+ if last_sync == 0 {+ // First sync - count as new+ result.new += 1;+ } else {+ // Incremental sync - count as updated+ result.updated += 1;+ }}// Track the latest updation time for next sync@@ -231,9 +276,10 @@ impl SyncEngine {}log::info!(- "Files synced: {} new, {} updated",+ "Files synced: {} new, {} updated, {} deleted",result.new,- result.updated+ result.updated,+ result.deleted);Ok(result)}