π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mobile] Clean up resources after native background work
laurenspriemffe197604a80
diff --git a/mobile/apps/photos/lib/db/common/base.dart b/mobile/apps/photos/lib/db/common/base.dartindex b2bc8a2d58..86b42f48a6 100644--- a/mobile/apps/photos/lib/db/common/base.dart+++ b/mobile/apps/photos/lib/db/common/base.dart@@ -15,9 +15,29 @@ class DatabaseDowngradeError extends Error {mixin SqlDbBase {static final Map<int, String> _params = <int, String>{};+ static final _openDatabases = <SqlDbBase>{};Future<SqliteDatabase>? _dbFuture;+ static Future<void> closeAll() async {+ await Future.wait(+ _openDatabases.toList().map((database) => database._close()),+ );+ }++ Future<void> _close() async {+ final future = _dbFuture;+ if (future == null) return;+ try {+ await (await future).close();+ } finally {+ if (identical(_dbFuture, future)) {+ _dbFuture = null;+ _openDatabases.remove(this);+ }+ }+ }+static String getParams(int count) {if (count <= 0) {throw ArgumentError.value(count, "count", "must be greater than 0");@@ -30,7 +50,9 @@ mixin SqlDbBase {) async {final future = _dbFuture ??= openDatabase();try {- return await future;+ final database = await future;+ _openDatabases.add(this);+ return database;} catch (e) {if (e is! DatabaseDowngradeError && identical(_dbFuture, future)) {_dbFuture = null;diff --git a/mobile/apps/photos/lib/db/offline_files_db.dart b/mobile/apps/photos/lib/db/offline_files_db.dartindex e5d0c13c8e..1aa7aafdf8 100644--- a/mobile/apps/photos/lib/db/offline_files_db.dart+++ b/mobile/apps/photos/lib/db/offline_files_db.dart@@ -1,6 +1,4 @@import "package:logging/logging.dart";-import "package:path/path.dart" show join;-import "package:path_provider/path_provider.dart";import "package:photos/db/common/base.dart";import "package:photos/db/ml/schema.dart";import "package:sqlite_async/sqlite_async.dart";@@ -17,26 +15,16 @@ class OfflineFilesDB with SqlDbBase {static const List<String> _migrationScripts = [createOfflineFileKeyMapTable];- Future<SqliteDatabase>? _sqliteAsyncDBFuture;+ Future<SqliteDatabase> get asyncDB =>+ getOrOpenDatabase(_initSqliteAsyncDatabase);- Future<SqliteDatabase> get asyncDB async {- _sqliteAsyncDBFuture ??= _initSqliteAsyncDatabase();- return _sqliteAsyncDBFuture!;- }-- Future<SqliteDatabase> _initSqliteAsyncDatabase() async {- final documentsDirectory = await getApplicationDocumentsDirectory();- final String databaseDirectory = join(- documentsDirectory.path,+ Future<SqliteDatabase> _initSqliteAsyncDatabase() {+ return openMigratedDatabase(_databaseName,- );- _logger.info("Opening offline files DB at $databaseDirectory");- final asyncDBConnection = SqliteDatabase(- path: databaseDirectory,+ _migrationScripts,maxReaders: 2,+ logPath: (path) => _logger.info("Opening offline files DB at $path"),);- await migrate(asyncDBConnection, _migrationScripts);- return asyncDBConnection;}Future<int> getOrCreateLocalIntId(String localId) async {diff --git a/mobile/apps/photos/lib/utils/background_tasks.dart b/mobile/apps/photos/lib/utils/background_tasks.dartindex becc6b0ca7..ca3819f7f4 100644--- a/mobile/apps/photos/lib/utils/background_tasks.dart+++ b/mobile/apps/photos/lib/utils/background_tasks.dart@@ -10,6 +10,7 @@ import "package:flutter/foundation.dart";import "package:flutter/widgets.dart" show AppLifecycleState, WidgetsBinding;import "package:logging/logging.dart";import "package:permission_handler/permission_handler.dart";+import "package:photos/db/common/base.dart";import "package:photos/db/upload_locks_db.dart";import "package:photos/main.dart";import "package:photos/module/upload/service/file_uploader.dart";@@ -17,6 +18,7 @@ import "package:photos/services/machine_learning/ml_run_control.dart";import "package:photos/services/notification_service.dart";import "package:photos/settings/local_settings.dart";import "package:photos/utils/bg_task_utils.dart";+import "package:photos/utils/isolate/super_isolate.dart";import "package:shared_preferences/shared_preferences.dart";import "package:workmanager/workmanager.dart" as legacy;@@ -281,19 +283,28 @@ class BackgroundTasks {final remainingBudget =BgTaskUtils.taskTimeoutFor(taskName) - task.elapsed;await runBackgroundTask(- taskName,- TimeLogger(),- control: control,- shouldStop: () => timedOut || task.isStopping,- mlSelfStop: BgTaskUtils.mlSelfStopFor(taskName) - task.elapsed,- mlLockWait: BgTaskUtils.mlLockWaitFor(taskName),- ).timeout(- remainingBudget.isNegative ? Duration.zero : remainingBudget,- onTimeout: () {- timedOut = true;- throw TimeoutException("Background task timed out");- },- );+ taskName,+ TimeLogger(),+ control: control,+ shouldStop: () => timedOut || task.isStopping,+ mlSelfStop:+ BgTaskUtils.mlSelfStopFor(taskName) - task.elapsed,+ mlLockWait: BgTaskUtils.mlLockWaitFor(taskName),+ )+ .whenComplete(() async {+ try {+ await SuperIsolate.disposeAll();+ } finally {+ await SqlDbBase.closeAll();+ }+ })+ .timeout(+ remainingBudget.isNegative ? Duration.zero : remainingBudget,+ onTimeout: () {+ timedOut = true;+ throw TimeoutException("Background task timed out");+ },+ );result = task.isStopping? BackgroundTaskResult.stopped: BackgroundTaskResult.completed;diff --git a/mobile/apps/photos/lib/utils/isolate/super_isolate.dart b/mobile/apps/photos/lib/utils/isolate/super_isolate.dartindex a7b8d83c2d..ac1812cff0 100644--- a/mobile/apps/photos/lib/utils/isolate/super_isolate.dart+++ b/mobile/apps/photos/lib/utils/isolate/super_isolate.dart@@ -11,6 +11,8 @@ import "package:synchronized/synchronized.dart";@pragma('vm:entry-point')abstract class SuperIsolate {+ static final _spawnedIsolates = <SuperIsolate>{};+Logger get logger;Timer? _inactivityTimer;@@ -29,6 +31,13 @@ abstract class SuperIsolate {bool get isIsolateSpawned => _isIsolateSpawned;bool _isIsolateSpawned = false;+ Future<void>? _disposeFuture;++ static Future<void> disposeAll() async {+ await Future.wait(+ _spawnedIsolates.toList().map((isolate) => isolate._disposeIsolate()),+ );+ }Future<void> _initIsolate() async {return _initIsolateLock.synchronized(() async {@@ -52,6 +61,7 @@ abstract class SuperIsolate {if (shouldAutomaticDispose) _resetInactivityTimer();logger.info('initIsolate done');_isIsolateSpawned = true;+ _spawnedIsolates.add(this);} catch (e) {logger.severe('Could not spawn isolate', e);_isIsolateSpawned = false;@@ -172,14 +182,24 @@ abstract class SuperIsolate {Future<void> onDispose() async {}- void _disposeIsolate() async {+ Future<void> _disposeIsolate() {+ return _disposeFuture ??= _dispose().whenComplete(() {+ _disposeFuture = null;+ });+ }++ Future<void> _dispose() async {if (!_isIsolateSpawned) return;logger.info('Disposing isolate');- await onDispose();- await clearAllCachedData();- _isIsolateSpawned = false;- _isolate.kill();- _receivePort.close();- _inactivityTimer?.cancel();+ try {+ await onDispose();+ await clearAllCachedData();+ } finally {+ _isIsolateSpawned = false;+ _isolate.kill();+ _receivePort.close();+ _inactivityTimer?.cancel();+ _spawnedIsolates.remove(this);+ }}}