π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mobile][photos] Prioritize foreground over background ML
laurenspriem33ae187d6810
diff --git a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/ForegroundHeartbeat.kt b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/ForegroundHeartbeat.ktnew file mode 100644index 0000000000..371517dada--- /dev/null+++ b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/ForegroundHeartbeat.kt@@ -0,0 +1,92 @@+package io.ente.photos++import android.content.Context+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import io.flutter.embedding.android.FlutterFragmentActivity++abstract class ForegroundHeartbeatActivity : FlutterFragmentActivity() {+ private val foregroundHeartbeat = ForegroundHeartbeat(this)++ override fun onCreate(savedInstanceState: Bundle?) {+ foregroundHeartbeat.start()+ super.onCreate(savedInstanceState)+ }++ override fun onStart() {+ super.onStart()+ foregroundHeartbeat.start()+ }++ override fun onStop() {+ foregroundHeartbeat.stop()+ super.onStop()+ }++ override fun onDestroy() {+ foregroundHeartbeat.stop()+ super.onDestroy()+ }+}++private class ForegroundHeartbeat(private val context: Context) {+ private val handler = Handler(Looper.getMainLooper())+ private val preferences by lazy {+ context.getSharedPreferences(+ EnteApplication.FLUTTER_SHARED_PREFERENCES,+ Context.MODE_PRIVATE+ )+ }+ private var nativeHeartbeatStartedAt = 0L+ private var isRunning = false+ private val heartbeat =+ object : Runnable {+ override fun run() {+ if (!isRunning) {+ return+ }+ if (hasDartHeartbeatTakenOver()) {+ isRunning = false+ return+ }+ writeNativeHeartbeat()+ handler.postDelayed(this, HEARTBEAT_INTERVAL_MS)+ }+ }++ fun start() {+ if (isRunning) {+ return+ }+ isRunning = true+ nativeHeartbeatStartedAt = currentTimeInMicroseconds()+ writeNativeHeartbeat(nativeHeartbeatStartedAt)+ handler.postDelayed(heartbeat, HEARTBEAT_INTERVAL_MS)+ }++ fun stop() {+ isRunning = false+ handler.removeCallbacks(heartbeat)+ }++ private fun hasDartHeartbeatTakenOver(): Boolean {+ val dartHeartbeat =+ preferences.getLong(DART_FOREGROUND_HEARTBEAT_KEY, 0L)+ return dartHeartbeat >= nativeHeartbeatStartedAt+ }++ private fun writeNativeHeartbeat(heartbeat: Long = currentTimeInMicroseconds()) {+ preferences.edit()+ .putLong(NATIVE_FOREGROUND_HEARTBEAT_KEY, heartbeat)+ .apply()+ }++ private fun currentTimeInMicroseconds() = System.currentTimeMillis() * 1000L++ private companion object {+ const val DART_FOREGROUND_HEARTBEAT_KEY = "flutter.fg_task_hb_time"+ const val NATIVE_FOREGROUND_HEARTBEAT_KEY = "flutter.native_fg_task_hb_time"+ const val HEARTBEAT_INTERVAL_MS = 1000L+ }+}diff --git a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.ktindex 7422f67826..0c80134840 100644--- a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt+++ b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MainActivity.kt@@ -1,9 +1,8 @@package io.ente.photosimport android.content.Intent-import io.flutter.embedding.android.FlutterFragmentActivity-class MainActivity : FlutterFragmentActivity() {+class MainActivity : ForegroundHeartbeatActivity() {override fun onNewIntent(intent: Intent) {setIntent(intent)super.onNewIntent(intent)diff --git a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MediaPickerActivity.kt b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MediaPickerActivity.ktindex 6f549c179b..e7da2ea490 100644--- a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MediaPickerActivity.kt+++ b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/MediaPickerActivity.kt@@ -2,9 +2,8 @@ package io.ente.photosimport android.content.Intentimport android.os.Bundle-import io.flutter.embedding.android.FlutterFragmentActivity-class MediaPickerActivity : FlutterFragmentActivity() {+class MediaPickerActivity : ForegroundHeartbeatActivity() {override fun onCreate(savedInstanceState: Bundle?) {normalizePickerIntent(intent)super.onCreate(savedInstanceState)diff --git a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxprojindex d8c9f0b476..1f5453d1d3 100644--- a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj+++ b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj@@ -14,6 +14,7 @@359D8BCF50FB143064FFC56F /* Pods_ShareExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D025F2F5A163F84B724D14D7 /* Pods_ShareExtension.framework */; };3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };54D121F62F02675C00B8CC69 /* ShareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 54D121EC2F02675C00B8CC69 /* ShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };+ 6DA601B38B4BCCD1C4BB0E25 /* ForegroundHeartbeat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EEDBC4E19D917C19BF4545 /* ForegroundHeartbeat.swift */; };74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };@@ -97,6 +98,7 @@3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };53DBFBDBE805FC6E13E3F31E /* Pods-ShareExtension.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ShareExtension.debug.xcconfig"; path = "Target Support Files/Pods-ShareExtension/Pods-ShareExtension.debug.xcconfig"; sourceTree = "<group>"; };54D121EC2F02675C00B8CC69 /* ShareExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = ShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };+ 57EEDBC4E19D917C19BF4545 /* ForegroundHeartbeat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForegroundHeartbeat.swift; sourceTree = "<group>"; };6A1E2DBA51995DADEC1ED952 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };6DACD83C2B755B0600BA9516 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };6DACD83E2B755B0600BA9516 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };@@ -312,6 +314,7 @@1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,74858FAE1ED2DC5600515810 /* AppDelegate.swift */,+ 57EEDBC4E19D917C19BF4545 /* ForegroundHeartbeat.swift */,74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,);path = Runner;@@ -867,6 +870,7 @@buildActionMask = 2147483647;files = (74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,+ 6DA601B38B4BCCD1C4BB0E25 /* ForegroundHeartbeat.swift in Sources */,1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,);runOnlyForDeploymentPostprocessing = 0;diff --git a/mobile/apps/photos/ios/Runner/AppDelegate.swift b/mobile/apps/photos/ios/Runner/AppDelegate.swiftindex 3a26fe44e7..2dc5853358 100644--- a/mobile/apps/photos/ios/Runner/AppDelegate.swift+++ b/mobile/apps/photos/ios/Runner/AppDelegate.swift@@ -9,6 +9,7 @@ import workmanager_apple@objc class AppDelegate: FlutterAppDelegate {private static let workmanagerDebugThreadIdentifier ="io.ente.frame.workmanager.debug"+ private let foregroundHeartbeat = ForegroundHeartbeat()override func application(_ application: UIApplication,@@ -82,13 +83,20 @@ import workmanager_apple}override func applicationDidBecomeActive(_ application: UIApplication) {+ foregroundHeartbeat.start()signal(SIGPIPE, SIG_IGN)}override func applicationWillEnterForeground(_ application: UIApplication) {+ foregroundHeartbeat.start()signal(SIGPIPE, SIG_IGN)}+ override func applicationDidEnterBackground(_ application: UIApplication) {+ foregroundHeartbeat.stop()+ super.applicationDidEnterBackground(application)+ }+override func userNotificationCenter(_ center: UNUserNotificationCenter,willPresent notification: UNNotification,diff --git a/mobile/apps/photos/ios/Runner/ForegroundHeartbeat.swift b/mobile/apps/photos/ios/Runner/ForegroundHeartbeat.swiftnew file mode 100644index 0000000000..bdd6051daf--- /dev/null+++ b/mobile/apps/photos/ios/Runner/ForegroundHeartbeat.swift@@ -0,0 +1,53 @@+import Foundation++final class ForegroundHeartbeat {+ private let defaults = UserDefaults.standard+ private var timer: Timer?+ private var nativeHeartbeatStartedAt: Int64 = 0++ func start() {+ guard timer == nil else {+ return+ }++ nativeHeartbeatStartedAt = currentTimeInMicroseconds()+ writeNativeHeartbeat(nativeHeartbeatStartedAt)++ let timer = Timer(timeInterval: heartbeatInterval, repeats: true) { [weak self] _ in+ self?.heartbeatTimerFired()+ }+ self.timer = timer+ RunLoop.main.add(timer, forMode: .common)+ }++ func stop() {+ timer?.invalidate()+ timer = nil+ }++ private func heartbeatTimerFired() {+ if hasDartHeartbeatTakenOver() {+ stop()+ return+ }+ writeNativeHeartbeat(currentTimeInMicroseconds())+ }++ private func hasDartHeartbeatTakenOver() -> Bool {+ let dartHeartbeat =+ (defaults.object(forKey: dartForegroundHeartbeatKey) as? NSNumber)?.int64Value ?? 0+ return dartHeartbeat >= nativeHeartbeatStartedAt+ }++ private func writeNativeHeartbeat(_ heartbeat: Int64) {+ defaults.set(heartbeat, forKey: nativeForegroundHeartbeatKey)+ }++ private func currentTimeInMicroseconds() -> Int64 {+ Int64(Date().timeIntervalSince1970 * 1_000_000)+ }++ private let dartForegroundHeartbeatKey = "flutter.fg_task_hb_time"+ private let nativeForegroundHeartbeatKey = "flutter.native_fg_task_hb_time"+ private let heartbeatInterval: TimeInterval = 1+}diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dartindex cda1896dda..f350e373b8 100644--- a/mobile/apps/photos/lib/main.dart+++ b/mobile/apps/photos/lib/main.dart@@ -351,13 +351,23 @@ Future<void> _runMinimally();} else {try {- await MLService.instance.init();- PersonService.init(entityService, MLDataDB.instance, prefs);- final disposition = await MLService.instance.runAllML(- force: false,- control: mlRunControl,- );- _logger.info("[BG TASK] ML run disposition: ${disposition.name}");+ if (await isForegroundEngineActive()) {+ _logger.info("[BG TASK] skipping ML, foreground became active");+ } else {+ await MLService.instance.init();+ if (await isForegroundEngineActive()) {+ _logger.info(+ "[BG TASK] skipping ML run, foreground became active during ML init",+ );+ } else {+ PersonService.init(entityService, MLDataDB.instance, prefs);+ final disposition = await MLService.instance.runAllML(+ force: false,+ control: mlRunControl,+ );+ _logger.info("[BG TASK] ML run disposition: ${disposition.name}");+ }+ }} finally {controller.releaseCompute(ml: true);}@@ -631,14 +641,20 @@ Future<void> _sync(String caller) async {}}-Future runWithLogs(Function() function, {String prefix = ""}) async {+Future runWithLogs(+ Function() function, {+ String prefix = "",+ bool enableSentry = true,+}) async {await SuperLogging.main(LogConfig(body: function,logDirPath: (await getApplicationSupportDirectory()).path + "/logs",maxLogFiles: 5,- sentryDsn: kDebugMode ? sentryDebugDSN : sentryDSN,- tunnel: sentryTunnel,+ sentryDsn: enableSentry+ ? (kDebugMode ? sentryDebugDSN : sentryDSN)+ : null,+ tunnel: enableSentry ? sentryTunnel : null,enableInDebugMode: true,prefix: prefix,),diff --git a/mobile/apps/photos/lib/services/process_activity.dart b/mobile/apps/photos/lib/services/process_activity.dartindex efde5b60e1..1fb03a54ec 100644--- a/mobile/apps/photos/lib/services/process_activity.dart+++ b/mobile/apps/photos/lib/services/process_activity.dart@@ -2,19 +2,22 @@ import "package:shared_preferences/shared_preferences.dart";const kLastBGTaskHeartBeatTime = "bg_task_hb_time";const kLastFGTaskHeartBeatTime = "fg_task_hb_time";+const kLastNativeFGTaskHeartBeatTime = "native_fg_task_hb_time";const kEngineDeathTimeoutInMicroseconds = 5000000;// Heartbeats affect priority and yield latency, not correctness.Future<bool> isForegroundEngineActive() =>- _isEngineActive(kLastFGTaskHeartBeatTime);+ _isEngineActive([kLastFGTaskHeartBeatTime, kLastNativeFGTaskHeartBeatTime]);Future<bool> isBackgroundEngineActive() =>- _isEngineActive(kLastBGTaskHeartBeatTime);+ _isEngineActive([kLastBGTaskHeartBeatTime]);-Future<bool> _isEngineActive(String heartBeatKey) async {+Future<bool> _isEngineActive(List<String> heartBeatKeys) async {final prefs = await SharedPreferences.getInstance();await prefs.reload();final currentTime = DateTime.now().microsecondsSinceEpoch;- final lastHeartBeatTime = prefs.getInt(heartBeatKey) ?? 0;+ final lastHeartBeatTime = heartBeatKeys+ .map((key) => prefs.getInt(key) ?? 0)+ .reduce((latest, heartbeat) => latest > heartbeat ? latest : heartbeat);return lastHeartBeatTime > (currentTime - kEngineDeathTimeoutInMicroseconds);}diff --git a/mobile/apps/photos/lib/utils/bg_task_utils.dart b/mobile/apps/photos/lib/utils/bg_task_utils.dartindex 8842734f70..026133c443 100644--- a/mobile/apps/photos/lib/utils/bg_task_utils.dart+++ b/mobile/apps/photos/lib/utils/bg_task_utils.dart@@ -20,26 +20,30 @@ void callbackDispatcher() {String? failure = "Task didn't run";final prefs = await SharedPreferences.getInstance();- await runWithLogs(() async {- try {- BgTaskUtils.$.info('Task started $tlog');- await runBackgroundTask(taskName, tlog).timeout(- Platform.isIOS ? kBGTaskTimeout : const Duration(hours: 1),- onTimeout: () async {- BgTaskUtils.$.warning(- "TLE, committing seppuku for taskID: $taskName",- );- await BgTaskUtils.releaseResourcesForKill(taskName, prefs);- },- );- BgTaskUtils.$.info('Task run successful $tlog');- failure = null;- } catch (e) {- BgTaskUtils.$.warning('Task error: $e');- await BgTaskUtils.releaseResourcesForKill(taskName, prefs);- failure = e.toString();- }- }, prefix: "[bg]").onError((_, _) {+ await runWithLogs(+ () async {+ try {+ BgTaskUtils.$.info('Task started $tlog');+ await runBackgroundTask(taskName, tlog).timeout(+ Platform.isIOS ? kBGTaskTimeout : const Duration(hours: 1),+ onTimeout: () async {+ BgTaskUtils.$.warning(+ "TLE, committing seppuku for taskID: $taskName",+ );+ await BgTaskUtils.releaseResourcesForKill(taskName, prefs);+ },+ );+ BgTaskUtils.$.info('Task run successful $tlog');+ failure = null;+ } catch (e) {+ BgTaskUtils.$.warning('Task error: $e');+ await BgTaskUtils.releaseResourcesForKill(taskName, prefs);+ failure = e.toString();+ }+ },+ prefix: "[bg]",+ enableSentry: !Platform.isAndroid,+ ).onError((_, _) {failure = "Didn't finished correctly!";return;});