π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Merge upstream/main into ml_fg_bg_lock
laurenspriemc0d6ca07a7f2
diff --cc mobile/apps/photos/lib/services/machine_learning/ml_service.dartindex 72d70488aa,7808798ed9..53d7c531e2--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart@@@ -348,101 -352,33 +348,101 @@@ class MLServiceFuture<void> sync() async {await fileDataService.syncFDStatus();- await personFeedbackService.syncPersonFeedback();+ await PersonService.instance.sync();}- Future<void> runAllML({bool force = false}) async {+ Future<MlRunDisposition> runAllML({+ bool force = false,+ MlRunControl? control,+ }) async {+ final runControl = control ?? MlRunControl();+ // A latched stop always wins, force included.+ if (runControl.stopRequested) {+ _logger.info(+ "runAllML skipped, stop already requested "+ "(${runControl.stopReason?.name})",+ );+ return MlRunDisposition.stopped;+ }if (_isRunningML) {_logger.info("runAllML called while already running, skipping");- return;+ return MlRunDisposition.denied;}+ if (!hasGrantedMLConsent) {+ _logger.info("runAllML called without ML consent, skipping");+ return MlRunDisposition.denied;+ }+ final MLMode mode = isLocalGalleryMode+ ? MLMode.localGallery+ : MLMode.enteGallery;+ final mlDataDB = _dbForMode(mode);+ if (force) {+ _mlControllerStatus = true;+ }+ if (!_canRunMLFunction(function: "AllML") && !force) {+ return MlRunDisposition.denied;+ }+ if (!force && !computeController.requestCompute(ml: true)) {+ return MlRunDisposition.denied;+ }+ var disposition = MlRunDisposition.completed;try {- if (!hasGrantedMLConsent) {- _logger.info("runAllML called without ML consent, skipping");- return;- }- final MLMode mode = isLocalGalleryMode- ? MLMode.localGallery- : MLMode.enteGallery;- final mlDataDB = _dbForMode(mode);- if (force) {- _mlControllerStatus = true;+ final attempt = await MlProcessLock.instance.tryRunExclusive(+ MlOperation.fullRun,+ () async {+ disposition = await _runAllMLProtected(+ mode: mode,+ mlDataDB: mlDataDB,+ force: force,+ control: runControl,+ );+ },+ background: isProcessBg,+ );+ if (attempt != MlLockAttempt.ran) {+ _logger.info("runAllML denied the ml process lock (${attempt.name})");+ disposition = MlRunDisposition.denied;+ _scheduleDeniedRunRetry();}- if (!_canRunMLFunction(function: "AllML") && !force) return;- if (!force && !computeController.requestCompute(ml: true)) return;- _isRunningML = true;+ } catch (e, s) {+ _logger.severe("runAllML failed", e, s);+ disposition = MlRunDisposition.failed;+ } finally {+ computeController.releaseCompute(ml: true);+ }+ return disposition;+ }++ // FG-only: one coalesced retry after a lock denial, because the natural+ // ComputeControlEvent re-trigger only fires on an interaction or health+ // transition β without this, an untouched device would stall until the+ // next user interaction. Preconditions are re-validated when it fires.+ void _scheduleDeniedRunRetry() {+ if (isProcessBg) return;+ if (_deniedRunRetryTimer != null) return;+ _deniedRunRetryTimer = Timer(_kDeniedRunRetryDelay, () {+ _deniedRunRetryTimer = null;+ if (!hasGrantedMLConsent) return;+ triggerML();+ });+ }++ Future<MlRunDisposition> _runAllMLProtected({+ required MLMode mode,+ required MLDataDB mlDataDB,+ required bool force,+ required MlRunControl control,+ }) async {+ assert(MlProcessLock.instance.isBusy, "ml funnel must be held");+ _installRunControl(control);+ try {await sync();+ if (control.stopRequested) {+ return _stoppedDisposition(control, "after sync");+ }if (_hasModeChanged(mode)) {_logger.info("App mode changed during ML run, stopping");- return;+ return MlRunDisposition.stopped;}final int unclusteredFacesCount = await mlDataDBdiff --cc mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dartindex cb0b9826ff,2e82303a88..339ad05f69--- a/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart+++ b/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart@@@ -802,26 -789,9 +802,26 @@@ class _MLDebugSettingsPageState extend}}+ Future<void> _onShowProcessLockState(BuildContext context) async {+ try {+ final owner = await ProcessLockClient.instance.state(name: "ml");+ final funnelOp = MlProcessLock.instance.activeOperation?.name;+ final native = owner == null+ ? "free"+ : "held by ${owner.origin}/${owner.operation} "+ "for ${owner.heldFor.inSeconds}s";+ if (!context.mounted) return;+ showShortToast(context, "Lock: $native Β· funnel: ${funnelOp ?? 'idle'}");+ } catch (e, s) {+ logger.warning('fetching ml process lock state failed', e, s);+ if (!context.mounted) return;+ await showGenericErrorDialog(context: context, error: e);+ }+ }+Future<void> _onTriggerClustering(BuildContext context) async {try {- await PersonService.instance.fetchRemoteClusterFeedback();+ await PersonService.instance.sync();MLService.instance.debugIndexingDisabled = false;await MLService.instance.clusterAllImages();Bus.instance.fire(PeopleChangedEvent());diff --cc mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/PhotosPlatformPlugin.ktindex 7ff4cc2e78,75087f9a4c..4cce8e9769--- a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/PhotosPlatformPlugin.kt+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/PhotosPlatformPlugin.kt@@@ -1,173 -1,16 +1,20 @@@package io.ente.photos.platform- import io.ente.photos.platform.devicehealth.BatteryHealth- import io.ente.photos.platform.devicehealth.BatteryReading- import io.ente.photos.platform.devicehealth.DeviceHealthError- import io.ente.photos.platform.devicehealth.DeviceHealthService- import io.ente.photos.platform.devicehealth.DeviceHealthSnapshot- import io.ente.photos.platform.devicehealth.DeviceSignal- import io.ente.photos.platform.devicehealth.ThermalState- import io.ente.photos.platform.processlock.ProcessLockRegistry+ import io.ente.photos.platform.flutter.DeviceHealthChannelAdapter++import io.ente.photos.platform.flutter.ProcessLockChannelAdapterimport io.flutter.embedding.engine.plugins.FlutterPlugin- import io.flutter.plugin.common.EventChannel- import io.flutter.plugin.common.MethodCall- import io.flutter.plugin.common.MethodChannel- import java.util.UUID- class PhotosPlatformPlugin :- FlutterPlugin,- MethodChannel.MethodCallHandler,- EventChannel.StreamHandler {- private lateinit var methodChannel: MethodChannel- private lateinit var eventChannel: EventChannel- private lateinit var healthService: DeviceHealthService- private var eventSink: EventChannel.EventSink? = null- private val processLockInstanceId = UUID.randomUUID().toString()+ class PhotosPlatformPlugin : FlutterPlugin {+ private val deviceHealthAdapter = DeviceHealthChannelAdapter()++ private val processLockAdapter = ProcessLockChannelAdapter()override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {- healthService = DeviceHealthService(binding.applicationContext)- methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)- eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)- methodChannel.setMethodCallHandler(this)- eventChannel.setStreamHandler(this)- }-- override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {- when (call.method) {- "deviceHealth.getSnapshot" -> result.success(healthService.snapshot().toChannelMap())- "deviceHealth.getMemorySnapshot" ->- result.success(healthService.memorySnapshot().toMemoryChannelMap())- "processLock.tryAcquire" -> {- val name = call.argument<String>("name")- val origin = call.argument<String>("origin")- val operation = call.argument<String>("operation")- if (name.isNullOrEmpty() || origin.isNullOrEmpty() || operation.isNullOrEmpty()) {- result.error(- "invalidArguments",- "name, origin and operation are required",- null,- )- } else {- result.success(- ProcessLockRegistry.tryAcquire(- name,- processLockInstanceId,- origin,- operation,- ),- )- }- }- "processLock.release" -> {- val name = call.argument<String>("name")- if (name.isNullOrEmpty()) {- result.error("invalidArguments", "name is required", null)- } else {- result.success(ProcessLockRegistry.release(name, processLockInstanceId))- }- }- "processLock.state" -> {- val name = call.argument<String>("name")- if (name.isNullOrEmpty()) {- result.error("invalidArguments", "name is required", null)- } else {- result.success(ProcessLockRegistry.state(name))- }- }- else -> result.notImplemented()- }- }-- override fun onListen(arguments: Any?, events: EventChannel.EventSink) {- eventSink = events- healthService.startObserving { snapshot ->- eventSink?.success(snapshot.toChannelMap())- }- }-- override fun onCancel(arguments: Any?) {- eventSink = null- healthService.stopObserving()+ deviceHealthAdapter.attach(binding)++ processLockAdapter.attach(binding)}override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {- ProcessLockRegistry.releaseAllForInstance(processLockInstanceId)- eventSink = null- healthService.stopObserving()- methodChannel.setMethodCallHandler(null)- eventChannel.setStreamHandler(null)- }-- private fun DeviceHealthSnapshot.toChannelMap(): Map<String, Any?> =- mapOf(- "platform" to "android",- "observedAtMs" to observedAtMs,- "battery" to battery.toBatteryChannelMap(),- "thermal" to thermal.toThermalChannelMap(),- )-- private fun DeviceSignal<BatteryReading>.toBatteryChannelMap(): Map<String, Any?> =- when (this) {- is DeviceSignal.Available ->- buildMap {- put("status", "available")- put("levelPercent", value.levelPercent)- value.temperatureCelsius?.let { put("temperatureCelsius", it) }- put("health", value.health.channelValue)- }- DeviceSignal.Unsupported -> mapOf("status" to "unsupported")- is DeviceSignal.Unavailable -> unavailableChannelMap(error)- }-- private fun DeviceSignal<ThermalState>.toThermalChannelMap(): Map<String, Any?> =- when (this) {- is DeviceSignal.Available ->- mapOf("status" to "available", "state" to value.channelValue)- DeviceSignal.Unsupported -> mapOf("status" to "unsupported")- is DeviceSignal.Unavailable -> unavailableChannelMap(error)- }-- private fun DeviceSignal<Long>.toMemoryChannelMap(): Map<String, Any?> =- when (this) {- is DeviceSignal.Available -> mapOf("status" to "available", "totalBytes" to value)- DeviceSignal.Unsupported -> mapOf("status" to "unsupported")- is DeviceSignal.Unavailable -> unavailableChannelMap(error)- }-- private val BatteryHealth.channelValue: String- get() =- when (this) {- BatteryHealth.GOOD -> "good"- BatteryHealth.COLD -> "cold"- BatteryHealth.OVERHEATING -> "overheating"- BatteryHealth.OVER_VOLTAGE -> "overVoltage"- BatteryHealth.DEAD -> "dead"- BatteryHealth.FAILURE -> "failure"- BatteryHealth.UNKNOWN -> "unknown"- }-- private val ThermalState.channelValue: String- get() = name.lowercase()-- private fun unavailableChannelMap(error: DeviceHealthError): Map<String, Any?> =- mapOf("status" to "unavailable", "errorCode" to error.channelValue)-- private val DeviceHealthError.channelValue: String- get() =- when (this) {- DeviceHealthError.BATTERY_INTENT_MISSING -> "battery_intent_missing"- DeviceHealthError.BATTERY_NOT_PRESENT -> "battery_not_present"- DeviceHealthError.BATTERY_LEVEL_MISSING -> "battery_level_missing"- DeviceHealthError.BATTERY_ACCESS_DENIED -> "battery_access_denied"- DeviceHealthError.BATTERY_READ_FAILED -> "battery_read_failed"- DeviceHealthError.THERMAL_STATUS_UNKNOWN -> "thermal_status_unknown"- DeviceHealthError.THERMAL_READ_FAILED -> "thermal_read_failed"- DeviceHealthError.MEMORY_TOTAL_MISSING -> "memory_total_missing"- DeviceHealthError.MEMORY_READ_FAILED -> "memory_read_failed"- }-- private companion object {- const val METHOD_CHANNEL = "io.ente.photos.platform"- const val EVENT_CHANNEL = "io.ente.photos.platform/device_health_events"+ deviceHealthAdapter.detach()++ processLockAdapter.detach()}}diff --cc mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/flutter/ProcessLockChannelAdapter.ktindex 0000000000,0000000000..4960b5e96fnew file mode 100644--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/flutter/ProcessLockChannelAdapter.kt@@@ -1,0 -1,0 +1,64 @@@++package io.ente.photos.platform.flutter++++import io.ente.photos.platform.processlock.ProcessLockRegistry++import io.flutter.embedding.engine.plugins.FlutterPlugin++import io.flutter.plugin.common.MethodCall++import io.flutter.plugin.common.MethodChannel++import java.util.UUID++++internal class ProcessLockChannelAdapter : MethodChannel.MethodCallHandler {++ private lateinit var methodChannel: MethodChannel++ private val instanceId = UUID.randomUUID().toString()++++ fun attach(binding: FlutterPlugin.FlutterPluginBinding) {++ methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)++ methodChannel.setMethodCallHandler(this)++ }++++ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {++ when (call.method) {++ "processLock.tryAcquire" -> {++ val name = call.argument<String>("name")++ val origin = call.argument<String>("origin")++ val operation = call.argument<String>("operation")++ if (name.isNullOrEmpty() || origin.isNullOrEmpty() || operation.isNullOrEmpty()) {++ result.error(++ "invalidArguments",++ "name, origin and operation are required",++ null,++ )++ } else {++ result.success(++ ProcessLockRegistry.tryAcquire(name, instanceId, origin, operation),++ )++ }++ }++ "processLock.release" -> {++ val name = call.argument<String>("name")++ if (name.isNullOrEmpty()) {++ result.error("invalidArguments", "name is required", null)++ } else {++ result.success(ProcessLockRegistry.release(name, instanceId))++ }++ }++ "processLock.state" -> {++ val name = call.argument<String>("name")++ if (name.isNullOrEmpty()) {++ result.error("invalidArguments", "name is required", null)++ } else {++ result.success(ProcessLockRegistry.state(name))++ }++ }++ else -> result.notImplemented()++ }++ }++++ fun detach() {++ ProcessLockRegistry.releaseAllForInstance(instanceId)++ methodChannel.setMethodCallHandler(null)++ }++++ private companion object {++ const val METHOD_CHANNEL = "io.ente.photos.platform/process_lock"++ }++}diff --cc mobile/apps/photos/plugins/ente_photos_platform/ios/Flutter/PhotosPlatformPlugin.swiftindex 0000000000,71290b3f9d..6eba26ff8amode 000000,100644..100644--- a/mobile/apps/photos/plugins/ente_photos_platform/ios/Flutter/PhotosPlatformPlugin.swift+++ b/mobile/apps/photos/plugins/ente_photos_platform/ios/Flutter/PhotosPlatformPlugin.swift@@@ -1,0 -1,20 +1,23 @@@+ @preconcurrency import Flutter+ import Foundation++ @MainActor+ public final class PhotosPlatformPlugin: NSObject, @preconcurrency FlutterPlugin {+ private let deviceHealthAdapter: DeviceHealthChannelAdapter++ private let processLockAdapter: ProcessLockChannelAdapter++ private init(registrar: FlutterPluginRegistrar) {+ deviceHealthAdapter = DeviceHealthChannelAdapter(registrar: registrar)++ processLockAdapter = ProcessLockChannelAdapter(registrar: registrar)+ super.init()+ }++ public static func register(with registrar: FlutterPluginRegistrar) {+ registrar.publish(PhotosPlatformPlugin(registrar: registrar))+ }++ public func detachFromEngine(for registrar: FlutterPluginRegistrar) {+ deviceHealthAdapter.detach()++ processLockAdapter.detach()+ }+ }diff --cc mobile/apps/photos/plugins/ente_photos_platform/ios/Flutter/ProcessLockChannelAdapter.swiftindex 0000000000,0000000000..1207009ba3new file mode 100644--- /dev/null+++ b/mobile/apps/photos/plugins/ente_photos_platform/ios/Flutter/ProcessLockChannelAdapter.swift@@@ -1,0 -1,0 +1,100 @@@++@preconcurrency import Flutter++import Foundation++++@MainActor++final class ProcessLockChannelAdapter: NSObject {++ private let methodChannel: FlutterMethodChannel++ private let instanceId = UUID().uuidString++ private var isAttached = true++++ init(registrar: FlutterPluginRegistrar) {++ methodChannel = FlutterMethodChannel(++ name: Self.methodChannelName,++ binaryMessenger: registrar.messenger()++ )++ super.init()++ methodChannel.setMethodCallHandler { [weak self] call, result in++ self?.handle(call, result: result)++ }++ }++++ func detach() {++ guard isAttached else { return }++ isAttached = false++ ProcessLockRegistry.shared.releaseAll(instanceId: instanceId)++ methodChannel.setMethodCallHandler(nil)++ }++++ private func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {++ guard isAttached else { return }++ switch call.method {++ case "processLock.tryAcquire":++ handleTryAcquire(call, result: result)++ case "processLock.release":++ handleRelease(call, result: result)++ case "processLock.state":++ handleState(call, result: result)++ default:++ result(FlutterMethodNotImplemented)++ }++ }++++ private func handleTryAcquire(_ call: FlutterMethodCall, result: FlutterResult) {++ guard let args = call.arguments as? [String: Any],++ let name = args["name"] as? String, !name.isEmpty,++ let origin = args["origin"] as? String, !origin.isEmpty,++ let operation = args["operation"] as? String, !operation.isEmpty++ else {++ result(++ FlutterError(++ code: "invalidArguments",++ message: "name, origin and operation are required",++ details: nil++ )++ )++ return++ }++ result(++ ProcessLockRegistry.shared.tryAcquire(++ name: name,++ instanceId: instanceId,++ origin: origin,++ operation: operation++ )++ )++ }++++ private func handleRelease(_ call: FlutterMethodCall, result: FlutterResult) {++ guard let args = call.arguments as? [String: Any],++ let name = args["name"] as? String, !name.isEmpty++ else {++ result(++ FlutterError(++ code: "invalidArguments",++ message: "name is required",++ details: nil++ )++ )++ return++ }++ result(ProcessLockRegistry.shared.release(name: name, instanceId: instanceId))++ }++++ private func handleState(_ call: FlutterMethodCall, result: FlutterResult) {++ guard let args = call.arguments as? [String: Any],++ let name = args["name"] as? String, !name.isEmpty++ else {++ result(++ FlutterError(++ code: "invalidArguments",++ message: "name is required",++ details: nil++ )++ )++ return++ }++ result(ProcessLockRegistry.shared.state(name: name))++ }++++ private static let methodChannelName = "io.ente.photos.platform/process_lock"++}diff --cc mobile/apps/photos/plugins/ente_photos_platform/ios/Sources/PhotosPlatformCore/ProcessLockRegistry.swiftindex 8bd3d283c9,0000000000..8bd3d283c9mode 100644,000000..100644--- a/mobile/apps/photos/plugins/ente_photos_platform/ios/Sources/PhotosPlatformCore/ProcessLockRegistry.swift+++ b/mobile/apps/photos/plugins/ente_photos_platform/ios/Sources/PhotosPlatformCore/ProcessLockRegistry.swiftdiff --cc mobile/apps/photos/plugins/ente_photos_platform/lib/src/process_lock.dartindex 304ea58e9e,0000000000..6dfbbda54cmode 100644,000000..100644--- a/mobile/apps/photos/plugins/ente_photos_platform/lib/src/process_lock.dart+++ b/mobile/apps/photos/plugins/ente_photos_platform/lib/src/process_lock.dart@@@ -1,89 -1,0 +1,89 @@@+import 'package:flutter/services.dart';++/// Diagnostic state of a named process lock.+class ProcessLockState {+ const ProcessLockState({+ required this.origin,+ required this.operation,+ required this.heldFor,+ });++ factory ProcessLockState.fromMap(Map<dynamic, dynamic> map) {+ final origin = map['origin'];+ final operation = map['operation'];+ final heldForMillis = map['heldForMillis'];+ if (origin is! String || operation is! String || heldForMillis is! int) {+ throw const FormatException('Malformed process lock state');+ }+ return ProcessLockState(+ origin: origin,+ operation: operation,+ heldFor: Duration(milliseconds: heldForMillis),+ );+ }++ final String origin;+ final String operation;+ final Duration heldFor;++ @override+ String toString() =>+ 'ProcessLockState(origin: $origin, operation: $operation, '+ 'heldFor: ${heldFor.inMilliseconds}ms)';+}++/// Client for the process-global, engine-owned named locks.+///+/// At most one Flutter engine holds a given name at a time. Acquisition is+/// idempotent for the engine that already holds the name; locks are released+/// automatically when the owning engine detaches, and all state dies with+/// the OS process.+class ProcessLockClient {+ ProcessLockClient({MethodChannel? methodChannel})+ : _methodChannel = methodChannel ?? const MethodChannel(_methodChannelName);++ static final instance = ProcessLockClient();- static const _methodChannelName = 'io.ente.photos.platform';++ static const _methodChannelName = 'io.ente.photos.platform/process_lock';++ final MethodChannel _methodChannel;++ /// Attempts to acquire [name] for this engine. Returns false when another+ /// engine holds the lock. [origin] and [operation] are diagnostic labels.+ Future<bool> tryAcquire({+ required String name,+ required String origin,+ required String operation,+ }) async {+ final result = await _methodChannel.invokeMethod<bool>(+ 'processLock.tryAcquire',+ {'name': name, 'origin': origin, 'operation': operation},+ );+ if (result == null) {+ throw const FormatException('processLock.tryAcquire returned no result');+ }+ return result;+ }++ /// Releases [name] if this engine holds it. Returns whether a release+ /// occurred.+ Future<bool> release({required String name}) async {+ final result = await _methodChannel.invokeMethod<bool>(+ 'processLock.release',+ {'name': name},+ );+ if (result == null) {+ throw const FormatException('processLock.release returned no result');+ }+ return result;+ }++ /// Returns the current holder of [name], or null when the lock is free.+ Future<ProcessLockState?> state({required String name}) async {+ final result = await _methodChannel.invokeMethod<Map<dynamic, dynamic>>(+ 'processLock.state',+ {'name': name},+ );+ if (result == null) return null;+ return ProcessLockState.fromMap(result);+ }+}