-
Notifications
You must be signed in to change notification settings - Fork 1.4k
fix(android): Resolve every permission request when they run in parallel #4168
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dennytosp
wants to merge
3
commits into
margelo:main
Choose a base branch
from
dennytosp:fix/android-parallel-permission-requests
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
ede0d0e
fix(android): Resolve every permission request when they run in parallel
dennytosp 1a9671e
fix(android): Address review - never drop the shared permission listener
dennytosp 024e511
Merge branch 'main' into fix/android-parallel-permission-requests
dennytosp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
apps/simple-camera/__tests__/visioncamera.permissions.harness.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import { describe, expect, it } from 'react-native-harness' | ||
| import { VisionCamera } from 'react-native-vision-camera' | ||
| import { withTimeout } from './test-utils' | ||
|
|
||
| describe('VisionCamera - Permissions', () => { | ||
| it('resolves camera and microphone requests that are started in parallel', async () => { | ||
| expect(VisionCamera.cameraPermissionStatus).toBe('authorized') | ||
| expect(VisionCamera.microphonePermissionStatus).toBe('authorized') | ||
|
|
||
| const parallelRequests = Promise.all([ | ||
| VisionCamera.requestCameraPermission(), | ||
| VisionCamera.requestMicrophonePermission(), | ||
| ]) | ||
| const [hasCameraPermission, hasMicrophonePermission] = await withTimeout( | ||
| parallelRequests, | ||
| 10_000, | ||
| 'parallel camera + microphone permission requests', | ||
| ) | ||
|
|
||
| expect(hasCameraPermission).toBe(true) | ||
| expect(hasMicrophonePermission).toBe(true) | ||
| }) | ||
|
|
||
| it('resolves every request when the same permission is requested multiple times at once', async () => { | ||
| expect(VisionCamera.cameraPermissionStatus).toBe('authorized') | ||
|
|
||
| const parallelRequests = Promise.all([ | ||
| VisionCamera.requestCameraPermission(), | ||
| VisionCamera.requestCameraPermission(), | ||
| VisionCamera.requestCameraPermission(), | ||
| ]) | ||
| const results = await withTimeout( | ||
| parallelRequests, | ||
| 10_000, | ||
| 'parallel camera permission requests', | ||
| ) | ||
|
|
||
| expect(results).toEqual([true, true, true]) | ||
| }) | ||
| }) |
67 changes: 67 additions & 0 deletions
67
.../android/src/main/java/com/margelo/nitro/camera/extensions/PermissionRequestDispatcher.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| package com.margelo.nitro.camera.extensions | ||
|
|
||
| import com.facebook.react.modules.core.PermissionAwareActivity | ||
| import com.facebook.react.modules.core.PermissionListener | ||
| import kotlinx.coroutines.CancellableContinuation | ||
| import kotlinx.coroutines.suspendCancellableCoroutine | ||
| import kotlinx.coroutines.sync.Mutex | ||
| import kotlinx.coroutines.sync.withLock | ||
| import java.util.concurrent.ConcurrentHashMap | ||
| import kotlin.coroutines.resume | ||
| import kotlin.coroutines.resumeWithException | ||
|
|
||
| /** | ||
| * Runs Android runtime permission requests one at a time and routes each result back to the caller that started it. | ||
| * | ||
| * Both React Native and Android only keep track of a single permission request at a time, so requests that overlap lose | ||
| * their results and leave their callers suspended forever: | ||
| * - A [PermissionAwareActivity] only remembers the [PermissionListener] of the most recent request, so a listener created | ||
| * per request is overwritten before its result arrives. This dispatcher registers one long-lived shared listener instead | ||
| * and keeps the per-request state here, keyed by request code. Because of the [mutex] there is at most one entry in | ||
| * [pendingRequests] at a time - the map is what claims and hands over that entry atomically. | ||
| * - `Activity.requestPermissions(...)` refuses a request while another one is still in flight ("Can request only one set of | ||
| * permissions at a time") and cancels it with empty grant results, which would look like a denial for a permission the | ||
| * user was never asked about. The [mutex] makes sure Android only ever sees one request at a time. | ||
| */ | ||
| internal object PermissionRequestDispatcher { | ||
| private val mutex = Mutex() | ||
| private val pendingRequests = ConcurrentHashMap<Int, CancellableContinuation<IntArray>>() | ||
| private var nextRequestCode = 3682 | ||
|
|
||
| private val listener = | ||
| PermissionListener { requestCode: Int, _: Array<String>, grantResults: IntArray -> | ||
| val continuation = pendingRequests.remove(requestCode) | ||
| if (continuation != null && continuation.isActive) { | ||
| continuation.resume(grantResults) | ||
| } | ||
| // This never returns `true`. `true` tells React Native to drop the listener again, and resuming | ||
| // the continuation above may already have let the next queued request register this very listener | ||
| // - dropping it afterwards would swallow that request's result and bring the hang back. A shared | ||
| // listener is never "done" anyway: it stays valid for every future request, ignores request codes | ||
| // it does not know, and is replaced as usual once other code registers a listener of its own. | ||
| return@PermissionListener false | ||
| } | ||
|
|
||
| /** | ||
| * Requests the given [permission] and suspends until Android reported a result for it. | ||
| * @return The grant results as reported by Android - empty if the request has been cancelled. | ||
| */ | ||
| suspend fun request( | ||
| activity: PermissionAwareActivity, | ||
| permission: String, | ||
| ): IntArray = | ||
| mutex.withLock { | ||
| suspendCancellableCoroutine { continuation -> | ||
| val requestCode = nextRequestCode++ | ||
| pendingRequests[requestCode] = continuation | ||
| continuation.invokeOnCancellation { pendingRequests.remove(requestCode) } | ||
|
|
||
| try { | ||
| activity.requestPermissions(arrayOf(permission), requestCode, listener) | ||
| } catch (error: Throwable) { | ||
| // Android never received the request, so no result will ever arrive for it. | ||
| pendingRequests.remove(requestCode)?.resumeWithException(error) | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.