Skip to content
This repository was archived by the owner on Apr 26, 2026. It is now read-only.

fix(android,ios): add thread safety to listener operations#3157

Merged
hyochan merged 2 commits into
mainfrom
fix/ios-listener-thread-safety
Mar 4, 2026
Merged

fix(android,ios): add thread safety to listener operations#3157
hyochan merged 2 commits into
mainfrom
fix/ios-listener-thread-safety

Conversation

@hyochan

@hyochan hyochan commented Mar 4, 2026

Copy link
Copy Markdown
Owner

Summary

  • iOS: Apply NSLock + snapshot pattern to all listener arrays for thread safety
  • Android: Apply snapshot pattern to userChoiceBilling / developerProvidedBilling listeners for consistency
  • Add thread safety unit tests and multi-listener registration/removal tests

Changes

iOS (ios/HybridRnIap.swift)

  • Add listenerLock (NSLock) for synchronized access to listener arrays
  • Wrap all add/remove listener methods (addPurchaseUpdatedListener, addPurchaseErrorListener, addPromotedProductListenerIOS, and their remove counterparts) with listenerLock.withLock
  • sendPurchaseUpdate, 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 threads
  • Apply snapshot pattern to promoted product listener iteration
  • cleanupExistingState: clear listener arrays and reset error dedup state inside lock

Android (android/.../HybridRnIap.kt)

  • sendUserChoiceBilling, sendDeveloperProvidedBilling: change from direct iteration to snapshot pattern
  • endConnection: add synchronized for clearing userChoiceBillingListenersAndroid and developerProvidedBillingListenersAndroid

Tests

  • Android: ListenerThreadSafetyTest.kt (new) - 5 tests verifying concurrent add/remove/iterate safety
  • TypeScript: index.test.ts - 4 new tests verifying multi-listener registration/removal independence

Test plan

  • yarn typecheck passes
  • yarn lint passes
  • yarn test passes (251 tests, 12 suites)
  • Pre-commit hooks pass

Closes #3150

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Enhanced thread-safety mechanisms for in-app purchase event listeners on iOS and Android to prevent potential crashes when listeners are added, removed, or notified concurrently.
  • Tests

    • Added comprehensive test suite validating thread-safe listener operations, snapshot semantics, and reliable event delivery across multiple concurrent listeners.

- 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>
@coderabbitai

coderabbitai Bot commented Mar 4, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Thread-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

Cohort / File(s) Summary
Android Listener Thread-Safety
android/src/main/java/com/margelo/nitro/iap/HybridRnIap.kt
Protected listener list access with synchronized blocks. endConnection clears listener lists under lock; sendUserChoiceBilling and sendDeveloperProvidedBilling take synchronized snapshots before iterating to avoid ConcurrentModification.
Android Listener Tests
android/src/test/java/com/margelo/nitro/iap/ListenerThreadSafetyTest.kt
New Kotlin test suite exercising concurrent add/remove/iterate, snapshot delivery/isolation, and synchronized clear semantics using multi-threading and barriers.
iOS Listener Thread-Safety
ios/HybridRnIap.swift
Added listenerLock and converted all listener mutations/iterations to lock-guarded operations with snapshot-before-iterate. Centralized purchase-error deduplication under lock and cleared listener/dedup state in endConnection.
TypeScript Listener Tests
src/__tests__/index.test.ts
Added JS/TS tests for multi-listener broadcast and per-listener removal behavior for purchase-updated and purchase-error listeners; asserts native remove calls where applicable.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Suggested labels

🤖 android, 📱 iOS, 🛠 bugfix

Poem

🐰 Hopping through code with a curious gleam,
I snipped tangled listeners mid-concurrent stream.
I snapshot the garden, then let events leap,
Locks guard the burrow when the callers all sleep.
Rejoice — no more crashes, just carrots to keep! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding thread safety to listener operations across Android and iOS platforms.
Linked Issues check ✅ Passed The pull request comprehensively addresses issue #3150 by implementing thread-safe listener operations to ensure reliable purchase event delivery on iOS and Android.
Out of Scope Changes check ✅ Passed All changes are directly related to addressing thread safety in listener operations and include supporting test coverage; no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/ios-listener-thread-safety

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, 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 HybridRnIap module by introducing explicit thread safety measures across iOS and Android. The changes prevent potential ConcurrentModificationException issues and ensure reliable event delivery, even when listeners are added, removed, or triggered concurrently. The update includes new unit tests to verify the integrity of these improvements.

