Skip to content

Commit cf75ad2

Browse files
fix: prune stale assets (#22530)
Co-authored-by: shenlong-tanwen <[email protected]> Co-authored-by: Alex <[email protected]>
1 parent 2286444 commit cf75ad2

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

mobile/lib/domain/services/sync_stream.service.dart

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,9 +130,9 @@ class SyncStreamService {
130130
// to acknowledge that the client has processed all the backfill events
131131
case SyncEntityType.syncAckV1:
132132
return;
133-
// No-op. SyncCompleteV1 is used to signal the completion of the sync process
133+
// SyncCompleteV1 is used to signal the completion of the sync process. Cleanup stale assets and signal completion
134134
case SyncEntityType.syncCompleteV1:
135-
return;
135+
return _syncStreamRepository.pruneAssets();
136136
// Request to reset the client state. Clear everything related to remote entities
137137
case SyncEntityType.syncResetV1:
138138
return _syncStreamRepository.reset();

mobile/lib/infrastructure/repositories/sync_stream.repository.dart

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,40 @@ class SyncStreamRepository extends DriftDatabaseRepository {
592592
rethrow;
593593
}
594594
}
595+
596+
Future<void> pruneAssets() async {
597+
try {
598+
await _db.transaction(() async {
599+
final authQuery = _db.authUserEntity.selectOnly()
600+
..addColumns([_db.authUserEntity.id])
601+
..limit(1);
602+
final currentUserId = await authQuery.map((row) => row.read(_db.authUserEntity.id)).getSingleOrNull();
603+
if (currentUserId == null) {
604+
_logger.warning('No authenticated user found during pruneAssets. Skipping asset pruning.');
605+
return;
606+
}
607+
608+
final partnerQuery = _db.partnerEntity.selectOnly()
609+
..addColumns([_db.partnerEntity.sharedById])
610+
..where(_db.partnerEntity.sharedWithId.equals(currentUserId));
611+
final partnerIds = await partnerQuery.map((row) => row.read(_db.partnerEntity.sharedById)).get();
612+
613+
final validUsers = {currentUserId, ...partnerIds.nonNulls};
614+
615+
// Asset is not owned by the current user or any of their partners and is not part of any (shared) album
616+
// Likely a stale asset that was previously shared but has been removed
617+
await _db.remoteAssetEntity.deleteWhere((asset) {
618+
return asset.ownerId.isNotIn(validUsers) &
619+
asset.id.isNotInQuery(
620+
_db.remoteAlbumAssetEntity.selectOnly()..addColumns([_db.remoteAlbumAssetEntity.assetId]),
621+
);
622+
});
623+
});
624+
} catch (error, stack) {
625+
_logger.severe('Error: pruneAssets', error, stack);
626+
// We do not rethrow here as this is a client-only cleanup and should not affect the sync process
627+
}
628+
}
595629
}
596630

597631
extension on AssetTypeEnum {

0 commit comments

Comments
 (0)