Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mob][contacts] fix profile picture and sync paging

Neeraj Gupta0158c59f8381
diff --git a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
index 1bb5c07bde..4e8f2a0b1b 100644
--- a/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
+++ b/mobile/packages/contacts/lib/src/rust/contacts_rust_api.dart
@@ -258,12 +258,7 @@ class _FrbContactsRustContext implements ContactsRustContext {
@override
Future<Uint8List> getProfilePicture(String contactId) async {
- final contact = await getContact(contactId);
- final attachmentId = contact.profilePictureAttachmentId;
- if (attachmentId == null) {
- throw StateError('Contact $contactId does not have a profile picture');
- }
- return getAttachment(ContactAttachmentType.profilePicture, attachmentId);
+ return _inner.getProfilePicture(contactId: contactId);
}
@override
diff --git a/mobile/packages/contacts/lib/src/service/contacts_service.dart b/mobile/packages/contacts/lib/src/service/contacts_service.dart
index 6dc2cd11e2..b15decfda8 100644
--- a/mobile/packages/contacts/lib/src/service/contacts_service.dart
+++ b/mobile/packages/contacts/lib/src/service/contacts_service.dart
@@ -11,6 +11,7 @@ import 'package:shared_preferences/shared_preferences.dart';
class ContactsService {
static const _syncLimit = 5000;
+ static const _maxSyncLimit = 50000;
ContactsService({
required SharedPreferences preferences,
@@ -69,18 +70,40 @@ class ContactsService {
Future<List<ContactRecord>> sync() async {
final ctx = _requireCtx();
var sinceTime = await _database.getLastSyncedUpdatedAt();
+ var limit = _syncLimit;
final synced = <ContactRecord>[];
+ final syncedIds = <String>{};
+ var previousSinceTime = -1;
+ List<String>? previousPageIds;
while (true) {
- final diff = await ctx.getDiff(sinceTime, _syncLimit);
+ final diff = await ctx.getDiff(sinceTime, limit);
if (diff.isEmpty) {
break;
}
+ final pageIds = diff.map((contact) => contact.id).toList(growable: false);
+ if (sinceTime == previousSinceTime &&
+ previousPageIds != null &&
+ _sameIds(previousPageIds, pageIds)) {
+ if (limit >= _maxSyncLimit) {
+ throw StateError(
+ 'Contacts sync pagination stalled at updatedAt ${diff.last.updatedAt}',
+ );
+ }
+ limit = min(limit * 2, _maxSyncLimit);
+ continue;
+ }
await _database.upsertContacts(diff);
final maxUpdatedAt = diff.map((e) => e.updatedAt).reduce(max);
- await _database.setLastSyncedUpdatedAt(maxUpdatedAt);
- sinceTime = maxUpdatedAt;
- synced.addAll(diff);
- if (diff.length < _syncLimit) {
+ previousSinceTime = sinceTime;
+ previousPageIds = pageIds;
+ sinceTime = _nextSyncCursor(diff, maxUpdatedAt, limit);
+ await _database.setLastSyncedUpdatedAt(sinceTime);
+ for (final contact in diff) {
+ if (syncedIds.add(contact.id)) {
+ synced.add(contact);
+ }
+ }
+ if (diff.length < limit) {
break;
}
}
@@ -194,8 +217,12 @@ class ContactsService {
if (cached != null) {
return cached;
}
- final bytes =
- await _requireCtx().getAttachment(attachmentType, attachmentId);
+ final ctx = _requireCtx();
+ final bytes = switch (attachmentType) {
+ ContactAttachmentType.profilePicture => await ctx.getProfilePicture(
+ contactId,
+ ),
+ };
await _database.upsertCachedAttachment(attachmentId, bytes);
return bytes;
}
@@ -221,6 +248,27 @@ class ContactsService {
await _database.resetState();
}
+ int _nextSyncCursor(List<ContactRecord> diff, int maxUpdatedAt, int limit) {
+ if (diff.length < limit || maxUpdatedAt <= 0) {
+ return maxUpdatedAt;
+ }
+ // Overlap the boundary timestamp by one tick so the next page can pick up
+ // additional rows that share the current page's max updatedAt.
+ return maxUpdatedAt - 1;
+ }
+
+ bool _sameIds(List<String> a, List<String> b) {
+ if (a.length != b.length) {
+ return false;
+ }
+ for (var i = 0; i < a.length; i++) {
+ if (a[i] != b[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
ContactsRustContext _requireCtx() {
final ctx = _ctx;
if (ctx == null) {
diff --git a/mobile/packages/contacts/test/contacts_service_test.dart b/mobile/packages/contacts/test/contacts_service_test.dart
index 27c57525a6..bae1aa84d9 100644
--- a/mobile/packages/contacts/test/contacts_service_test.dart
+++ b/mobile/packages/contacts/test/contacts_service_test.dart
@@ -171,7 +171,8 @@ void main() {
],
const [],
];
- rustApi.ctx.attachments['att_1'] = Uint8List.fromList([7, 8, 9]);
+ rustApi.ctx.attachments['att_1'] = Uint8List.fromList([99, 88, 77]);
+ rustApi.ctx.profilePictures['ct_1'] = Uint8List.fromList([7, 8, 9]);
await service.open(
ContactsSession(
@@ -187,12 +188,13 @@ void main() {
await service.getProfilePicture('ct_1'),
Uint8List.fromList([7, 8, 9]),
);
- expect(rustApi.ctx.getAttachmentCalls, 1);
+ expect(rustApi.ctx.getAttachmentCalls, 0);
+ expect(rustApi.ctx.getProfilePictureCalls, 1);
expect(
await service.getProfilePicture('ct_1'),
Uint8List.fromList([7, 8, 9]),
);
- expect(rustApi.ctx.getAttachmentCalls, 1);
+ expect(rustApi.ctx.getProfilePictureCalls, 1);
});
test('replacing profile picture removes stale cached bytes', () async {
@@ -280,6 +282,68 @@ void main() {
expect(await database.getCachedAttachment('att_drop'), isNull);
},
);
+
+ test('sync increases overlap page size to avoid skipping equal timestamps',
+ () async {
+ final firstPage = <ContactRecord>[
+ for (var i = 0; i < 5000; i++)
+ ContactRecord(
+ id: 'ct_$i',
+ contactUserId: i + 2,
+ email: '[email protected]',
+ data: ContactData(contactUserId: i + 2, name: 'User $i'),
+ profilePictureAttachmentId: null,
+ isDeleted: false,
+ createdAt: 10,
+ updatedAt: 20,
+ ),
+ ];
+ const overflow = ContactRecord(
+ id: 'ct_overflow',
+ contactUserId: 6002,
+ email: '[email protected]',
+ data: ContactData(contactUserId: 6002, name: 'Overflow'),
+ profilePictureAttachmentId: null,
+ isDeleted: false,
+ createdAt: 10,
+ updatedAt: 20,
+ );
+ rustApi.ctx.diffHandler = (sinceTime, limit) async {
+ if (sinceTime == 0) {
+ return firstPage;
+ }
+ if (sinceTime == 19 && limit == 5000) {
+ return firstPage;
+ }
+ if (sinceTime == 19 && limit == 10000) {
+ return [...firstPage, overflow];
+ }
+ return const [];
+ };
+
+ await service.open(
+ ContactsSession(
+ baseUrl: 'http://localhost:8080',
+ authToken: 'token',
+ userId: 1,
+ accountKey: Uint8List.fromList([1, 2, 3]),
+ ),
+ );
+
+ final synced = await service.sync();
+
+ expect(
+ synced.any((contact) => contact.id == 'ct_overflow'),
+ isTrue,
+ );
+ expect(rustApi.ctx.diffSinceTimes.first, 0);
+ expect(rustApi.ctx.diffSinceTimes.skip(1), everyElement(19));
+ expect(rustApi.ctx.diffLimits.first, 5000);
+ expect(rustApi.ctx.diffLimits.where((limit) => limit == 5000), isNotEmpty);
+ expect(rustApi.ctx.diffLimits, contains(10000));
+ expect((await service.getContact('ct_overflow'))?.data?.name, 'Overflow');
+ expect(synced.where((contact) => contact.id == 'ct_0'), hasLength(1));
+ });
}
class FakeContactsRustApi implements ContactsRustApi {
@@ -307,8 +371,13 @@ class FakeContactsRustContext implements ContactsRustContext {
int userIdValue = 0;
final Map<String, ContactRecord> records = {};
final Map<String, Uint8List> attachments = {};
+ final Map<String, Uint8List> profilePictures = {};
List<List<ContactRecord>> diffPages = [];
+ Future<List<ContactRecord>> Function(int sinceTime, int limit)? diffHandler;
+ final List<int> diffSinceTimes = [];
+ final List<int> diffLimits = [];
int getAttachmentCalls = 0;
+ int getProfilePictureCalls = 0;
String nextAttachmentId = 'att_profile';
@override
@@ -385,6 +454,16 @@ class FakeContactsRustContext implements ContactsRustContext {
@override
Future<List<ContactRecord>> getDiff(int sinceTime, int limit) async {
+ diffSinceTimes.add(sinceTime);
+ diffLimits.add(limit);
+ final handler = diffHandler;
+ if (handler != null) {
+ final page = await handler(sinceTime, limit);
+ for (final record in page) {
+ records[record.id] = record;
+ }
+ return page;
+ }
if (diffPages.isEmpty) {
return const [];
}
@@ -407,8 +486,13 @@ class FakeContactsRustContext implements ContactsRustContext {
@override
Future<Uint8List> getProfilePicture(String contactId) {
+ getProfilePictureCalls += 1;
+ final picture = profilePictures[contactId];
+ if (picture != null) {
+ return Future.value(picture);
+ }
final attachmentId = records[contactId]!.profilePictureAttachmentId!;
- return getAttachment(ContactAttachmentType.profilePicture, attachmentId);
+ return Future.value(attachments[attachmentId]!);
}
@override
@@ -430,6 +514,7 @@ class FakeContactsRustContext implements ContactsRustContext {
);
records[contactId] = updated;
attachments[nextAttachmentId] = attachmentBytes;
+ profilePictures[contactId] = attachmentBytes;
return updated;
}