Skip to content

armgit / ente

Public Imported from GitHub
0

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

add debug logging for background upload failures

Prateek Sunald677e782f31c
diff --git a/mobile/apps/photos/lib/services/sync/remote_sync_service.dart b/mobile/apps/photos/lib/services/sync/remote_sync_service.dart
index 038ee1bb50..108e3bea89 100644
--- a/mobile/apps/photos/lib/services/sync/remote_sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/remote_sync_service.dart
@@ -601,92 +601,319 @@ class RemoteSyncService {
_ignoredUploads = 0;
final int toBeUploaded = filesToBeUploaded.length + updatedFileIDs.length;
if (toBeUploaded > 0) {
+ _logger.info(
+ "[UPLOAD-DEBUG] Preparing to upload $toBeUploaded files "
+ "(${filesToBeUploaded.length} new, ${updatedFileIDs.length} updated) "
+ "in ${isProcessBg ? 'BACKGROUND' : 'FOREGROUND'} mode",
+ );
+
+ // Add random delay to detect if OS is killing background tasks
+ final randomDelaySeconds = 3 + Random().nextInt(6); // 3-8 seconds
+ _logger.info(
+ "[UPLOAD-DEBUG] Adding random delay of $randomDelaySeconds seconds "
+ "before preparingForUpload to detect potential OS kills...",
+ );
+ final delayStartTime = DateTime.now();
+ await Future.delayed(Duration(seconds: randomDelaySeconds));
+ final delayEndTime = DateTime.now();
+ final actualDelayMs =
+ delayEndTime.difference(delayStartTime).inMilliseconds;
+ _logger.info(
+ "[UPLOAD-DEBUG] Random delay completed successfully! "
+ "Expected: ${randomDelaySeconds}s, Actual: ${actualDelayMs}ms. "
+ "Task was NOT killed by OS during delay.",
+ );
+
Bus.instance.fire(
SyncStatusUpdate(SyncStatus.preparingForUpload, total: toBeUploaded),
);
- await _uploader.verifyMediaLocationAccess();
- await _uploader.checkNetworkForUpload();
- // verify if files upload is allowed based on their subscription plan and
- // storage limit. To avoid creating new endpoint, we are using
- // fetchUploadUrls as alternative method.
- await _uploader.fetchUploadURLs(toBeUploaded);
+ _logger.info("[UPLOAD-DEBUG] Fired preparingForUpload status update");
+
+ // Step 1: Verify media location access permission
+ _logger.info(
+ "[UPLOAD-DEBUG] Step 1/3: Checking media location access permission...",
+ );
+ try {
+ await _uploader.verifyMediaLocationAccess();
+ _logger
+ .info("[UPLOAD-DEBUG] Step 1/3: Media location access verified βœ“");
+ } catch (e, s) {
+ _logger.severe(
+ "[UPLOAD-DEBUG] Step 1/3: Media location access check FAILED βœ—",
+ e,
+ s,
+ );
+ _logger.severe(
+ "[UPLOAD-DEBUG] Upload cannot proceed - permission error. "
+ "This is likely why background uploads fail.",
+ );
+ rethrow;
+ }
+
+ // Step 2: Check network availability for upload
+ _logger.info(
+ "[UPLOAD-DEBUG] Step 2/3: Checking network availability for upload...",
+ );
+ try {
+ await _uploader.checkNetworkForUpload();
+ _logger.info("[UPLOAD-DEBUG] Step 2/3: Network check passed βœ“");
+ } catch (e, s) {
+ _logger.severe(
+ "[UPLOAD-DEBUG] Step 2/3: Network check FAILED βœ—",
+ e,
+ s,
+ );
+ _logger.severe(
+ "[UPLOAD-DEBUG] Upload cannot proceed - network unavailable. "
+ "Requires WiFi or user enabled mobile data upload.",
+ );
+ rethrow;
+ }
+
+ // Step 3: Fetch upload URLs from server
+ _logger.info(
+ "[UPLOAD-DEBUG] Step 3/3: Fetching upload URLs from server for $toBeUploaded files...",
+ );
+ try {
+ await _uploader.fetchUploadURLs(toBeUploaded);
+ _logger.info(
+ "[UPLOAD-DEBUG] Step 3/3: Upload URLs fetched successfully βœ“",
+ );
+ } catch (e, s) {
+ _logger.severe(
+ "[UPLOAD-DEBUG] Step 3/3: Fetching upload URLs FAILED βœ—",
+ e,
+ s,
+ );
+ _logger.severe(
+ "[UPLOAD-DEBUG] Upload cannot proceed - server error or quota exceeded. "
+ "Check subscription status and storage limits.",
+ );
+ rethrow;
+ }
+
+ _logger.info(
+ "[UPLOAD-DEBUG] All pre-upload checks completed successfully! "
+ "Proceeding to queue individual file uploads...",
+ );
+ } else {
+ _logger.info(
+ "[UPLOAD-DEBUG] No files to upload, skipping upload preparation",
+ );
}
final List<Future> futures = [];
+ _logger.info(
+ "[UPLOAD-DEBUG] Starting to queue ${filesToBeUploaded.length} new files for upload...",
+ );
+ int queuedCount = 0;
for (final file in filesToBeUploaded) {
if (shouldThrottleUpload &&
futures.length >= kMaximumPermissibleUploadsInThrottledMode) {
- _logger.info("Skipping some new files as we are throttling uploads");
+ _logger.info(
+ "[UPLOAD-DEBUG] Throttle limit reached (${futures.length} files queued). "
+ "Skipping remaining ${filesToBeUploaded.length - queuedCount} files.",
+ );
break;
}
// prefer existing collection ID for manually uploaded files.
// See https://github.com/ente-io/photos-app/pull/187
- final collectionID = file.collectionID ??
- (await _collectionsService
- .getOrCreateForPath(file.deviceFolder ?? 'Unknown Folder'))
- .id;
- _uploadFile(file, collectionID, futures);
+ _logger.info(
+ "[UPLOAD-DEBUG] Queueing file ${queuedCount + 1}/${filesToBeUploaded.length}: "
+ "${file.title} (localID: ${file.localID}, generatedID: ${file.generatedID})",
+ );
+ try {
+ final collectionID = file.collectionID ??
+ (await _collectionsService
+ .getOrCreateForPath(file.deviceFolder ?? 'Unknown Folder'))
+ .id;
+ _logger.info(
+ "[UPLOAD-DEBUG] Resolved collectionID: $collectionID for file ${file.title}",
+ );
+ _uploadFile(file, collectionID, futures);
+ queuedCount++;
+ _logger.info(
+ "[UPLOAD-DEBUG] Successfully queued file ${file.title} ($queuedCount queued so far)",
+ );
+ } catch (e, s) {
+ _logger.severe(
+ "[UPLOAD-DEBUG] Failed to queue file ${file.title}",
+ e,
+ s,
+ );
+ }
}
+ _logger.info(
+ "[UPLOAD-DEBUG] Finished queueing new files. Total queued: $queuedCount/${filesToBeUploaded.length}",
+ );
+ _logger.info(
+ "[UPLOAD-DEBUG] Starting to queue ${updatedFileIDs.length} updated files for re-upload...",
+ );
+ int reuploadQueuedCount = 0;
for (final uploadedFileID in updatedFileIDs) {
if (shouldThrottleUpload &&
futures.length >= kMaximumPermissibleUploadsInThrottledMode) {
- _logger
- .info("Skipping some updated files as we are throttling uploads");
+ _logger.info(
+ "[UPLOAD-DEBUG] Throttle limit reached for re-uploads (${futures.length} total queued). "
+ "Skipping remaining ${updatedFileIDs.length - reuploadQueuedCount} updated files.",
+ );
break;
}
- final allFiles = await _db.getFilesInAllCollection(
- uploadedFileID,
- ownerID,
+ _logger.info(
+ "[UPLOAD-DEBUG] Processing updated file ${reuploadQueuedCount + 1}/${updatedFileIDs.length} "
+ "(uploadedFileID: $uploadedFileID)",
);
- if (allFiles.isEmpty) {
- _logger.warning("No files found for uploadedFileID $uploadedFileID");
- continue;
- }
- EnteFile? fileInCollectionOwnedByUser;
- for (final file in allFiles) {
- if (file.canReUpload(ownerID)) {
- fileInCollectionOwnedByUser = file;
- break;
+ try {
+ final allFiles = await _db.getFilesInAllCollection(
+ uploadedFileID,
+ ownerID,
+ );
+ if (allFiles.isEmpty) {
+ _logger.warning(
+ "[UPLOAD-DEBUG] No files found for uploadedFileID $uploadedFileID, skipping",
+ );
+ continue;
}
- }
- if (fileInCollectionOwnedByUser != null) {
- _uploadFile(
- fileInCollectionOwnedByUser,
- fileInCollectionOwnedByUser.collectionID!,
- futures,
+ _logger.info(
+ "[UPLOAD-DEBUG] Found ${allFiles.length} file(s) for uploadedFileID $uploadedFileID",
+ );
+ EnteFile? fileInCollectionOwnedByUser;
+ for (final file in allFiles) {
+ if (file.canReUpload(ownerID)) {
+ fileInCollectionOwnedByUser = file;
+ break;
+ }
+ }
+ if (fileInCollectionOwnedByUser != null) {
+ _logger.info(
+ "[UPLOAD-DEBUG] Queueing re-upload for ${fileInCollectionOwnedByUser.title}",
+ );
+ _uploadFile(
+ fileInCollectionOwnedByUser,
+ fileInCollectionOwnedByUser.collectionID!,
+ futures,
+ );
+ reuploadQueuedCount++;
+ _logger.info(
+ "[UPLOAD-DEBUG] Successfully queued re-upload ($reuploadQueuedCount re-uploads queued)",
+ );
+ } else {
+ _logger.warning(
+ "[UPLOAD-DEBUG] No re-uploadable file found for uploadedFileID $uploadedFileID",
+ );
+ }
+ } catch (e, s) {
+ _logger.severe(
+ "[UPLOAD-DEBUG] Failed to queue re-upload for uploadedFileID $uploadedFileID",
+ e,
+ s,
);
}
}
+ _logger.info(
+ "[UPLOAD-DEBUG] Finished queueing updated files. Total re-uploads queued: "
+ "$reuploadQueuedCount/${updatedFileIDs.length}",
+ );
+
+ _logger.info(
+ "[UPLOAD-DEBUG] ═══════════════════════════════════════════════════════",
+ );
+ _logger.info(
+ "[UPLOAD-DEBUG] SUMMARY: Total ${futures.length} upload futures queued",
+ );
+ _logger.info(
+ "[UPLOAD-DEBUG] - New files queued: $queuedCount/${filesToBeUploaded.length}",
+ );
+ _logger.info(
+ "[UPLOAD-DEBUG] - Re-uploads queued: $reuploadQueuedCount/${updatedFileIDs.length}",
+ );
+ _logger.info(
+ "[UPLOAD-DEBUG] - Process mode: ${isProcessBg ? 'BACKGROUND' : 'FOREGROUND'}",
+ );
+ _logger.info(
+ "[UPLOAD-DEBUG] Now waiting for all ${futures.length} upload futures to complete...",
+ );
+ _logger.info(
+ "[UPLOAD-DEBUG] ═══════════════════════════════════════════════════════",
+ );
try {
await Future.wait(futures);
- } on InvalidFileError {
+ _logger.info(
+ "[UPLOAD-DEBUG] All upload futures completed successfully! "
+ "Completed: $_completedUploads, Ignored: $_ignoredUploads",
+ );
+ } on InvalidFileError catch (e, s) {
+ _logger.warning("[UPLOAD-DEBUG] InvalidFileError caught (ignored)", e, s);
// Do nothing
- } on FileSystemException {
+ } on FileSystemException catch (e, s) {
+ _logger.warning(
+ "[UPLOAD-DEBUG] FileSystemException caught (ignored - likely concurrency issue)",
+ e,
+ s,
+ );
// Do nothing since it's caused mostly due to concurrency issues
// when the foreground app deletes temporary files, interrupting a background
// upload
- } on LockAlreadyAcquiredError {
+ } on LockAlreadyAcquiredError catch (e, s) {
+ _logger.warning(
+ "[UPLOAD-DEBUG] LockAlreadyAcquiredError caught (ignored)",
+ e,
+ s,
+ );
// Do nothing
- } on SilentlyCancelUploadsError {
+ } on SilentlyCancelUploadsError catch (e, s) {
+ _logger.warning(
+ "[UPLOAD-DEBUG] SilentlyCancelUploadsError caught (ignored)",
+ e,
+ s,
+ );
// Do nothing
- } on UserCancelledUploadError {
+ } on UserCancelledUploadError catch (e, s) {
+ _logger.warning(
+ "[UPLOAD-DEBUG] UserCancelledUploadError caught (ignored)",
+ e,
+ s,
+ );
// Do nothing
- } catch (e) {
+ } catch (e, s) {
+ _logger.severe("[UPLOAD-DEBUG] Unexpected error during upload", e, s);
rethrow;
}
- return _completedUploads > 0;
+
+ final hasUploaded = _completedUploads > 0;
+ _logger.info(
+ "[UPLOAD-DEBUG] Upload process finished. Returning hasUploaded=$hasUploaded "
+ "(completedUploads: $_completedUploads)",
+ );
+ return hasUploaded;
}
void _uploadFile(EnteFile file, int collectionID, List<Future> futures) {
- final future = _uploader
- .upload(file, collectionID)
- .then((uploadedFile) => _onFileUploaded(uploadedFile))
- .onError(
- (error, stackTrace) => _onFileUploadError(error, stackTrace, file),
- );
+ _logger.info(
+ "[UPLOAD-DEBUG] _uploadFile() called for ${file.title} "
+ "(localID: ${file.localID}, collectionID: $collectionID). "
+ "Calling FileUploader.upload()...",
+ );
+ final future = _uploader.upload(file, collectionID).then((uploadedFile) {
+ _logger.info(
+ "[UPLOAD-DEBUG] Upload completed successfully for ${uploadedFile.title}",
+ );
+ return _onFileUploaded(uploadedFile);
+ }).onError((error, stackTrace) {
+ _logger.severe(
+ "[UPLOAD-DEBUG] Upload failed for ${file.title}",
+ error,
+ stackTrace,
+ );
+ return _onFileUploadError(error, stackTrace, file);
+ });
futures.add(future);
+ _logger.info(
+ "[UPLOAD-DEBUG] Upload future added to futures list for ${file.title} "
+ "(futures count: ${futures.length})",
+ );
}
Future<void> _onFileUploaded(EnteFile file) async {
diff --git a/mobile/apps/photos/lib/utils/file_uploader.dart b/mobile/apps/photos/lib/utils/file_uploader.dart
index 698328a82f..607971b9c9 100644
--- a/mobile/apps/photos/lib/utils/file_uploader.dart
+++ b/mobile/apps/photos/lib/utils/file_uploader.dart
@@ -164,13 +164,26 @@ class FileUploader {
// upload future will return null as File when the file entry is deleted
// locally because it's already present in the destination collection.
Future<EnteFile> upload(EnteFile file, int collectionID) {
+ _logger.info(
+ "[UPLOAD-DEBUG] FileUploader.upload() called for ${file.title} "
+ "(localID: ${file.localID}, collectionID: $collectionID, "
+ "isProcessBg: $isProcessBg)",
+ );
+
if (file.localID == null || file.localID!.isEmpty) {
+ _logger.severe(
+ "[UPLOAD-DEBUG] Upload rejected - file's localID is null or empty for ${file.title}",
+ );
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)) {
+ _logger.info(
+ "[UPLOAD-DEBUG] File ${file.title} not in queue. Adding to upload queue... "
+ "(queue size before: ${_queue.length})",
+ );
final completer = Completer<EnteFile>();
_queue[localID] = FileUploadItem(file, collectionID, completer);
_allBackups[localID] = BackupItem(
@@ -180,16 +193,33 @@ class FileUploader {
completer: completer,
);
Bus.instance.fire(BackupUpdatedEvent(_allBackups));
+ _logger.info(
+ "[UPLOAD-DEBUG] File ${file.title} added to queue (queue size: ${_queue.length}). "
+ "Calling _pollQueue()...",
+ );
_pollQueue();
+ _logger.info(
+ "[UPLOAD-DEBUG] _pollQueue() called for ${file.title}. Returning completer.future",
+ );
return completer.future;
}
// If the file exists in the queue for a matching collectionID,
// return the existing future
+ _logger.info(
+ "[UPLOAD-DEBUG] File ${file.title} already in queue with localID $localID",
+ );
final FileUploadItem item = _queue[localID]!;
if (item.collectionID == collectionID) {
_totalCountInUploadSession--;
+ _logger.info(
+ "[UPLOAD-DEBUG] Same collectionID ($collectionID) - returning existing future",
+ );
return item.completer.future;
}
+ _logger.info(
+ "[UPLOAD-DEBUG] Different collectionID (existing: ${item.collectionID}, new: $collectionID) "
+ "- waiting for existing upload to complete",
+ );
debugPrint(
"Wait on another upload on same local ID to finish before "
"adding it to new collection",
@@ -261,24 +291,53 @@ class FileUploader {
}
void _pollQueue() {
+ _logger.info(
+ "[UPLOAD-DEBUG] _pollQueue() called. Queue size: ${_queue.length}, "
+ "uploadCounter: $_uploadCounter/$kMaximumConcurrentUploads, "
+ "isProcessBg: $isProcessBg",
+ );
+
if (SyncService.instance.shouldStopSync()) {
+ _logger.warning("[UPLOAD-DEBUG] Sync stop requested - clearing queue");
clearQueue(SyncStopRequestedError());
+ return;
}
if (_queue.isEmpty) {
// Upload session completed
+ _logger.info(
+ "[UPLOAD-DEBUG] Queue is empty - upload session completed. "
+ "Resetting totalCountInUploadSession",
+ );
_totalCountInUploadSession = 0;
return;
}
if (_uploadCounter < kMaximumConcurrentUploads) {
+ _logger.info(
+ "[UPLOAD-DEBUG] Upload capacity available ($_uploadCounter < $kMaximumConcurrentUploads). "
+ "Searching for pending entry...",
+ );
var pendingEntry = _queue.entries
.firstWhereOrNull(
(entry) => entry.value.status == UploadStatus.notStarted,
)
?.value;
+ if (pendingEntry != null) {
+ _logger.info(
+ "[UPLOAD-DEBUG] Found pending entry: ${pendingEntry.file.title} "
+ "(fileType: ${pendingEntry.file.fileType})",
+ );
+ } else {
+ _logger.info("[UPLOAD-DEBUG] No pending entry found in queue");
+ }
+
if (pendingEntry != null &&
pendingEntry.file.fileType == FileType.video &&
_videoUploadCounter >= kMaximumConcurrentVideoUploads) {
+ _logger.info(
+ "[UPLOAD-DEBUG] Video upload limit reached ($_videoUploadCounter >= $kMaximumConcurrentVideoUploads). "
+ "Looking for non-video entry...",
+ );
// check if there's any non-video entry which can be queued for upload
pendingEntry = _queue.entries
.firstWhereOrNull(
@@ -287,8 +346,19 @@ class FileUploader {
entry.value.file.fileType != FileType.video,
)
?.value;
+ if (pendingEntry != null) {
+ _logger.info(
+ "[UPLOAD-DEBUG] Found non-video entry: ${pendingEntry.file.title}",
+ );
+ } else {
+ _logger.info("[UPLOAD-DEBUG] No non-video entry available");
+ }
}
if (pendingEntry != null) {
+ _logger.info(
+ "[UPLOAD-DEBUG] Starting upload for ${pendingEntry.file.title}. "
+ "Marking as inProgress and calling _encryptAndUploadFileToCollection()...",
+ );
pendingEntry.status = UploadStatus.inProgress;
_allBackups[pendingEntry.file.localID!] =
_allBackups[pendingEntry.file.localID]!
@@ -298,7 +368,20 @@ class FileUploader {
pendingEntry.file,
pendingEntry.collectionID,
);
+ _logger.info(
+ "[UPLOAD-DEBUG] _encryptAndUploadFileToCollection() initiated for ${pendingEntry.file.title}",
+ );
+ } else {
+ _logger.info(
+ "[UPLOAD-DEBUG] No pending entry to process at this time "
+ "(either all uploads in progress or video limit reached)",
+ );
}
+ } else {
+ _logger.info(
+ "[UPLOAD-DEBUG] Upload capacity full ($_uploadCounter >= $kMaximumConcurrentUploads). "
+ "Waiting for uploads to complete...",
+ );
}
}
@@ -307,21 +390,36 @@ class FileUploader {
int collectionID, {
bool forcedUpload = false,
}) async {
+ _logger.info(
+ "[UPLOAD-DEBUG] _encryptAndUploadFileToCollection() started for ${file.title} "
+ "(collectionID: $collectionID, forcedUpload: $forcedUpload, "
+ "isProcessBg: $isProcessBg)",
+ );
_uploadCounter++;
if (file.fileType == FileType.video) {
_videoUploadCounter++;
}
+ _logger.info(
+ "[UPLOAD-DEBUG] Upload counters updated: uploadCounter=$_uploadCounter, "
+ "videoUploadCounter=$_videoUploadCounter",
+ );
final localID = file.localID!;
try {
+ _logger.info(
+ "[UPLOAD-DEBUG] Calling _tryToUpload() for ${file.title} with ${kFileUploadTimeout.inSeconds}s timeout...",
+ );
final uploadedFile =
await _tryToUpload(file, collectionID, forcedUpload).timeout(
kFileUploadTimeout,
onTimeout: () {
final message = "Upload timed out for file " + file.toString();
- _logger.warning(message);
+ _logger.warning("[UPLOAD-DEBUG] $message");
throw TimeoutException(message);
},
);
+ _logger.info(
+ "[UPLOAD-DEBUG] _tryToUpload() completed successfully for ${file.title}",
+ );
_queue.remove(localID)!.completer.complete(uploadedFile);
_allBackups[localID] =
_allBackups[localID]!.copyWith(status: BackupItemStatus.uploaded);