Skip to content

armgit / ente

Public Imported from GitHub
0

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

Use priority queue for more efficient fetching of local thumbnails

ashilkna57041d0d2d3
diff --git a/mobile/lib/ui/viewer/file/thumbnail_widget.dart b/mobile/lib/ui/viewer/file/thumbnail_widget.dart
index 4ace74da94..e5f74d0d59 100644
--- a/mobile/lib/ui/viewer/file/thumbnail_widget.dart
+++ b/mobile/lib/ui/viewer/file/thumbnail_widget.dart
@@ -1,4 +1,6 @@
import "dart:async";
+import "dart:math";
+import "dart:typed_data";
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
@@ -21,6 +23,7 @@ import 'package:photos/ui/viewer/file/file_icons_widget.dart';
import "package:photos/ui/viewer/gallery/component/group/type.dart";
import "package:photos/ui/viewer/gallery/state/gallery_context_state.dart";
import 'package:photos/utils/file_util.dart';
+import "package:photos/utils/standalone/task_queue.dart";
import 'package:photos/utils/thumbnail_util.dart';
class ThumbnailWidget extends StatefulWidget {
@@ -78,6 +81,8 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
ImageProvider? _imageProvider;
int? optimizedImageHeight;
int? optimizedImageWidth;
+ String? _localThumbnailQueueTaskId;
+ static const _maxLocalThumbnailRetries = 10;
@override
void initState() {
@@ -89,6 +94,13 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
void dispose() {
super.dispose();
Future.delayed(const Duration(milliseconds: 10), () {
+ if (!mounted && _localThumbnailQueueTaskId != null) {
+ if (widget.thumbnailSize == thumbnailLargeSize) {
+ largeLocalThumbnailQueue.removeTask(_localThumbnailQueueTaskId!);
+ } else if (widget.thumbnailSize == thumbnailSmallSize) {
+ smallLocalThumbnailQueue.removeTask(_localThumbnailQueueTaskId!);
+ }
+ }
// Cancel request only if the widget has been unmounted
if (!mounted && widget.file.isRemoteFile && !_hasLoadedThumbnail) {
removePendingGetThumbnailRequestIfAny(widget.file);
@@ -104,6 +116,18 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
}
}
+ static final smallLocalThumbnailQueue = TaskQueue<String>(
+ maxConcurrentTasks: 15,
+ taskTimeout: const Duration(minutes: 1),
+ maxQueueSize: 200,
+ );
+
+ static final largeLocalThumbnailQueue = TaskQueue<String>(
+ maxConcurrentTasks: 5,
+ taskTimeout: const Duration(minutes: 1),
+ maxQueueSize: 200,
+ );
+
///Assigned dimension will be the size of a grid item. The size will be
///assigned to the side which is smaller in dimension.
void assignOptimizedImageDimensions() {
@@ -244,10 +268,7 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
}
Future _getThumbnailFromDisk() async {
- return getThumbnailFromLocal(
- widget.file,
- size: widget.thumbnailSize,
- ).then((thumbData) async {
+ return _loadWithRetry().then((thumbData) async {
if (thumbData == null) {
if (widget.file.isUploaded) {
_logger.fine("Removing localID reference for " + widget.file.tag);
@@ -284,11 +305,76 @@ class _ThumbnailWidgetState extends State<ThumbnailWidget> {
thumbnailSmallSize,
);
}).catchError((e) {
- _logger.warning("Could not load image: ", e);
+ _logger.warning("Could not thumbnail from disk: ", e);
_errorLoadingLocalThumbnail = true;
});
}
+ Future<Uint8List?> _loadWithRetry() async {
+ int retryAttempts = 0;
+ while (retryAttempts <= _maxLocalThumbnailRetries) {
+ try {
+ return _getLocalThumbnailUsingHeapPriorityQueue();
+ } catch (e) {
+ // only retry for specific exceptions
+ if (e is! TaskQueueTimeoutException &&
+ e is! TaskQueueOverflowException &&
+ e is! TaskQueueCancelledException) {
+ rethrow;
+ }
+
+ retryAttempts++;
+ final backoff = Duration(
+ milliseconds: 100 * pow(2, retryAttempts).toInt(),
+ );
+ if (retryAttempts <= _maxLocalThumbnailRetries) {
+ _logger.warning(
+ "Error getting local thumbnail for ${widget.file.displayName}, retrying (attempt $retryAttempts) in $backoff ms",
+ e,
+ );
+ await Future.delayed(backoff); // Exponential backoff
+ } else {
+ rethrow;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ Future<Uint8List?> _getLocalThumbnailUsingHeapPriorityQueue() async {
+ final completer = Completer<Uint8List?>();
+
+ if (widget.thumbnailSize == thumbnailLargeSize) {
+ _localThumbnailQueueTaskId = [widget.file.localID!, "-large"].join();
+ await largeLocalThumbnailQueue.addTask(_localThumbnailQueueTaskId!,
+ () async {
+ final thumbnailBytes = await getThumbnailFromLocal(
+ widget.file,
+ size: widget.thumbnailSize,
+ );
+ completer.complete(thumbnailBytes);
+ });
+ } else if (widget.thumbnailSize == thumbnailSmallSize) {
+ _localThumbnailQueueTaskId = [widget.file.localID!, "-small"].join();
+ await smallLocalThumbnailQueue.addTask(_localThumbnailQueueTaskId!,
+ () async {
+ final thumbnailBytes = await getThumbnailFromLocal(
+ widget.file,
+ size: widget.thumbnailSize,
+ );
+ completer.complete(thumbnailBytes);
+ });
+ } else {
+ assert(false, "Invalid thumbnail size ${widget.thumbnailSize}");
+ _logger.severe(
+ "Invalid thumbnail size ${widget.thumbnailSize} for file ${widget.file.displayName}",
+ );
+ }
+
+ return completer.future;
+ }
+
void _loadNetworkImage() {
if (!_hasLoadedThumbnail &&
!_errorLoadingRemoteThumbnail &&
diff --git a/mobile/lib/utils/standalone/task_queue.dart b/mobile/lib/utils/standalone/task_queue.dart
new file mode 100644
index 0000000000..a5a5eb0dfb
--- /dev/null
+++ b/mobile/lib/utils/standalone/task_queue.dart
@@ -0,0 +1,270 @@
+import 'dart:async';
+
+import 'package:collection/collection.dart';
+
+/// Class to hold task information
+class _QueueItem<T> {
+ final T id;
+ final Future<void> Function() task;
+ final Completer<void> completer;
+ int lastUpdated;
+ int counter;
+
+ _QueueItem(this.id, this.task)
+ : lastUpdated = DateTime.now().millisecondsSinceEpoch,
+ counter = 1,
+ completer = Completer<void>();
+
+ void updateTimestamp() {
+ lastUpdated = DateTime.now().millisecondsSinceEpoch;
+ counter++;
+ }
+
+ bool isTimedOut(Duration timeout) {
+ return (DateTime.now().millisecondsSinceEpoch - lastUpdated) >
+ timeout.inMilliseconds;
+ }
+
+ Future<void> get future => completer.future;
+}
+
+/// Custom exception for task timeout
+class TaskQueueTimeoutException implements Exception {
+ final dynamic taskId;
+ final Duration timeout;
+
+ TaskQueueTimeoutException(this.taskId, this.timeout);
+
+ @override
+ String toString() =>
+ 'Task $taskId timed out after ${timeout.inSeconds} seconds';
+}
+
+/// Custom exception for task being discarded due to queue overflow
+class TaskQueueOverflowException implements Exception {
+ final dynamic taskId;
+
+ TaskQueueOverflowException(this.taskId);
+
+ @override
+ String toString() => 'Task $taskId was discarded due to queue overflow';
+}
+
+class TaskQueueCancelledException implements Exception {
+ final dynamic taskId;
+
+ TaskQueueCancelledException(this.taskId);
+
+ @override
+ String toString() => 'Task $taskId was cancelled';
+}
+
+/// A generic task queue that can manage tasks with priority, cancellation, and timeout functionality.
+class TaskQueue<T> {
+ /// Maximum number of tasks that can run concurrently
+ final int maxConcurrentTasks;
+
+ /// Timeout duration after which a task is considered stale
+ final Duration taskTimeout;
+
+ /// Maximum size of the queue before older tasks are discarded
+ final int maxQueueSize;
+
+ /// Map to store tasks for quick lookup by ID
+ final _taskMap = <T, _QueueItem>{};
+
+ /// Priority queue to sort tasks by timestamp (most recent first)
+ final HeapPriorityQueue<_QueueItem> _priorityQueue;
+
+ /// Set of currently running task ids
+ final _runningTasks = <T>{};
+
+ /// Constructor
+ TaskQueue({
+ this.maxConcurrentTasks = 1,
+ this.taskTimeout = const Duration(minutes: 5),
+ this.maxQueueSize = 100,
+ }) : _priorityQueue = HeapPriorityQueue<_QueueItem>(
+ (a, b) => b.lastUpdated.compareTo(a.lastUpdated),
+ ); // Reversed for most recent first
+
+ /// Add or update a task in the queue
+ Future<void> addTask(T id, Future<void> Function() task) {
+ // If the task is already in the queue, update its timestamp to increase priority
+ if (_taskMap.containsKey(id)) {
+ final item = _taskMap[id]!;
+
+ // We need to remove and re-add to the priority queue to update its position
+ _priorityQueue.remove(item);
+ item.updateTimestamp();
+ _priorityQueue.add(item);
+
+ return item.future;
+ } else {
+ // Check if we need to make room in the queue
+ _enforceQueueSizeLimit();
+
+ // Add new task to the queue
+ final queueItem = _QueueItem(id, task);
+ _taskMap[id] = queueItem;
+ _priorityQueue.add(queueItem);
+
+ // Try to process tasks
+ _processQueue();
+
+ return queueItem.future;
+ }
+ }
+
+ /// Enforce the maximum queue size by discarding older tasks
+ void _enforceQueueSizeLimit() {
+ // If we're under the limit, no action needed
+ if (_taskMap.length < maxQueueSize) {
+ return;
+ }
+
+ // Create a temporary queue to find oldest items
+ // We need this because our main queue is ordered by most recent first
+ final tempQueue = PriorityQueue<_QueueItem>(
+ (a, b) => a.lastUpdated.compareTo(b.lastUpdated),
+ ); // Oldest first
+
+ // Add all items to the temporary queue
+ for (var item in _taskMap.values) {
+ tempQueue.add(item);
+ }
+
+ // Calculate how many items we need to remove
+ final excessItems =
+ _taskMap.length - maxQueueSize + 1; // +1 to make room for the new item
+
+ // Remove the oldest items
+ for (var i = 0; i < excessItems && tempQueue.isNotEmpty; i++) {
+ final oldestItem = tempQueue.removeFirst();
+ _priorityQueue.remove(oldestItem);
+ _taskMap.remove(oldestItem.id);
+
+ // Complete with overflow error
+ if (!oldestItem.completer.isCompleted) {
+ oldestItem.completer
+ .completeError(TaskQueueOverflowException(oldestItem.id));
+ }
+ }
+ }
+
+ /// Remove a task from the queue by its ID
+ bool removeTask(T id) {
+ // Can only remove tasks that aren't already running
+ if (_runningTasks.contains(id)) {
+ return false;
+ }
+
+ if (_taskMap.containsKey(id)) {
+ final item = _taskMap[id]!;
+ item.counter--;
+ if (item.counter > 0) {
+ return false;
+ }
+ _priorityQueue.remove(item);
+ // Complete the future with a cancellation error
+ if (!item.completer.isCompleted) {
+ item.completer.completeError(TaskQueueCancelledException(id));
+ }
+
+ _taskMap.remove(id);
+ return true;
+ }
+
+ return false;
+ }
+
+ /// Get the number of tasks waiting in the queue
+ int get pendingTasksCount => _taskMap.length;
+
+ /// Get the number of currently running tasks
+ int get runningTasksCount => _runningTasks.length;
+
+ /// Process the queue and execute tasks if possible
+ void _processQueue() async {
+ // Remove timed out tasks
+ _removeTimedOutTasks();
+
+ // If we can't run more tasks, exit
+ if (_runningTasks.length >= maxConcurrentTasks || _priorityQueue.isEmpty) {
+ return;
+ }
+
+ // Get the highest priority task (most recent)
+ final queueItem = _priorityQueue.removeFirst();
+ final taskId = queueItem.id;
+
+ // Remove from the map
+ _taskMap.remove(taskId);
+
+ // Mark this task as running
+ _runningTasks.add(taskId);
+
+ try {
+ // Execute the task
+ await queueItem.task();
+ // Complete the future successfully
+ if (!queueItem.completer.isCompleted) {
+ queueItem.completer.complete();
+ }
+ } catch (e) {
+ // Complete the future with the error
+ if (!queueItem.completer.isCompleted) {
+ queueItem.completer.completeError(e);
+ }
+ print('Task error: $e');
+ } finally {
+ // Mark the task as completed
+ _runningTasks.remove(taskId);
+
+ // Process the next task in the queue
+ _processQueue();
+ }
+ }
+
+ /// Remove tasks that have timed out
+ void _removeTimedOutTasks() {
+ final timedOutIds = <T>[];
+
+ // First pass: identify timed out items
+ for (var entry in _taskMap.entries) {
+ if (entry.value.isTimedOut(taskTimeout)) {
+ timedOutIds.add(entry.key);
+ }
+ }
+ // Second pass: remove them and complete with timeout error
+ for (var id in timedOutIds) {
+ final item = _taskMap[id]!;
+ _priorityQueue.remove(item);
+
+ // Complete the future with a timeout error
+ if (!item.completer.isCompleted) {
+ item.completer
+ .completeError(TaskQueueTimeoutException(id, taskTimeout));
+ }
+
+ _taskMap.remove(id);
+ }
+ }
+
+ /// Clear all pending tasks
+ void clear() {
+ // Complete all pending tasks with cancellation errors
+ for (var entry in _taskMap.entries) {
+ if (!entry.value.completer.isCompleted) {
+ entry.value.completer.completeError(
+ Exception('Task ${entry.key} was cancelled during queue clear'),
+ );
+ }
+ }
+
+ while (_priorityQueue.isNotEmpty) {
+ _priorityQueue.removeFirst();
+ }
+ _taskMap.clear();
+ }
+}