Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mobile] Centralize upload queue transitions (#11430)

neeraj-pilotbfcedaf8c5c5
diff --git a/mobile/apps/photos/lib/events/backup_updated_event.dart b/mobile/apps/photos/lib/events/backup_updated_event.dart
index 7d710df199..f5ae0bc5b0 100644
--- a/mobile/apps/photos/lib/events/backup_updated_event.dart
+++ b/mobile/apps/photos/lib/events/backup_updated_event.dart
@@ -1,10 +1,8 @@
-import "dart:collection";
-
import "package:photos/events/event.dart";
import "package:photos/models/backup/backup_item.dart";
class BackupUpdatedEvent extends Event {
- final LinkedHashMap<String, BackupItem> items;
+ final Map<String, BackupItem> items;
BackupUpdatedEvent(this.items);
}
diff --git a/mobile/apps/photos/lib/module/upload/service/file_uploader.dart b/mobile/apps/photos/lib/module/upload/service/file_uploader.dart
index 5bd62b967e..6faa1de15e 100644
--- a/mobile/apps/photos/lib/module/upload/service/file_uploader.dart
+++ b/mobile/apps/photos/lib/module/upload/service/file_uploader.dart
@@ -1,5 +1,4 @@
import 'dart:async';
-import 'dart:collection';
import 'dart:convert';
import 'dart:io';
@@ -26,7 +25,6 @@ import "package:photos/gateways/collections/models/metadata.dart";
import "package:photos/gateways/files/file_upload_gateway.dart";
import "package:photos/main.dart" show isProcessBg, kLastBGTaskHeartBeatTime;
import "package:photos/models/backup/backup_item.dart";
-import "package:photos/models/backup/backup_item_status.dart";
import 'package:photos/models/file/file.dart';
import 'package:photos/models/file/file_type.dart';
import "package:photos/models/user_details.dart";
@@ -35,6 +33,7 @@ import 'package:photos/module/upload/model/media_upload_data.dart';
import 'package:photos/module/upload/model/upload_url.dart';
import "package:photos/module/upload/service/multipart.dart";
import 'package:photos/module/upload/service/upload_artifact_lifecycle.dart';
+import 'package:photos/module/upload/service/upload_queue.dart';
import "package:photos/module/upload/upload_data.dart";
import "package:photos/module/upload/upload_metadata.dart";
import "package:photos/service_locator.dart";
@@ -63,10 +62,9 @@ class FileUploader {
final _logger = Logger("FileUploader");
final _dio = NetworkClient.instance.getDio();
FileUploadGateway get _gateway => fileUploadGateway;
- final LinkedHashMap<String, FileUploadItem> _queue =
- LinkedHashMap<String, FileUploadItem>();
- final LinkedHashMap<String, BackupItem> _allBackups =
- LinkedHashMap<String, BackupItem>();
+ final _queue = UploadQueue(
+ (items) => Bus.instance.fire(BackupUpdatedEvent(items)),
+ );
final _uploadLocks = UploadLocksDB.instance;
final _uploadArtifactLifecycle = UploadArtifactLifecycle(
UploadLocksDB.instance,
@@ -77,23 +75,16 @@ class FileUploader {
// Track used upload URLs to detect race conditions
final Map<String, DateTime> _usedUploadURLs = {};
- LinkedHashMap<String, BackupItem> get allBackups => _allBackups;
+ Map<String, BackupItem> get allBackups => _queue.backupItems;
/// Returns true if any file uploads are currently in progress
- bool get isUploading => _uploadCounter > 0;
+ bool get isUploading => _queue.isUploading;
/// Returns true if an upload is queued, running, or waiting in background.
- bool get hasPendingUploads => _queue.isNotEmpty;
-
- // Maintains the count of files in the current upload session.
- // Upload session is the period between the first entry into the _queue and last entry out of the _queue
- int _totalCountInUploadSession = 0;
-
- // _uploadCounter indicates number of uploads which are currently in progress
- int _uploadCounter = 0;
- int _videoUploadCounter = 0;
+ bool get hasPendingUploads => _queue.hasPendingUploads;
late ProcessType _processType;
late SharedPreferences _prefs;
+ bool _hasStartedBackgroundUploadPolling = false;
late MultiPartUploader _multiPartUploader;
StreamSubscription<LocalPhotosUpdatedEvent>? _localPhotosUpdatedSubscription;
@@ -132,8 +123,11 @@ class FileUploader {
"BG task is alive, not clearing locks ${DateTime.fromMicrosecondsSinceEpoch(lastBGTaskHeartBeatTime)}",
);
}
- // ignore: unawaited_futures
- _pollBackgroundUploadStatus();
+ if (!_hasStartedBackgroundUploadPolling) {
+ _hasStartedBackgroundUploadPolling = true;
+ // ignore: unawaited_futures
+ _pollBackgroundUploadStatus();
+ }
}
_multiPartUploader = MultiPartUploader(
_dio, // legacy parameter, not used by MultiPartUploader
@@ -178,28 +172,15 @@ class FileUploader {
if (file.localID == null || file.localID!.isEmpty) {
return Future.error(Exception("file's localID can not be null or empty"));
}
- // If the file hasn't been queued yet, queue it for upload
- _totalCountInUploadSession++;
- final String localID = file.localID!;
- if (!_queue.containsKey(localID)) {
- final completer = Completer<EnteFile>();
- _queue[localID] = FileUploadItem(file, collectionID, completer);
- _allBackups[localID] = BackupItem(
- status: BackupItemStatus.inQueue,
- file: file,
- collectionID: collectionID,
- completer: completer,
- );
- Bus.instance.fire(BackupUpdatedEvent(_allBackups));
+ final request = _queue.add(file, collectionID);
+ if (request.disposition == UploadQueueDisposition.added) {
_pollQueue();
- return completer.future;
+ return request.item.completer.future;
}
// If the file exists in the queue for a matching collectionID,
// return the existing future
- final FileUploadItem item = _queue[localID]!;
- if (item.collectionID == collectionID) {
- _totalCountInUploadSession--;
- return item.completer.future;
+ if (request.disposition == UploadQueueDisposition.sameCollection) {
+ return request.item.completer.future;
}
debugPrint(
"Wait on another upload on same local ID to finish before "
@@ -207,7 +188,7 @@ class FileUploader {
);
// Else wait for the existing upload to complete,
// and add it to the relevant collection
- return item.completer.future.then((uploadedFile) {
+ return request.item.completer.future.then((uploadedFile) {
// If the fileUploader completer returned null,
_logger.info(
"original upload completer resolved, try adding the file to another "
@@ -223,16 +204,11 @@ class FileUploader {
}
int getCurrentSessionUploadCount() {
- return _totalCountInUploadSession;
+ return _queue.sessionUploadCount;
}
void clearQueue(final Error reason) {
- final pendingUploadIDs = _queue.entries
- .where((entry) => entry.value.status == UploadStatus.notStarted)
- .map((entry) => entry.key)
- .toList();
- _removePendingUploads(pendingUploadIDs, reason);
- _totalCountInUploadSession = 0;
+ _queue.clear(reason);
}
void clearCachedUploadURLs() {
@@ -262,30 +238,8 @@ class FileUploader {
final bool Function(EnteFile) fn,
final Error reason,
) {
- final pendingUploadIDs = _queue.entries
- .where(
- (entry) =>
- entry.value.status == UploadStatus.notStarted &&
- fn(entry.value.file),
- )
- .map((entry) => entry.key)
- .toList();
- _removePendingUploads(pendingUploadIDs, reason);
- _logger.info(
- 'number of entries removed from queue ${pendingUploadIDs.length}',
- );
- _totalCountInUploadSession -= pendingUploadIDs.length;
- }
-
- void _removePendingUploads(List<String> localIDs, Error reason) {
- for (final localID in localIDs) {
- _queue.remove(localID)?.completer.completeError(reason);
- _allBackups[localID] = _allBackups[localID]!.copyWith(
- status: BackupItemStatus.retry,
- error: reason,
- );
- Bus.instance.fire(BackupUpdatedEvent(_allBackups));
- }
+ final removedCount = _queue.removeWhere(fn, reason);
+ _logger.info('number of entries removed from queue $removedCount');
}
void _pollQueue() {
@@ -293,55 +247,21 @@ class FileUploader {
clearQueue(SyncStopRequestedError());
return;
}
- if (_queue.isEmpty) {
- // Upload session completed
- _totalCountInUploadSession = 0;
- return;
- }
- if (_uploadCounter < kMaximumConcurrentUploads) {
- var pendingEntry = _queue.entries
- .firstWhereOrNull(
- (entry) => entry.value.status == UploadStatus.notStarted,
- )
- ?.value;
-
- if (pendingEntry != null &&
- pendingEntry.file.fileType == FileType.video &&
- _videoUploadCounter >= kMaximumConcurrentVideoUploads) {
- // check if there's any non-video entry which can be queued for upload
- pendingEntry = _queue.entries
- .firstWhereOrNull(
- (entry) =>
- entry.value.status == UploadStatus.notStarted &&
- entry.value.file.fileType != FileType.video,
- )
- ?.value;
- }
- if (pendingEntry != null) {
- pendingEntry.status = UploadStatus.inProgress;
- _allBackups[pendingEntry.file.localID!] =
- _allBackups[pendingEntry.file.localID]!.copyWith(
- status: BackupItemStatus.uploading,
- );
- Bus.instance.fire(BackupUpdatedEvent(_allBackups));
- _encryptAndUploadFileToCollection(
- pendingEntry.file,
- pendingEntry.collectionID,
- );
- }
+ final pendingItem = _queue.startNext(
+ maximumConcurrentUploads: kMaximumConcurrentUploads,
+ maximumConcurrentVideoUploads: kMaximumConcurrentVideoUploads,
+ );
+ if (pendingItem != null) {
+ _encryptAndUploadFileToCollection(pendingItem);
}
}
Future<EnteFile?> _encryptAndUploadFileToCollection(
- EnteFile file,
- int collectionID, {
+ UploadQueueItem item, {
bool forcedUpload = false,
}) async {
- _uploadCounter++;
- if (file.fileType == FileType.video) {
- _videoUploadCounter++;
- }
- final localID = file.localID!;
+ final file = item.file;
+ final collectionID = item.collectionID;
try {
final uploadedFile = await _tryToUpload(file, collectionID, forcedUpload)
.timeout(
@@ -351,34 +271,17 @@ class FileUploader {
throw TimeoutException(message);
},
);
- _queue.remove(localID)!.completer.complete(uploadedFile);
- _allBackups[localID] = _allBackups[localID]!.copyWith(
- status: BackupItemStatus.uploaded,
- );
- Bus.instance.fire(BackupUpdatedEvent(_allBackups));
+ _queue.complete(item, uploadedFile);
return uploadedFile;
} catch (e) {
if (e is LockAlreadyAcquiredError) {
- _queue[localID]!.status = UploadStatus.inBackground;
- _allBackups[localID] = _allBackups[localID]!.copyWith(
- status: BackupItemStatus.inBackground,
- );
- Bus.instance.fire(BackupUpdatedEvent(_allBackups));
- return _queue[localID]!.completer.future;
+ return _queue.moveToBackground(item);
} else {
- _queue.remove(localID)!.completer.completeError(e);
- _allBackups[localID] = _allBackups[localID]!.copyWith(
- status: BackupItemStatus.retry,
- error: e,
- );
- Bus.instance.fire(BackupUpdatedEvent(_allBackups));
+ _queue.fail(item, e);
return null;
}
} finally {
- _uploadCounter--;
- if (file.fileType == FileType.video) {
- _videoUploadCounter--;
- }
+ _queue.finishAttempt(item);
_pollQueue();
}
}
@@ -425,23 +328,20 @@ class FileUploader {
Future<EnteFile> forceUpload(EnteFile file, int collectionID) {
return _uploadArtifactLifecycle.runForceUpload(() async {
- final isInQueue = _allBackups[file.localID!] != null;
+ final localID = file.localID!;
+ final backupOwner = _queue.backupOwner(localID);
+ if (backupOwner != null) {
+ _queue.markBackupUploading(backupOwner, localID);
+ }
try {
final result = await _tryToUpload(file, collectionID, true);
- if (isInQueue) {
- _allBackups[file.localID!] = _allBackups[file.localID]!.copyWith(
- status: BackupItemStatus.uploaded,
- );
- Bus.instance.fire(BackupUpdatedEvent(_allBackups));
+ if (backupOwner != null) {
+ _queue.markBackupUploaded(backupOwner, localID);
}
return result;
} catch (error) {
- if (isInQueue) {
- _allBackups[file.localID!] = _allBackups[file.localID]!.copyWith(
- status: BackupItemStatus.retry,
- error: error,
- );
- Bus.instance.fire(BackupUpdatedEvent(_allBackups));
+ if (backupOwner != null) {
+ _queue.markBackupForRetry(backupOwner, localID, error);
}
rethrow;
}
@@ -467,13 +367,6 @@ class FileUploader {
}
}
- if (_allBackups[file.localID!] != null &&
- _allBackups[file.localID]!.status != BackupItemStatus.uploading) {
- _allBackups[file.localID!] = _allBackups[file.localID]!.copyWith(
- status: BackupItemStatus.uploading,
- );
- Bus.instance.fire(BackupUpdatedEvent(_allBackups));
- }
if ((file.localID ?? '') == '') {
_logger.severe('Trying to upload file with missing localID');
return file;
@@ -1484,32 +1377,20 @@ class FileUploader {
// _pollBackgroundUploadStatus polls the background uploads to check if the
// upload is completed or failed.
Future<void> _pollBackgroundUploadStatus() async {
- final blockedUploads = _queue.entries
- .where((e) => e.value.status == UploadStatus.inBackground)
- .toList();
+ final blockedUploads = _queue.backgroundItems;
for (final upload in blockedUploads) {
- final file = upload.value.file;
+ final file = upload.file;
final isStillLocked = await _uploadLocks.isLocked(
file.localID!,
ProcessType.background.toString(),
);
if (!isStillLocked) {
- final completer = _queue.remove(upload.key)?.completer;
- final dbFile = await FilesDB.instance.getFile(
- upload.value.file.generatedID!,
- );
+ final dbFile = await FilesDB.instance.getFile(upload.file.generatedID!);
if (dbFile?.uploadedFileID != null) {
- _logger.info(
- "Background upload success detected ${upload.value.file.tag}",
- );
- completer?.complete(dbFile);
- _allBackups[upload.key] = _allBackups[upload.key]!.copyWith(
- status: BackupItemStatus.uploaded,
- );
+ _logger.info("Background upload success detected ${upload.file.tag}");
+ _queue.complete(upload, dbFile!);
} else {
- _logger.info(
- "Background upload failure detected ${upload.value.file.tag}",
- );
+ _logger.info("Background upload failure detected ${upload.file.tag}");
// The upload status is marked as in background, but the file is not locked
// by the background process. Release any lock taken by the foreground process
// and complete the completer with error.
@@ -1517,14 +1398,8 @@ class FileUploader {
file.localID!,
ProcessType.foreground.toString(),
);
- completer?.completeError(SilentlyCancelUploadsError());
- _allBackups[upload.key] = _allBackups[upload.key]!.copyWith(
- status: BackupItemStatus.retry,
- error: SilentlyCancelUploadsError(),
- );
+ _queue.fail(upload, SilentlyCancelUploadsError());
}
-
- Bus.instance.fire(BackupUpdatedEvent(_allBackups));
}
}
Future.delayed(kBlockedUploadsPollFrequency, () async {
@@ -1533,20 +1408,4 @@ class FileUploader {
}
}
-class FileUploadItem {
- final EnteFile file;
- final int collectionID;
- final Completer<EnteFile> completer;
- UploadStatus status;
-
- FileUploadItem(
- this.file,
- this.collectionID,
- this.completer, {
- this.status = UploadStatus.notStarted,
- });
-}
-
-enum UploadStatus { notStarted, inProgress, inBackground }
-
enum ProcessType { background, foreground }
diff --git a/mobile/apps/photos/lib/module/upload/service/upload_queue.dart b/mobile/apps/photos/lib/module/upload/service/upload_queue.dart
new file mode 100644
index 0000000000..433b0711ac
--- /dev/null
+++ b/mobile/apps/photos/lib/module/upload/service/upload_queue.dart
@@ -0,0 +1,273 @@
+import 'dart:async';
+
+import 'package:collection/collection.dart';
+import 'package:photos/models/backup/backup_item.dart';
+import 'package:photos/models/backup/backup_item_status.dart';
+import 'package:photos/models/file/file.dart';
+import 'package:photos/models/file/file_type.dart';
+
+typedef BackupItemsChanged = void Function(Map<String, BackupItem> items);
+
+class UploadQueue {
+ UploadQueue(this._onBackupItemsChanged);
+
+ final BackupItemsChanged _onBackupItemsChanged;
+ final _items = <String, UploadQueueItem>{};
+ final _backupItems = <String, BackupItem>{};
+ final _backupOwners = <String, Object>{};
+
+ Map<String, BackupItem> _backupItemsSnapshot = const {};
+ int _activeUploads = 0;
+ int _activeVideoUploads = 0;
+ int _sessionUploadCount = 0;
+
+ Map<String, BackupItem> get backupItems => _backupItemsSnapshot;
+ bool get hasPendingUploads => _items.isNotEmpty;
+ bool get isUploading => _activeUploads > 0;
+ int get sessionUploadCount => _sessionUploadCount;
+
+ UploadQueueRequest add(EnteFile file, int collectionID) {
+ final localID = file.localID!;
+ _sessionUploadCount++;
+ final existingItem = _items[localID];
+ if (existingItem != null) {
+ final isSameCollection = existingItem.collectionID == collectionID;
+ if (isSameCollection) {
+ _sessionUploadCount--;
+ }
+ return UploadQueueRequest.existing(existingItem, isSameCollection);
+ }
+
+ final completer = Completer<EnteFile>();
+ final item = UploadQueueItem(file, collectionID, completer);
+ _items[localID] = item;
+ _backupItems[localID] = BackupItem(
+ status: BackupItemStatus.inQueue,
+ file: file,
+ collectionID: collectionID,
+ completer: completer,
+ );
+ _backupOwners[localID] = item;
+ _notifyBackupItemsChanged();
+ return UploadQueueRequest.added(item);
+ }
+
+ void clear(Error reason) {
+ final pendingUploadIDs = _items.entries
+ .where((entry) => entry.value._status == _UploadStatus.notStarted)
+ .map((entry) => entry.key)
+ .toList();
+ _removePendingUploads(pendingUploadIDs, reason);
+ _sessionUploadCount = 0;
+ }
+
+ int removeWhere(bool Function(EnteFile) predicate, Error reason) {
+ final pendingUploadIDs = _items.entries
+ .where(
+ (entry) =>
+ entry.value._status == _UploadStatus.notStarted &&
+ predicate(entry.value.file),
+ )
+ .map((entry) => entry.key)
+ .toList();
+ _removePendingUploads(pendingUploadIDs, reason);
+ _sessionUploadCount -= pendingUploadIDs.length;
+ return pendingUploadIDs.length;
+ }
+
+ UploadQueueItem? startNext({
+ required int maximumConcurrentUploads,
+ required int maximumConcurrentVideoUploads,
+ }) {
+ if (_items.isEmpty) {
+ _sessionUploadCount = 0;
+ return null;
+ }
+ if (_activeUploads >= maximumConcurrentUploads) {
+ return null;
+ }
+
+ var pendingItem = _items.values.firstWhereOrNull(
+ (item) => item._status == _UploadStatus.notStarted,
+ );
+ if (pendingItem?.file.fileType == FileType.video &&
+ _activeVideoUploads >= maximumConcurrentVideoUploads) {
+ pendingItem = _items.values.firstWhereOrNull(
+ (item) =>
+ item._status == _UploadStatus.notStarted &&
+ item.file.fileType != FileType.video,
+ );
+ }
+ if (pendingItem == null) {
+ return null;
+ }
+
+ pendingItem._status = _UploadStatus.inProgress;
+ _activeUploads++;
+ if (pendingItem.file.fileType == FileType.video) {
+ _activeVideoUploads++;
+ }
+ _setBackupStatus(
+ pendingItem.file.localID!,
+ pendingItem,
+ BackupItemStatus.uploading,
+ );
+ return pendingItem;
+ }
+
+ void finishAttempt(UploadQueueItem item) {
+ _activeUploads--;
+ if (item.file.fileType == FileType.video) {
+ _activeVideoUploads--;
+ }
+ }
+
+ void complete(UploadQueueItem item, EnteFile uploadedFile) {
+ final localID = item.file.localID!;
+ if (!identical(_items[localID], item)) {
+ return;
+ }
+ _items.remove(localID);
+ item.completer.complete(uploadedFile);
+ _backupItems.remove(localID);
+ _backupOwners.remove(localID);
+ _notifyBackupItemsChanged();
+ }
+
+ Future<EnteFile> moveToBackground(UploadQueueItem item) {
+ final localID = item.file.localID!;
+ if (!identical(_items[localID], item)) {
+ return item.completer.future;
+ }
+ item._status = _UploadStatus.inBackground;
+ _setBackupStatus(localID, item, BackupItemStatus.inBackground);
+ return item.completer.future;
+ }
+
+ void fail(UploadQueueItem item, Object error) {
+ final localID = item.file.localID!;
+ if (!identical(_items[localID], item)) {
+ return;
+ }
+ _items.remove(localID);
+ item.completer.completeError(error);
+ _setBackupStatus(localID, item, BackupItemStatus.retry, error: error);
+ }
+
+ Object? backupOwner(String localID) => _backupOwners[localID];
+
+ void markBackupUploading(Object owner, String localID) {
+ if (_backupItems[localID]?.status != BackupItemStatus.uploading) {
+ _setBackupStatusIfOwned(localID, owner, BackupItemStatus.uploading);
+ }
+ }
+
+ void markBackupUploaded(Object owner, String localID) {
+ if (!identical(_backupOwners[localID], owner)) {
+ return;
+ }
+ if (_items.containsKey(localID)) {
+ _setBackupStatus(localID, owner, BackupItemStatus.uploaded);
+ } else if (_backupItems.remove(localID) != null) {
+ _backupOwners.remove(localID);
+ _notifyBackupItemsChanged();
+ }
+ }
+
+ void markBackupForRetry(Object owner, String localID, Object error) {
+ _setBackupStatusIfOwned(
+ localID,
+ owner,
+ BackupItemStatus.retry,
+ error: error,
+ );
+ }
+
+ List<UploadQueueItem> get backgroundItems => _items.values
+ .where((item) => item._status == _UploadStatus.inBackground)
+ .toList();
+
+ void _removePendingUploads(List<String> localIDs, Error reason) {
+ if (localIDs.isEmpty) {
+ return;
+ }
+ for (final localID in localIDs) {
+ _items.remove(localID)?.completer.completeError(reason);
+ _setBackupStatusWithoutNotification(
+ localID,
+ _backupOwners[localID]!,
+ BackupItemStatus.retry,
+ error: reason,
+ );
+ }
+ _notifyBackupItemsChanged();
+ }
+
+ void _setBackupStatus(
+ String localID,
+ Object owner,
+ BackupItemStatus status, {
+ Object? error,
+ }) {
+ _setBackupStatusWithoutNotification(localID, owner, status, error: error);
+ _notifyBackupItemsChanged();
+ }
+
+ void _setBackupStatusIfOwned(
+ String localID,
+ Object owner,
+ BackupItemStatus status, {
+ Object? error,
+ }) {
+ if (!identical(_backupOwners[localID], owner)) {
+ return;
+ }
+ _setBackupStatus(localID, owner, status, error: error);
+ }
+
+ void _setBackupStatusWithoutNotification(
+ String localID,
+ Object owner,
+ BackupItemStatus status, {
+ Object? error,
+ }) {
+ if (!identical(_backupOwners[localID], owner)) {
+ return;
+ }
+ _backupItems[localID] = _backupItems[localID]!.copyWith(
+ status: status,
+ error: error,
+ );
+ }
+
+ void _notifyBackupItemsChanged() {
+ _backupItemsSnapshot = Map.unmodifiable(_backupItems);
+ _onBackupItemsChanged(_backupItemsSnapshot);
+ }
+}
+
+class UploadQueueRequest {
+ UploadQueueRequest.added(this.item)
+ : disposition = UploadQueueDisposition.added;
+
+ UploadQueueRequest.existing(this.item, bool isSameCollection)
+ : disposition = isSameCollection
+ ? UploadQueueDisposition.sameCollection
+ : UploadQueueDisposition.otherCollection;
+
+ final UploadQueueItem item;
+ final UploadQueueDisposition disposition;
+}
+
+enum UploadQueueDisposition { added, sameCollection, otherCollection }
+
+class UploadQueueItem {
+ UploadQueueItem(this.file, this.collectionID, this.completer);
+
+ final EnteFile file;
+ final int collectionID;
+ final Completer<EnteFile> completer;
+ _UploadStatus _status = _UploadStatus.notStarted;
+}
+
+enum _UploadStatus { notStarted, inProgress, inBackground }
diff --git a/mobile/apps/photos/lib/ui/settings/backup/backup_status_screen.dart b/mobile/apps/photos/lib/ui/settings/backup/backup_status_screen.dart
index fcc5c9b050..503187c5b5 100644
--- a/mobile/apps/photos/lib/ui/settings/backup/backup_status_screen.dart
+++ b/mobile/apps/photos/lib/ui/settings/backup/backup_status_screen.dart
@@ -1,6 +1,5 @@
// ignore_for_file: public_member_api_docs, sort_constructors_first
import "dart:async";
-import "dart:collection";
import "package:collection/collection.dart";
import "package:ente_components/ente_components.dart";
@@ -25,7 +24,7 @@ class BackupStatusScreen extends StatefulWidget {
}
class _BackupStatusScreenState extends State<BackupStatusScreen> {
- LinkedHashMap<String, BackupItem> items = FileUploader.instance.allBackups;
+ Map<String, BackupItem> items = FileUploader.instance.allBackups;
List<BackupItem>? result;
StreamSubscription? _fileUploadedSubscription;
StreamSubscription? _backupUpdatedSubscription;
diff --git a/mobile/apps/photos/test/module/upload/service/upload_queue_test.dart b/mobile/apps/photos/test/module/upload/service/upload_queue_test.dart
new file mode 100644
index 0000000000..c639b062c3
--- /dev/null
+++ b/mobile/apps/photos/test/module/upload/service/upload_queue_test.dart
@@ -0,0 +1,122 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:photos/models/backup/backup_item.dart';
+import 'package:photos/models/backup/backup_item_status.dart';
+import 'package:photos/models/file/file.dart';
+import 'package:photos/models/file/file_type.dart';
+import 'package:photos/module/upload/service/upload_queue.dart';
+
+void main() {
+ test('shares requests and preserves session count semantics', () {
+ final snapshots = <Map<String, BackupItem>>[];
+ final queue = UploadQueue(snapshots.add);
+ final file = _file('local-1');
+
+ final added = queue.add(file, 10);
+ final sameCollection = queue.add(file, 10);
+ final otherCollection = queue.add(file, 20);
+
+ expect(added.disposition, UploadQueueDisposition.added);
+ expect(sameCollection.disposition, UploadQueueDisposition.sameCollection);
+ expect(otherCollection.disposition, UploadQueueDisposition.otherCollection);
+ expect(identical(added.item, sameCollection.item), isTrue);
+ expect(identical(added.item, otherCollection.item), isTrue);
+ expect(queue.sessionUploadCount, 2);
+ expect(snapshots, hasLength(1));
+ expect(
+ () => snapshots.single['other'] = snapshots.single.values.single,
+ throwsUnsupportedError,
+ );
+ });
+
+ test('selects FIFO work within total and video limits', () {
+ final queue = UploadQueue((_) {});
+ final firstVideo = queue.add(_file('video-1', FileType.video), 1).item;
+ final secondVideo = queue.add(_file('video-2', FileType.video), 1).item;
+ final thirdVideo = queue.add(_file('video-3', FileType.video), 1).item;
+ final image = queue.add(_file('image-1'), 1).item;
+
+ expect(_start(queue), same(firstVideo));
+ expect(_start(queue), same(secondVideo));
+ expect(_start(queue), same(image));
+ expect(_start(queue), isNull);
+
+ queue.finishAttempt(firstVideo);
+ expect(_start(queue), same(thirdVideo));
+ expect(queue.isUploading, isTrue);
+ expect(queue.backupItems['video-3']!.status, BackupItemStatus.uploading);
+ });
+
+ test('cancels pending items with one backup notification', () async {
+ final snapshots = <Map<String, BackupItem>>[];
+ final queue = UploadQueue(snapshots.add);
+ final active = queue.add(_file('active'), 1).item;
+ final firstPending = queue.add(_file('pending-1'), 1).item;
+ final secondPending = queue.add(_file('pending-2'), 1).item;
+ _start(queue);
+ final error = _QueueError();
+ final firstResult = expectLater(
+ firstPending.completer.future,
+ throwsA(error),
+ );
+ final secondResult = expectLater(
+ secondPending.completer.future,
+ throwsA(error),
+ );
+ final notificationsBeforeRemoval = snapshots.length;
+
+ final removed = queue.removeWhere((_) => true, error);
+
+ expect(removed, 2);
+ expect(snapshots.length, notificationsBeforeRemoval + 1);
+ expect(queue.hasPendingUploads, isTrue);
+ expect(queue.backupItems['active']!.status, BackupItemStatus.uploading);
+ expect(queue.backupItems['pending-1']!.status, BackupItemStatus.retry);
+ expect(queue.backupItems['pending-2']!.status, BackupItemStatus.retry);
+ await firstResult;
+ await secondResult;
+ queue.finishAttempt(active);
+ });
+
+ test('stale transitions cannot mutate a newer request', () async {
+ final queue = UploadQueue((_) {});
+ final firstItem = queue.add(_file('same-local'), 1).item;
+ expect(_start(queue), same(firstItem));
+ final firstError = _QueueError();
+ final firstResult = expectLater(
+ firstItem.completer.future,
+ throwsA(firstError),
+ );
+ queue.fail(firstItem, firstError);
+ queue.finishAttempt(firstItem);
+ await firstResult;
+
+ final secondItem = queue.add(_file('same-local'), 1).item;
+ queue.complete(firstItem, _file('uploaded-old'));
+ queue.markBackupForRetry(firstItem, 'same-local', _QueueError());
+
+ expect(queue.hasPendingUploads, isTrue);
+ expect(queue.backupItems['same-local']!.status, BackupItemStatus.inQueue);
+ expect(_start(queue), same(secondItem));
+
+ final uploadedFile = _file('uploaded-new');
+ queue.complete(secondItem, uploadedFile);
+ queue.finishAttempt(secondItem);
+ expect(await secondItem.completer.future, same(uploadedFile));
+ expect(queue.backupItems, isEmpty);
+ });
+}
+
+UploadQueueItem? _start(UploadQueue queue) {
+ return queue.startNext(
+ maximumConcurrentUploads: 4,
+ maximumConcurrentVideoUploads: 2,
+ );
+}
+
+EnteFile _file(String localID, [FileType fileType = FileType.image]) {
+ return EnteFile()
+ ..localID = localID
+ ..fileType = fileType;
+}
+
+class _QueueError extends Error {}