Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mobile][photos] Add engine-owned process lock registry to platform plugin

laurenspriem962a3b1f1214
diff --git 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
index 038f1cb6a3..7ff4cc2e78 100644
--- 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
@@ -7,10 +7,12 @@ 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.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,
@@ -20,6 +22,7 @@ class PhotosPlatformPlugin :
private lateinit var eventChannel: EventChannel
private lateinit var healthService: DeviceHealthService
private var eventSink: EventChannel.EventSink? = null
+ private val processLockInstanceId = UUID.randomUUID().toString()
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
healthService = DeviceHealthService(binding.applicationContext)
@@ -34,6 +37,43 @@ class PhotosPlatformPlugin :
"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()
}
}
@@ -51,6 +91,7 @@ class PhotosPlatformPlugin :
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
+ ProcessLockRegistry.releaseAllForInstance(processLockInstanceId)
eventSink = null
healthService.stopObserving()
methodChannel.setMethodCallHandler(null)
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/processlock/ProcessLockRegistry.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/processlock/ProcessLockRegistry.kt
new file mode 100644
index 0000000000..927bbd61e0
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/processlock/ProcessLockRegistry.kt
@@ -0,0 +1,87 @@
+package io.ente.photos.platform.processlock
+
+import android.util.Log
+
+/**
+ * Process-global registry of named, engine-owned locks. Re-acquiring a name
+ * already held by the same plugin instance is granted idempotently (this is
+ * what heals a holder orphaned by a Dart hot restart); a different instance
+ * is denied. State lives only as long as the process.
+ */
+object ProcessLockRegistry {
+ private class Holder(
+ val instanceId: String,
+ var origin: String,
+ var operation: String,
+ val acquiredAtNanos: Long,
+ )
+
+ private const val TAG = "ProcessLockRegistry"
+
+ private val guard = Any()
+ private val holders = HashMap<String, Holder>()
+
+ fun tryAcquire(
+ name: String,
+ instanceId: String,
+ origin: String,
+ operation: String,
+ ): Boolean =
+ synchronized(guard) {
+ val current = holders[name]
+ when {
+ current == null -> {
+ holders[name] = Holder(instanceId, origin, operation, System.nanoTime())
+ true
+ }
+ current.instanceId == instanceId -> {
+ Log.i(
+ TAG,
+ "Healed same-instance holder of '$name' " +
+ "(${current.origin}/${current.operation} -> $origin/$operation)",
+ )
+ current.origin = origin
+ current.operation = operation
+ true
+ }
+ else -> false
+ }
+ }
+
+ fun release(name: String, instanceId: String): Boolean =
+ synchronized(guard) {
+ if (holders[name]?.instanceId == instanceId) {
+ holders.remove(name)
+ true
+ } else {
+ false
+ }
+ }
+
+ fun releaseAllForInstance(instanceId: String) {
+ synchronized(guard) {
+ val released = holders.filterValues { it.instanceId == instanceId }
+ if (released.isNotEmpty()) {
+ Log.w(
+ TAG,
+ "Engine detach released lock(s) still held: " +
+ released.entries.joinToString {
+ "${it.key} (${it.value.origin}/${it.value.operation})"
+ },
+ )
+ }
+ holders.values.removeAll { it.instanceId == instanceId }
+ }
+ }
+
+ fun state(name: String): Map<String, Any>? =
+ synchronized(guard) {
+ holders[name]?.let {
+ mapOf(
+ "origin" to it.origin,
+ "operation" to it.operation,
+ "heldForMillis" to (System.nanoTime() - it.acquiredAtNanos) / 1_000_000,
+ )
+ }
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/ios/Classes/PhotosPlatformPlugin.swift b/mobile/apps/photos/plugins/ente_photos_platform/ios/Classes/PhotosPlatformPlugin.swift
index 5dee8677f6..59395082ff 100644
--- a/mobile/apps/photos/plugins/ente_photos_platform/ios/Classes/PhotosPlatformPlugin.swift
+++ b/mobile/apps/photos/plugins/ente_photos_platform/ios/Classes/PhotosPlatformPlugin.swift
@@ -7,6 +7,7 @@ public final class PhotosPlatformPlugin: NSObject, @preconcurrency FlutterPlugin
private let eventChannel: FlutterEventChannel
private let healthService = DeviceHealthService()
private var eventSink: FlutterEventSink?
+ private let processLockInstanceId = UUID().uuidString
private init(registrar: FlutterPluginRegistrar) {
methodChannel = FlutterMethodChannel(
@@ -33,12 +34,85 @@ public final class PhotosPlatformPlugin: NSObject, @preconcurrency FlutterPlugin
result(healthService.snapshot().channelValue)
case "deviceHealth.getMemorySnapshot":
result(healthService.memorySnapshot().memoryChannelValue)
+ case "processLock.tryAcquire":
+ handleProcessLockTryAcquire(call, result: result)
+ case "processLock.release":
+ handleProcessLockRelease(call, result: result)
+ case "processLock.state":
+ handleProcessLockState(call, result: result)
default:
result(FlutterMethodNotImplemented)
}
}
+ private func handleProcessLockTryAcquire(
+ _ 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: processLockInstanceId,
+ origin: origin,
+ operation: operation
+ )
+ )
+ }
+
+ private func handleProcessLockRelease(
+ _ 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: processLockInstanceId))
+ }
+
+ private func handleProcessLockState(
+ _ 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))
+ }
+
public func detachFromEngine(for registrar: FlutterPluginRegistrar) {
+ ProcessLockRegistry.shared.releaseAll(instanceId: processLockInstanceId)
eventSink = nil
healthService.stopObserving()
methodChannel.setMethodCallHandler(nil)
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/ios/Classes/ProcessLockRegistry.swift b/mobile/apps/photos/plugins/ente_photos_platform/ios/Classes/ProcessLockRegistry.swift
new file mode 100644
index 0000000000..8bd3d283c9
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_photos_platform/ios/Classes/ProcessLockRegistry.swift
@@ -0,0 +1,86 @@
+import Foundation
+
+/// Process-global registry of named, engine-owned locks. Re-acquiring a name
+/// already held by the same plugin instance is granted idempotently (this is
+/// what heals a holder orphaned by a Dart hot restart); a different instance
+/// is denied. State lives only as long as the process.
+final class ProcessLockRegistry: @unchecked Sendable {
+ static let shared = ProcessLockRegistry()
+
+ private struct Holder {
+ let instanceId: String
+ var origin: String
+ var operation: String
+ let acquiredAt: DispatchTime
+ }
+
+ private let lock = NSLock()
+ private var holders: [String: Holder] = [:]
+
+ private init() {}
+
+ func tryAcquire(
+ name: String,
+ instanceId: String,
+ origin: String,
+ operation: String
+ ) -> Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ if var current = holders[name] {
+ guard current.instanceId == instanceId else { return false }
+ NSLog(
+ "ProcessLockRegistry: healed same-instance holder of '%@' (%@/%@ -> %@/%@)",
+ name, current.origin, current.operation, origin, operation
+ )
+ current.origin = origin
+ current.operation = operation
+ holders[name] = current
+ return true
+ }
+ holders[name] = Holder(
+ instanceId: instanceId,
+ origin: origin,
+ operation: operation,
+ acquiredAt: .now()
+ )
+ return true
+ }
+
+ func release(name: String, instanceId: String) -> Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ guard holders[name]?.instanceId == instanceId else { return false }
+ holders.removeValue(forKey: name)
+ return true
+ }
+
+ func releaseAll(instanceId: String) {
+ lock.lock()
+ defer { lock.unlock() }
+ let released = holders.filter { $0.value.instanceId == instanceId }
+ if !released.isEmpty {
+ let description = released
+ .map { "\($0.key) (\($0.value.origin)/\($0.value.operation))" }
+ .joined(separator: ", ")
+ NSLog(
+ "ProcessLockRegistry: engine detach released lock(s) still held: %@",
+ description
+ )
+ }
+ holders = holders.filter { $0.value.instanceId != instanceId }
+ }
+
+ func state(name: String) -> [String: Any]? {
+ lock.lock()
+ defer { lock.unlock() }
+ guard let holder = holders[name] else { return nil }
+ let heldForNanos =
+ DispatchTime.now().uptimeNanoseconds - holder.acquiredAt.uptimeNanoseconds
+ return [
+ "origin": holder.origin,
+ "operation": holder.operation,
+ "heldForMillis": Int64(heldForNanos / 1_000_000),
+ ]
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dart b/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dart
index bbd6ccff1b..94602fd017 100644
--- a/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dart
+++ b/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dart
@@ -1 +1,2 @@
export 'src/device_health.dart';
+export 'src/process_lock.dart';
diff --git 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
new file mode 100644
index 0000000000..304ea58e9e
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_photos_platform/lib/src/process_lock.dart
@@ -0,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';
+
+ 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);
+ }
+}