fix(android,ios): add thread safety to listener operations#3157
Conversation
- iOS: Add NSLock with snapshot pattern for all listener arrays (purchaseUpdated, purchaseError, promotedProduct) to prevent concurrent access crashes and silent event loss - iOS: Protect error dedup state (lastPurchaseErrorKey/Timestamp) under the same lock since sendPurchaseError is called from multiple threads - Android: Apply snapshot pattern to userChoiceBilling and developerProvidedBilling send methods for consistency - Android: Add synchronized to endConnection cleanup for userChoiceBilling and developerProvidedBilling listeners - Add Android thread safety unit tests (ListenerThreadSafetyTest) - Add TypeScript multi-listener registration/removal tests Closes #3150 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
📝 WalkthroughWalkthroughThread-safety changes across Android and iOS listener management: synchronized access and snapshot-before-iterate semantics for listener collections, plus new tests validating concurrent add/remove/iterate scenarios and snapshot isolation. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~40 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the robustness of event listener handling within the Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #3157 +/- ##
==========================================
+ Coverage 68.67% 68.84% +0.16%
==========================================
Files 9 9
Lines 1778 1778
Branches 587 587
==========================================
+ Hits 1221 1224 +3
+ Misses 552 549 -3
Partials 5 5
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Code Review
This PR significantly improves thread safety for listener operations on Android and iOS by introducing NSLock and a snapshot pattern to prevent race conditions like ConcurrentModificationException. The addition of concurrency tests for Android is also a positive step. However, a critical race condition persists on the iOS platform where state-tracking collections (deliveredPurchaseEventKeys, deliveredPurchaseEventOrder, and purchasePayloadById) are cleared on a background thread during endConnection while simultaneously being accessed on the Main Actor during event processing, which could lead to intermittent crashes. Furthermore, a serious issue was identified in the iOS listener removal logic: remove...Listener methods incorrectly use removeAll() to clear all listeners of a specific type instead of just the intended one. This deviates from the expected behavior of the JS layer and requires modification to allow individual listener management and removal on iOS.
| func removePurchaseUpdatedListener(listener: @escaping (NitroPurchase) -> Void) throws { | ||
| // Note: This is a limitation of Swift closures - we can't easily remove by reference | ||
| // For now, we'll just clear all listeners when requested | ||
| purchaseUpdatedListeners.removeAll() | ||
| listenerLock.withLock { purchaseUpdatedListeners.removeAll() } | ||
| } |
There was a problem hiding this comment.
This method, along with the other remove...Listener methods, uses removeAll(), which can cause a serious issue.
The JS layer and the newly added tests (src/__tests__/index.test.ts) expect listeners to be added and removed individually. However, in the current iOS implementation, attempting to remove a single listener will remove all listeners of that type. This can lead to unexpected bugs where removing a listener from one UI component unintentionally removes listeners registered by other components.
To properly resolve this, each listener needs to be tracked individually. Since Swift closures cannot be directly compared, a common approach is to associate each listener with a unique identifier. For example, listeners could be wrapped in a class that conforms to Equatable, or the native interface could return a unique ID when a listener is added and require that ID when removing it.
Alternative approach:
Manage the listener list in the JS layer and register only a single wrapped listener per type on the native side. This approach would remain compatible with the current removeAll() implementation.
There was a problem hiding this comment.
Good catch. The removeAll() behavior is pre-existing and by design given the current architecture:
The JS layer manages individual listener mapping via WeakMap — each purchaseUpdatedListener() call stores the wrapped callback in a WeakMap keyed by the original listener. When remove() is called on the EventSubscription, it passes the specific wrapped callback to native removePurchaseUpdatedListener().
However, in Swift, closures passed through the Nitro bridge create new wrapper instances on each call, so the native listener parameter cannot be identity-compared with stored closures. The removeAll() approach works correctly with the JS layer's WeakMap pattern because:
- The JS layer tracks which listeners are "attached" via the WeakMap
- The
useIAPhook (recommended API) manages a single listener pair internally - On
endConnection, all listeners are cleared anyway
That said, this is a valid limitation for advanced multi-listener use cases. A token/ID-based approach would require Nitro interface changes and is better addressed in a separate PR. Filed as a follow-up consideration.
| deliveredPurchaseEventKeys.removeAll() | ||
| deliveredPurchaseEventOrder.removeAll() | ||
| purchasePayloadById.removeAll() |
There was a problem hiding this comment.
The collections deliveredPurchaseEventKeys, deliveredPurchaseEventOrder, and purchasePayloadById are accessed concurrently from the Main Actor (in event handlers and transaction methods) and from a background thread in cleanupExistingState (called by endConnection). Since these collections are not thread-safe, this concurrent access can lead to data corruption or application crashes (SIGABRT). While this PR introduces listenerLock for listener arrays, it should also be used to protect these state collections, or the cleanup operations should be moved to the Main Actor.
There was a problem hiding this comment.
Fixed in 8d22fa7.
Moved deliveredPurchaseEventKeys, deliveredPurchaseEventOrder, and purchasePayloadById cleanup into the existing listenerLock.withLock block in cleanupExistingState. Also restructured sendPurchaseUpdate to perform dedup state reads/writes inside listenerLock.withLock, ensuring two-sided synchronization between cleanup (background thread) and event delivery (MainActor).
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/__tests__/index.test.ts (1)
294-308: Add native remove-call assertion for parity with the updated-listener test.This test validates behavioral isolation, but asserting native remove invocation count would tighten regression detection.
Suggested test assertion tweak
sub1.remove(); + expect(mockIap.removePurchaseErrorListener).toHaveBeenCalledTimes(1); const wrapped2 = mockIap.addPurchaseErrorListener.mock.calls[1][0]; wrapped2({code: 'network-error', message: 'Network error'}); expect(listener2).toHaveBeenCalledTimes(1); expect(listener1).not.toHaveBeenCalled(); sub2.remove(); + expect(mockIap.removePurchaseErrorListener).toHaveBeenCalledTimes(2);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/__tests__/index.test.ts` around lines 294 - 308, The test 'removing one purchaseErrorListener does not affect others' checks behavior but lacks an assertion that the native remove was invoked; update the test to assert that mockIap.removePurchaseErrorListener was called exactly once when sub1.remove() is invoked (and again if you call sub2.remove()), by referencing the subscription objects sub1/sub2 and the mock function mockIap.removePurchaseErrorListener so the native remove invocation count is verified for parity with the updated-listener test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@android/src/test/java/com/margelo/nitro/iap/ListenerThreadSafetyTest.kt`:
- Around line 48-50: The test uses join(5000) on threads (e.g., adder and sender
in ListenerThreadSafetyTest) but doesn't assert they actually finished, allowing
stalled threads to pass; update the joins to enforce completion by either
calling join() without a timeout or, if keeping a timeout, immediately assert
the thread is not alive after join (e.g., assertFalse(adder.isAlive(), "adder
did not finish") and assertFalse(sender.isAlive(), "sender did not finish")),
and apply the same change to the other block around lines 89-93 (any
remover/sender joins) before asserting errorRef.get() is null so a hung thread
fails the test instead of producing a false positive.
In `@ios/HybridRnIap.swift`:
- Around line 870-872: The current removePromotedProductListenerIOS
implementation (and the other similar remove methods) calls
promotedProductListeners.removeAll(), which unsubscribes every listener; change
the listener management to remove only the targeted callback by identity: store
listeners as structs/tuples with a unique token (e.g., UUID) and the callback
(e.g., (NitroProduct)->Void), update the add/subscribe method to return that
token, and change removePromotedProductListenerIOS to accept the token (or look
up the matching token) and remove only the entry matching that token (use
listenerList.removeAll { $0.id == token } or remove(at:) after finding the
index), and apply the same token-based removal change to the other remove
methods that currently call removeAll().
---
Nitpick comments:
In `@src/__tests__/index.test.ts`:
- Around line 294-308: The test 'removing one purchaseErrorListener does not
affect others' checks behavior but lacks an assertion that the native remove was
invoked; update the test to assert that mockIap.removePurchaseErrorListener was
called exactly once when sub1.remove() is invoked (and again if you call
sub2.remove()), by referencing the subscription objects sub1/sub2 and the mock
function mockIap.removePurchaseErrorListener so the native remove invocation
count is verified for parity with the updated-listener test.
ℹ️ Review info
Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: dba9079c-f717-41f1-90fc-51cb8f92c16b
📒 Files selected for processing (4)
android/src/main/java/com/margelo/nitro/iap/HybridRnIap.ktandroid/src/test/java/com/margelo/nitro/iap/ListenerThreadSafetyTest.ktios/HybridRnIap.swiftsrc/__tests__/index.test.ts
- Android tests: add assertFalse(thread.isAlive) after join(5000) to detect stalled threads instead of false positives - iOS: protect deliveredPurchaseEventKeys, deliveredPurchaseEventOrder, and purchasePayloadById in cleanupExistingState with listenerLock to prevent concurrent access from background thread - iOS: move dedup state access in sendPurchaseUpdate inside listenerLock for consistent two-sided synchronization Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ios/HybridRnIap.swift`:
- Around line 1083-1093: cleanupExistingState currently clears
purchasePayloadById under listenerLock while most other accesses
(attachListenersIfNeeded, finishTransaction, entitlement methods) run on the
MainActor, creating a race; change cleanupExistingState to clear
purchasePayloadById on the MainActor (e.g., wrap the removal of
purchasePayloadById in MainActor.run/await) instead of inside listenerLock so it
follows the existing MainActor access pattern and avoids data races, leaving the
other listenerLock-protected fields unchanged.
ℹ️ Review info
Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 4fdc9bf0-e2eb-48c4-bfa6-8ea5a04bdc32
📒 Files selected for processing (2)
android/src/test/java/com/margelo/nitro/iap/ListenerThreadSafetyTest.ktios/HybridRnIap.swift
🚧 Files skipped from review as they are similar to previous changes (1)
- android/src/test/java/com/margelo/nitro/iap/ListenerThreadSafetyTest.kt
Summary
NSLock+ snapshot pattern to all listener arrays for thread safetyuserChoiceBilling/developerProvidedBillinglisteners for consistencyChanges
iOS (
ios/HybridRnIap.swift)listenerLock(NSLock) for synchronized access to listener arraysaddPurchaseUpdatedListener,addPurchaseErrorListener,addPromotedProductListenerIOS, and their remove counterparts) withlistenerLock.withLocksendPurchaseUpdate,sendPurchaseError: iterate over snapshot copy instead of live array (matches Android pattern)sendPurchaseError: protect error dedup state (lastPurchaseErrorKey,lastPurchaseErrorTimestamp) inside lock since they are accessed from multiple threadscleanupExistingState: clear listener arrays and reset error dedup state inside lockAndroid (
android/.../HybridRnIap.kt)sendUserChoiceBilling,sendDeveloperProvidedBilling: change from direct iteration to snapshot patternendConnection: addsynchronizedfor clearinguserChoiceBillingListenersAndroidanddeveloperProvidedBillingListenersAndroidTests
ListenerThreadSafetyTest.kt(new) - 5 tests verifying concurrent add/remove/iterate safetyindex.test.ts- 4 new tests verifying multi-listener registration/removal independenceTest plan
yarn typecheckpassesyarn lintpassesyarn testpasses (251 tests, 12 suites)Closes #3150
🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
Bug Fixes
Tests