-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(mobile): new sync #16556
Draft
alextran1502
wants to merge
3
commits into
main
Choose a base branch
from
new-mobile-sync
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+399
−0
Draft
feat(mobile): new sync #16556
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import 'package:immich_mobile/domain/models/sync/sync_event.model.dart'; | ||
|
||
abstract interface class ISyncApiRepository { | ||
Future<void> ack(String data); | ||
|
||
Stream<List<SyncEvent>> watchUserSyncEvent(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
// ignore_for_file: public_member_api_docs, sort_constructors_first | ||
import 'dart:convert'; | ||
|
||
class SyncEvent { | ||
// dynamic | ||
final dynamic data; | ||
|
||
final String ack; | ||
|
||
SyncEvent({ | ||
required this.data, | ||
required this.ack, | ||
}); | ||
|
||
SyncEvent copyWith({ | ||
dynamic data, | ||
String? ack, | ||
}) { | ||
return SyncEvent( | ||
data: data ?? this.data, | ||
ack: ack ?? this.ack, | ||
); | ||
} | ||
|
||
Map<String, dynamic> toMap() { | ||
return <String, dynamic>{ | ||
'data': data, | ||
'ack': ack, | ||
}; | ||
} | ||
|
||
factory SyncEvent.fromMap(Map<String, dynamic> map) { | ||
return SyncEvent( | ||
data: map['data'] as dynamic, | ||
ack: map['ack'] as String, | ||
); | ||
} | ||
|
||
String toJson() => json.encode(toMap()); | ||
|
||
factory SyncEvent.fromJson(String source) => | ||
SyncEvent.fromMap(json.decode(source) as Map<String, dynamic>); | ||
|
||
@override | ||
String toString() => 'SyncEvent(data: $data, ack: $ack)'; | ||
|
||
@override | ||
bool operator ==(covariant SyncEvent other) { | ||
if (identical(this, other)) return true; | ||
|
||
return other.data == data && other.ack == ack; | ||
} | ||
|
||
@override | ||
int get hashCode => data.hashCode ^ ack.hashCode; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
// ignore_for_file: public_member_api_docs, sort_constructors_first | ||
import 'dart:convert'; | ||
|
||
class SyncUserDeleteResponse { | ||
final String userId; | ||
SyncUserDeleteResponse({ | ||
required this.userId, | ||
}); | ||
|
||
SyncUserDeleteResponse copyWith({ | ||
String? userId, | ||
}) { | ||
return SyncUserDeleteResponse( | ||
userId: userId ?? this.userId, | ||
); | ||
} | ||
|
||
Map<String, dynamic> toMap() { | ||
return <String, dynamic>{ | ||
'userId': userId, | ||
}; | ||
} | ||
|
||
factory SyncUserDeleteResponse.fromMap(Map<String, dynamic> map) { | ||
return SyncUserDeleteResponse( | ||
userId: map['userId'] as String, | ||
); | ||
} | ||
|
||
String toJson() => json.encode(toMap()); | ||
|
||
factory SyncUserDeleteResponse.fromJson(String source) => | ||
SyncUserDeleteResponse.fromMap( | ||
json.decode(source) as Map<String, dynamic>, | ||
); | ||
|
||
@override | ||
String toString() => 'SyncUserDeleteResponse(userId: $userId)'; | ||
|
||
@override | ||
bool operator ==(covariant SyncUserDeleteResponse other) { | ||
if (identical(this, other)) return true; | ||
|
||
return other.userId == userId; | ||
} | ||
|
||
@override | ||
int get hashCode => userId.hashCode; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
// ignore_for_file: public_member_api_docs, sort_constructors_first | ||
import 'dart:convert'; | ||
|
||
class SyncUserUpdateResponse { | ||
final String id; | ||
|
||
final String name; | ||
|
||
final String email; | ||
|
||
final DateTime? deletedAt; | ||
|
||
SyncUserUpdateResponse({ | ||
required this.id, | ||
required this.name, | ||
required this.email, | ||
required this.deletedAt, | ||
}); | ||
|
||
SyncUserUpdateResponse copyWith({ | ||
String? id, | ||
String? name, | ||
String? email, | ||
DateTime? deletedAt, | ||
}) { | ||
return SyncUserUpdateResponse( | ||
id: id ?? this.id, | ||
name: name ?? this.name, | ||
email: email ?? this.email, | ||
deletedAt: deletedAt ?? this.deletedAt, | ||
); | ||
} | ||
|
||
Map<String, dynamic> toMap() { | ||
return <String, dynamic>{ | ||
'id': id, | ||
'name': name, | ||
'email': email, | ||
'deletedAt': deletedAt, | ||
}; | ||
} | ||
|
||
factory SyncUserUpdateResponse.fromMap(Map<String, dynamic> map) { | ||
return SyncUserUpdateResponse( | ||
id: map['id'] as String, | ||
name: map['name'] as String, | ||
email: map['email'] as String, | ||
deletedAt: | ||
map['deletedAt'] != null ? DateTime.parse(map['deletedAt']) : null, | ||
); | ||
} | ||
|
||
String toJson() => json.encode(toMap()); | ||
|
||
factory SyncUserUpdateResponse.fromJson(String source) => | ||
SyncUserUpdateResponse.fromMap( | ||
json.decode(source) as Map<String, dynamic>, | ||
); | ||
|
||
@override | ||
String toString() { | ||
return 'SyncUserResponse(id: $id, name: $name, email: $email, deletedAt: $deletedAt)'; | ||
} | ||
|
||
@override | ||
bool operator ==(covariant SyncUserUpdateResponse other) { | ||
if (identical(this, other)) return true; | ||
|
||
return other.id == id && | ||
other.name == name && | ||
other.email == email && | ||
other.deletedAt == deletedAt; | ||
} | ||
|
||
@override | ||
int get hashCode { | ||
return id.hashCode ^ name.hashCode ^ email.hashCode ^ deletedAt.hashCode; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import 'package:flutter/foundation.dart'; | ||
import 'package:hooks_riverpod/hooks_riverpod.dart'; | ||
import 'package:immich_mobile/domain/interfaces/sync_api.interface.dart'; | ||
import 'package:immich_mobile/interfaces/user.interface.dart'; | ||
import 'package:immich_mobile/domain/models/sync/sync_user_delete.model.dart'; | ||
import 'package:immich_mobile/domain/models/sync/sync_user_update.model.dart'; | ||
import 'package:immich_mobile/infrastructure/repositories/sync_api.repository.dart'; | ||
import 'package:immich_mobile/repositories/user.repository.dart'; | ||
|
||
final syncStreamServiceProvider = Provider( | ||
(ref) => SyncStreamService( | ||
ref.watch(syncApiRepositoryProvider), | ||
ref.watch(userRepositoryProvider), | ||
), | ||
); | ||
|
||
class SyncStreamService { | ||
final ISyncApiRepository _syncApiRepository; | ||
final IUserRepository _userRepository; | ||
|
||
SyncStreamService(this._syncApiRepository, this._userRepository); | ||
|
||
void syncUsers() { | ||
_syncApiRepository.watchUserSyncEvent().listen((events) async { | ||
for (final event in events) { | ||
if (event.data is SyncUserUpdateResponse) { | ||
final data = event.data as SyncUserUpdateResponse; | ||
final user = await _userRepository.get(data.id); | ||
|
||
if (user == null) { | ||
continue; | ||
} | ||
|
||
user.name = data.name; | ||
user.email = data.email; | ||
user.updatedAt = DateTime.now(); | ||
|
||
await _userRepository.update(user); | ||
await _syncApiRepository.ack(event.ack); | ||
} | ||
|
||
if (event.data is SyncUserDeleteResponse) { | ||
final data = event.data as SyncUserDeleteResponse; | ||
|
||
debugPrint("User delete: $data"); | ||
} | ||
} | ||
}); | ||
} | ||
} |
151 changes: 151 additions & 0 deletions
151
mobile/lib/infrastructure/repositories/sync_api.repository.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,151 @@ | ||
import 'dart:convert'; | ||
|
||
import 'package:flutter/foundation.dart'; | ||
import 'package:hooks_riverpod/hooks_riverpod.dart'; | ||
import 'package:http/http.dart'; | ||
import 'package:immich_mobile/domain/models/store.model.dart'; | ||
import 'package:immich_mobile/entities/store.entity.dart'; | ||
import 'package:immich_mobile/domain/interfaces/sync_api.interface.dart'; | ||
import 'package:immich_mobile/domain/models/sync/sync_event.model.dart'; | ||
import 'package:immich_mobile/domain/models/sync/sync_user_delete.model.dart'; | ||
import 'package:immich_mobile/domain/models/sync/sync_user_update.model.dart'; | ||
import 'package:immich_mobile/providers/api.provider.dart'; | ||
import 'package:immich_mobile/providers/db.provider.dart'; | ||
import 'package:immich_mobile/repositories/database.repository.dart'; | ||
import 'package:http/http.dart' as http; | ||
import 'package:openapi/api.dart'; | ||
|
||
final syncApiRepositoryProvider = Provider( | ||
(ref) => SyncApiRepository( | ||
ref.watch(dbProvider), | ||
ref.watch(apiServiceProvider).syncApi, | ||
), | ||
); | ||
|
||
class SyncApiRepository extends DatabaseRepository | ||
implements ISyncApiRepository { | ||
final SyncApi _syncApi; | ||
SyncApiRepository(super.db, this._syncApi); | ||
|
||
@override | ||
Stream<List<SyncEvent>> watchUserSyncEvent() { | ||
return _streamSync( | ||
types: [SyncRequestType.usersV1], | ||
methodName: 'watchUserSyncEvent', | ||
); | ||
} | ||
|
||
Stream<List<SyncEvent>> _streamSync({ | ||
required List<SyncRequestType> types, | ||
required String methodName, | ||
int batchSize = 5000, | ||
}) async* { | ||
final timer = Stopwatch()..start(); | ||
String previousChunk = ''; | ||
List<String> lines = []; | ||
|
||
final client = http.Client(); | ||
final request = _getRequest(types); | ||
if (request == null) { | ||
return; | ||
} | ||
|
||
try { | ||
final response = await client.send(request); | ||
|
||
await for (var chunk in response.stream.transform(utf8.decoder)) { | ||
previousChunk += chunk; | ||
final parts = previousChunk.split('\n'); | ||
previousChunk = parts.removeLast(); | ||
lines.addAll(parts); | ||
|
||
if (lines.length < batchSize) { | ||
continue; | ||
} | ||
|
||
final events = await compute(_parseSyncResponse, lines); | ||
yield events; | ||
lines.clear(); | ||
} | ||
} finally { | ||
if (lines.isNotEmpty) { | ||
final events = await compute(_parseSyncResponse, lines); | ||
yield events; | ||
} | ||
client.close(); | ||
|
||
timer.stop(); | ||
debugPrint( | ||
"[SyncApiRepository.$methodName] Elapsed time: ${timer.elapsedMilliseconds}ms", | ||
); | ||
} | ||
} | ||
|
||
Request? _getRequest(List<SyncRequestType> types) { | ||
final serverUrl = Store.tryGet(StoreKey.serverUrl); | ||
final accessToken = Store.tryGet(StoreKey.accessToken); | ||
if (serverUrl == null || accessToken == null) { | ||
return null; | ||
} | ||
|
||
final url = Uri.parse('$serverUrl/sync/stream'); | ||
final request = http.Request('POST', url); | ||
final headers = { | ||
'Content-Type': 'application/json', | ||
'x-immich-user-token': accessToken, | ||
}; | ||
|
||
request.headers.addAll(headers); | ||
request.body = json.encode({ | ||
"types": [...types], | ||
}); | ||
|
||
return request; | ||
} | ||
|
||
@override | ||
Future<void> ack(String data) { | ||
return _syncApi.sendSyncAck(SyncAckSetDto(acks: [data])); | ||
} | ||
} | ||
|
||
// Need to be outside of the class to be able to use compute | ||
List<SyncEvent> _parseSyncResponse( | ||
List<String> lines, | ||
) { | ||
final List<SyncEvent> data = []; | ||
|
||
for (var line in lines) { | ||
try { | ||
final jsonData = jsonDecode(line); | ||
final type = SyncEntityType.fromJson(jsonData['type'])!; | ||
final dataJson = jsonData['data']; | ||
final ack = jsonData['ack']; | ||
|
||
switch (type) { | ||
case SyncEntityType.userV1: | ||
data.add( | ||
SyncEvent( | ||
data: SyncUserUpdateResponse.fromMap(dataJson), | ||
ack: ack, | ||
), | ||
); | ||
break; | ||
case SyncEntityType.userDeleteV1: | ||
data.add( | ||
SyncEvent( | ||
data: SyncUserDeleteResponse.fromMap(dataJson), | ||
ack: ack, | ||
), | ||
); | ||
break; | ||
default: | ||
debugPrint("[_parseSyncReponse] Unknown type $type"); | ||
} | ||
} catch (error, stack) { | ||
debugPrint("[_parseSyncReponse] Error parsing json $error $stack"); | ||
} | ||
} | ||
|
||
return data; | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@shenlong-tanwen I saw your note on not accessing the Store directly in the repo. How do you propose to access these values here?