fix(mobile): run user sync operation with lock (#4984)

This commit is contained in:
Fynn Petersen-Frey 2023-11-12 17:35:08 +01:00 committed by GitHub
parent 388144823a
commit 069a32dcdb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -34,36 +34,8 @@ class SyncService {
/// Syncs users from the server to the local database /// Syncs users from the server to the local database
/// Returns `true`if there were any changes /// Returns `true`if there were any changes
Future<bool> syncUsersFromServer(List<User> users) async { Future<bool> syncUsersFromServer(List<User> users) =>
users.sortBy((u) => u.id); _lock.run(() => _syncUsersFromServer(users));
final dbUsers = await _db.users.where().sortById().findAll();
assert(dbUsers.isSortedBy((u) => u.id), "dbUsers not sorted!");
final List<int> toDelete = [];
final List<User> toUpsert = [];
final changes = diffSortedListsSync(
users,
dbUsers,
compare: (User a, User b) => a.id.compareTo(b.id),
both: (User a, User b) {
if (!a.updatedAt.isAtSameMomentAs(b.updatedAt) ||
a.isPartnerSharedBy != b.isPartnerSharedBy ||
a.isPartnerSharedWith != b.isPartnerSharedWith) {
toUpsert.add(a);
return true;
}
return false;
},
onlyFirst: (User a) => toUpsert.add(a),
onlySecond: (User b) => toDelete.add(b.isarId),
);
if (changes) {
await _db.writeTxn(() async {
await _db.users.deleteAll(toDelete);
await _db.users.putAll(toUpsert);
});
}
return changes;
}
/// Syncs remote assets owned by the logged-in user to the DB /// Syncs remote assets owned by the logged-in user to the DB
/// Returns `true` if there were any changes /// Returns `true` if there were any changes
@ -120,6 +92,39 @@ class SyncService {
// private methods: // private methods:
/// Syncs users from the server to the local database
/// Returns `true`if there were any changes
Future<bool> _syncUsersFromServer(List<User> users) async {
users.sortBy((u) => u.id);
final dbUsers = await _db.users.where().sortById().findAll();
assert(dbUsers.isSortedBy((u) => u.id), "dbUsers not sorted!");
final List<int> toDelete = [];
final List<User> toUpsert = [];
final changes = diffSortedListsSync(
users,
dbUsers,
compare: (User a, User b) => a.id.compareTo(b.id),
both: (User a, User b) {
if (!a.updatedAt.isAtSameMomentAs(b.updatedAt) ||
a.isPartnerSharedBy != b.isPartnerSharedBy ||
a.isPartnerSharedWith != b.isPartnerSharedWith) {
toUpsert.add(a);
return true;
}
return false;
},
onlyFirst: (User a) => toUpsert.add(a),
onlySecond: (User b) => toDelete.add(b.isarId),
);
if (changes) {
await _db.writeTxn(() async {
await _db.users.deleteAll(toDelete);
await _db.users.putAll(toUpsert);
});
}
return changes;
}
/// Syncs a new asset to the db. Returns `true` if successful /// Syncs a new asset to the db. Returns `true` if successful
Future<bool> _syncNewAssetToDb(Asset a) async { Future<bool> _syncNewAssetToDb(Asset a) async {
final Asset? inDb = final Asset? inDb =