Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mobile] Bound upload URL tracking

Neeraj Gupta51e1077b1615
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 d3baa0107c..ebbf9fb203 100644
--- a/mobile/apps/photos/lib/module/upload/service/file_uploader.dart
+++ b/mobile/apps/photos/lib/module/upload/service/file_uploader.dart
@@ -135,7 +135,6 @@ class FileUploader {
clearQueue: clearQueue,
);
_multiPartUploader = MultiPartUploader(
- _dio, // legacy parameter, not used by MultiPartUploader
_dio,
UploadLocksDB.instance,
flagService,
diff --git a/mobile/apps/photos/lib/module/upload/service/multipart.dart b/mobile/apps/photos/lib/module/upload/service/multipart.dart
index 991e4bcaf4..bb168b6946 100644
--- a/mobile/apps/photos/lib/module/upload/service/multipart.dart
+++ b/mobile/apps/photos/lib/module/upload/service/multipart.dart
@@ -22,12 +22,7 @@ class MultiPartUploader {
late final Logger _logger = Logger("MultiPartUploader");
FileUploadGateway get _gateway => fileUploadGateway;
- MultiPartUploader(
- Dio _, // unused, kept for backwards compatibility
- this._s3Dio,
- this._db,
- this._featureFlagService,
- );
+ MultiPartUploader(this._s3Dio, this._db, this._featureFlagService);
Future<FileEncryptResult> getEncryptionResult(
String localId,
diff --git a/mobile/apps/photos/lib/module/upload/service/upload_transport.dart b/mobile/apps/photos/lib/module/upload/service/upload_transport.dart
index 73030e7619..9677fa6941 100644
--- a/mobile/apps/photos/lib/module/upload/service/upload_transport.dart
+++ b/mobile/apps/photos/lib/module/upload/service/upload_transport.dart
@@ -3,6 +3,7 @@ import "dart:io";
import "package:dio/dio.dart";
import "package:ente_pure_utils/ente_pure_utils.dart";
+import "package:flutter/foundation.dart";
import "package:logging/logging.dart";
import "package:path/path.dart";
import "package:photos/core/constants.dart";
@@ -54,6 +55,9 @@ class UploadTransport {
static const maximumAttempts = 4;
static const apiRetryDelay = Duration(seconds: 3);
+ static const _maximumRecentUploadURLs = 5000;
+ static const _uploadURLRetention = Duration(hours: 1);
+ static const _uploadURLCleanupInterval = Duration(minutes: 5);
final _logger = Logger("UploadTransport");
final Dio _dio;
@@ -64,8 +68,17 @@ class UploadTransport {
final UploadClock _clock;
final Md5Computer _recomputeMd5;
final Map<String, DateTime> _usedUploadURLs = {};
+ DateTime? _nextUploadURLCleanupAt;
+ int _uploadURLCleanupEntryChecks = 0;
- void clearCachedUploadURLs() => _usedUploadURLs.clear();
+ @visibleForTesting
+ int get uploadURLCleanupEntryChecks => _uploadURLCleanupEntryChecks;
+
+ void clearCachedUploadURLs() {
+ _usedUploadURLs.clear();
+ _nextUploadURLCleanupAt = null;
+ _uploadURLCleanupEntryChecks = 0;
+ }
Future<String> uploadSinglePart(
File file,
@@ -136,24 +149,42 @@ class UploadTransport {
UploadURL _registerUploadURLUsage(UploadURL uploadURL) {
final now = _clock();
- final existingTimestamp = _usedUploadURLs.putIfAbsent(
- uploadURL.url,
- () => now,
- );
- if (existingTimestamp != now) {
+ final existingTimestamp = _usedUploadURLs[uploadURL.url];
+ if (existingTimestamp != null) {
throw DuplicateUploadURLError(
firstUsedAt: existingTimestamp,
duplicateUsedAt: now,
);
}
- if (_usedUploadURLs.length > 5000) {
- final oneHourAgo = now.subtract(const Duration(hours: 1));
- _usedUploadURLs.removeWhere((key, value) => value.isBefore(oneHourAgo));
+
+ _usedUploadURLs[uploadURL.url] = now;
+ _cleanUsedUploadURLsIfDue(now);
+ return uploadURL;
+ }
+
+ void _cleanUsedUploadURLsIfDue(DateTime now) {
+ if (_usedUploadURLs.length <= _maximumRecentUploadURLs ||
+ (_nextUploadURLCleanupAt?.isAfter(now) ?? false)) {
+ return;
+ }
+
+ final oldestRetainedAt = now.subtract(_uploadURLRetention);
+ var removedCount = 0;
+ _usedUploadURLs.removeWhere((key, usedAt) {
+ _uploadURLCleanupEntryChecks++;
+ final shouldRemove = usedAt.isBefore(oldestRetainedAt);
+ if (shouldRemove) {
+ removedCount++;
+ }
+ return shouldRemove;
+ });
+ _nextUploadURLCleanupAt = now.add(_uploadURLCleanupInterval);
+ if (removedCount > 0) {
_logger.info(
- "Cleaned up used upload URLs, remaining: ${_usedUploadURLs.length}",
+ "Removed $removedCount expired upload URLs, "
+ "remaining: ${_usedUploadURLs.length}",
);
}
- return uploadURL;
}
Future<String> _putFile(
diff --git a/mobile/apps/photos/test/module/upload/service/upload_transport_test.dart b/mobile/apps/photos/test/module/upload/service/upload_transport_test.dart
index 4d60f9fd91..2ecf4bcebd 100644
--- a/mobile/apps/photos/test/module/upload/service/upload_transport_test.dart
+++ b/mobile/apps/photos/test/module/upload/service/upload_transport_test.dart
@@ -59,6 +59,62 @@ void main() {
);
});
+ test("rejects duplicate URLs with identical timestamps", () async {
+ final clock = _FixedRegistrationClock();
+ final fixture = _Fixture(uploadClock: clock.call);
+ fixture.gateway.uploadURLs.addAll([
+ UploadURL("same-url", "first"),
+ UploadURL("same-url", "second"),
+ ]);
+
+ expect(
+ await fixture.transport.uploadSinglePart(file, 4, contentMd5: "md5"),
+ "first",
+ );
+ await expectLater(
+ fixture.transport.uploadSinglePart(file, 4, contentMd5: "md5"),
+ throwsA(isA<DuplicateUploadURLError>()),
+ );
+ });
+
+ test("10000 URLs keep cleanup work linear and expire old entries", () async {
+ final clock = _FixedRegistrationClock();
+ final fixture = _Fixture(uploadClock: clock.call);
+ fixture.gateway.uploadURLs.addAll(
+ List.generate(10000, (index) => UploadURL("url-$index", "key-$index")),
+ );
+
+ String? lastObjectKey;
+ for (var index = 0; index < 10000; index++) {
+ lastObjectKey = await fixture.transport.uploadSinglePart(
+ file,
+ 4,
+ contentMd5: "md5-$index",
+ );
+ }
+
+ expect(lastObjectKey, "key-9999");
+ expect(fixture.transport.uploadURLCleanupEntryChecks, 5001);
+
+ clock.advance(const Duration(hours: 1, seconds: 1));
+ fixture.gateway.uploadURLs.addAll([
+ UploadURL("cleanup-trigger", "trigger-key"),
+ UploadURL("url-0", "reused-key"),
+ ]);
+ expect(
+ await fixture.transport.uploadSinglePart(file, 4, contentMd5: "trigger"),
+ "trigger-key",
+ );
+ expect(
+ await fixture.transport.uploadSinglePart(file, 4, contentMd5: "reused"),
+ "reused-key",
+ );
+
+ expect(fixture.transport.uploadURLCleanupEntryChecks, 15002);
+ expect(fixture.gateway.uploadURLRequests, hasLength(10002));
+ expect(fixture.dio.putPaths, hasLength(10002));
+ });
+
test("maps upload URL 402 and 426 responses and clears the queue", () async {
for (final statusCode in [402, 426]) {
final fixture = _Fixture();
@@ -556,14 +612,14 @@ const _expectedUpdateRequest = <String, dynamic>{
};
class _Fixture {
- _Fixture({String recomputedMd5 = "recomputed"}) {
+ _Fixture({String recomputedMd5 = "recomputed", UploadClock? uploadClock}) {
transport = UploadTransport(
dio,
gateway,
shouldUseUploadProxy: () => useProxy,
clearQueue: clearedErrors.add,
delay: (duration) async => delays.add(duration),
- clock: clock.call,
+ clock: uploadClock ?? clock.call,
recomputeMd5: (path) async {
recomputedPaths.add(path);
return recomputedMd5;
@@ -590,6 +646,20 @@ class _Clock {
}
}
+class _FixedRegistrationClock {
+ var _value = DateTime.utc(2026);
+ var _calls = 0;
+
+ void advance(Duration duration) {
+ _value = _value.add(duration);
+ }
+
+ DateTime call() {
+ final phase = _calls++ % 3;
+ return phase == 2 ? _value.add(const Duration(milliseconds: 1)) : _value;
+ }
+}
+
class _FakeDio extends Fake implements Dio {
final putFailures = Queue<DioException>();
final putPaths = <String>[];