Highlights

  • Thread Safety for Listeners: Implemented thread-safe mechanisms for listener operations on both iOS and Android platforms to prevent concurrent modification issues.
  • iOS Listener Synchronization: Introduced NSLock and a snapshot pattern for all listener arrays and error deduplication state in iOS, ensuring synchronized access during add, remove, and iteration.
  • Android Listener Consistency: Applied the snapshot pattern to userChoiceBilling and developerProvidedBilling listeners in Android for consistent thread-safe iteration.
  • New Unit Tests: Added comprehensive unit tests for Android (Kotlin) and TypeScript to validate the new thread safety measures and multi-listener behavior.

🧠 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
  • android/src/main/java/com/margelo/nitro/iap/HybridRnIap.kt
    • Added synchronized blocks for clearing userChoiceBillingListenersAndroid and developerProvidedBillingListenersAndroid in endConnection.
    • Refactored sendUserChoiceBilling and sendDeveloperProvidedBilling to use a synchronized snapshot pattern for listener iteration.
  • android/src/test/java/com/margelo/nitro/iap/ListenerThreadSafetyTest.kt
    • Added a new test file ListenerThreadSafetyTest.kt containing five unit tests to verify concurrent add, remove, and iterate operations on listeners are thread-safe using the snapshot pattern.
  • ios/HybridRnIap.swift
    • Introduced a listenerLock (NSLock) to protect listener arrays and error deduplication state.
    • Wrapped addPromotedProductListenerIOS, addPurchaseUpdatedListener, addPurchaseErrorListener, and their corresponding remove methods with listenerLock.withLock.
    • Modified sendPurchaseUpdate and sendPurchaseError to iterate over a snapshot of listeners, created under listenerLock.
    • Protected lastPurchaseErrorKey and lastPurchaseErrorTimestamp updates within sendPurchaseError using listenerLock.
    • Ensured listener array clearing and error dedup state reset in cleanupExistingState are performed within listenerLock.
  • src/tests/index.test.ts
    • Added four new tests to confirm that multiple purchaseUpdatedListeners and purchaseErrorListeners correctly receive events, and that removing one listener does not impact others.
Activity
  • The pull request addresses and closes issue [iOS/Android] - High volume of purchases not being handled/notified #3150, which reported silently lost purchase events due to concurrent listener access.
  • The author, hyochan, has implemented changes across Android (Kotlin), iOS (Swift), and TypeScript test files.
  • The PR description provides a detailed breakdown of changes for each platform and the new tests.
  • A test plan is included, confirming successful execution of yarn typecheck, yarn lint, yarn test, and pre-commit hooks.
  • The pull request was generated with Claude Code.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@codecov

codecov Bot commented Mar 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 68.84%. Comparing base (6343b15) to head (8d22fa7).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            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              
Flag Coverage Δ
library 68.84% <ø> (+0.16%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.
see 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread ios/HybridRnIap.swift
Comment on lines 884 to 886
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() }
}

@gemini-code-assist gemini-code-assist Bot Mar 4, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. The JS layer tracks which listeners are "attached" via the WeakMap
  2. The useIAP hook (recommended API) manages a single listener pair internally
  3. 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.

Comment thread ios/HybridRnIap.swift Outdated
Comment on lines 1082 to 1084
deliveredPurchaseEventKeys.removeAll()
deliveredPurchaseEventOrder.removeAll()
purchasePayloadById.removeAll()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between cc4de64 and 949e4d7.

📒 Files selected for processing (4)
  • android/src/main/java/com/margelo/nitro/iap/HybridRnIap.kt
  • android/src/test/java/com/margelo/nitro/iap/ListenerThreadSafetyTest.kt
  • ios/HybridRnIap.swift
  • src/__tests__/index.test.ts

Comment thread ios/HybridRnIap.swift
- 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>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 949e4d7 and 8d22fa7.

📒 Files selected for processing (2)
  • android/src/test/java/com/margelo/nitro/iap/ListenerThreadSafetyTest.kt
  • ios/HybridRnIap.swift
🚧 Files skipped from review as they are similar to previous changes (1)
  • android/src/test/java/com/margelo/nitro/iap/ListenerThreadSafetyTest.kt

Comment thread ios/HybridRnIap.swift
@hyochan hyochan merged commit f14d652 into main Mar 4, 2026
11 checks passed
@hyochan hyochan deleted the fix/ios-listener-thread-safety branch March 4, 2026 09:18
@hyochan hyochan added the 🛠 bugfix All kinds of bug fixes label Mar 4, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

🛠 bugfix All kinds of bug fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[iOS/Android] - High volume of purchases not being handled/notified

1 participant