Skip to content

feat: add destroy method to clear registry state on module invalidation #858

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

Merged
merged 1 commit into from
Jun 13, 2025

Conversation

jpudysz
Copy link
Owner

@jpudysz jpudysz commented Jun 13, 2025

Summary

Fixes #830

Summary by CodeRabbit

  • New Features
    • Added support for invalidating and cleaning up native resources in both Android and iOS modules, improving resource management during the module lifecycle.

Copy link

vercel bot commented Jun 13, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
react-native-unistyles-2.0 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 13, 2025 6:07pm
react-native-unistyles-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 13, 2025 6:07pm

Copy link

coderabbitai bot commented Jun 13, 2025

Walkthrough

A new mechanism for cleaning up native resources was introduced across Android, iOS, and C++ layers. This includes adding an invalidate method to the Unistyles module on both platforms, which triggers a new destroy() method in the core registry, clearing internal state and registries.

Changes

Files/Paths Change Summary
android/src/main/cxx/NativeUnistylesModule.cpp, android/src/main/cxx/NativeUnistylesModule.h Added native method registration and implementation for invalidateNative, calling registry cleanup.
android/src/main/java/com/unistyles/UnistylesModule.kt Added invalidate() override, calling new native method invalidateNative().
cxx/core/UnistylesRegistry.cpp, cxx/core/UnistylesRegistry.h Added destroy() method to clear all internal state and registries in UnistylesRegistry.
ios/UnistylesModuleOnLoad.mm Added invalidate method to Objective-C UnistylesModule, calling registry cleanup and superclass invalidate.

Assessment against linked issues

Objective Addressed Explanation
Provide a mechanism to clean up native state/registries on module invalidation to prevent crashes on reloads and reconfiguration (e.g., after StyleSheet.configure() changes) [#830]
Ensure cleanup is triggered from both Android and iOS Unistyles modules [#830]
Expose cleanup to the Java/Kotlin and Objective-C layers, connecting lifecycle events to native cleanup [#830]

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected. All modifications directly relate to the introduction of a native cleanup/invalidation mechanism as required by the linked issue.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch feature/cleanup
  • Post Copyable Unit Tests in Comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (3)
android/src/main/cxx/NativeUnistylesModule.h (1)

31-33: Suppress unused-parameter warning for jThis

jThis isn’t used inside invalidateNative, which triggers -Wunused-parameter with strict builds. Either drop the param or mark it unused:

-static void invalidateNative(jni::alias_ref<jhybridobject> jThis) {
+static void invalidateNative(jni::alias_ref<jhybridobject> /* jThis */) {

Tiny, but keeps CI warnings clean.

android/src/main/java/com/unistyles/UnistylesModule.kt (1)

51-52: Missing @Keep / visibility modifier on native method

Proguard/R8 can still strip private externals even with @DoNotStrip in some configs. Mark as internal external or annotate with @Keep to be safe.

android/src/main/cxx/NativeUnistylesModule.cpp (1)

28-30: Use fully-qualified member pointer for consistency

Both existing registrations use the UnistylesModule:: qualifier; dropping it here is harmless but breaks the established convention and makes grepping harder.

-        makeNativeMethod("invalidateNative", invalidateNative),
+        makeNativeMethod("invalidateNative", UnistylesModule::invalidateNative),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7f43278 and b532e6e.

📒 Files selected for processing (6)
  • android/src/main/cxx/NativeUnistylesModule.cpp (1 hunks)
  • android/src/main/cxx/NativeUnistylesModule.h (2 hunks)
  • android/src/main/java/com/unistyles/UnistylesModule.kt (2 hunks)
  • cxx/core/UnistylesRegistry.cpp (1 hunks)
  • cxx/core/UnistylesRegistry.h (2 hunks)
  • ios/UnistylesModuleOnLoad.mm (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
android/src/main/cxx/NativeUnistylesModule.cpp (1)
android/src/main/java/com/unistyles/UnistylesModule.kt (2)
  • initHybrid (45-49)
  • invalidateNative (51-52)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: lint
🔇 Additional comments (1)
android/src/main/cxx/NativeUnistylesModule.cpp (1)

25-31: Confirm registry teardown is safe under concurrent access

invalidateNative triggers core::UnistylesRegistry::destroy(). If any JS / native thread may still touch the registry, you risk use-after-free.
Please ensure:

  1. destroy() is idempotent and internally synchronized.
  2. Calls into the registry are quiesced (or guarded by a mutex/atomic flag) before this native method can run.

Consider adding explicit locking or an “isDestroyed” guard inside UnistylesRegistry if it isn’t already present.

Comment on lines 50 to 53
void setScopedTheme(std::optional<std::string> themeName);
core::Unistyle::Shared getUnistyleById(jsi::Runtime& rt, std::string unistyleID);
void destroy();

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

destroy() needs explicit thread-safety guarantees

destroy() mutates _states, _styleSheetRegistry, _shadowRegistry, and _scopedTheme without any locking whilst most public APIs manipulate the same structures under trafficController.withLock or other threads. Exposing it publicly without the same protection opens the door to racy teardown.

Consider:

-    void destroy();
+    // Thread-safe wipe of the global registry.
+    // Must be called when _no other thread_ might read / write the maps.
+    void destroy();

…and inside the implementation use a mutex / reuse trafficController lock.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
void setScopedTheme(std::optional<std::string> themeName);
core::Unistyle::Shared getUnistyleById(jsi::Runtime& rt, std::string unistyleID);
void destroy();
void setScopedTheme(std::optional<std::string> themeName);
core::Unistyle::Shared getUnistyleById(jsi::Runtime& rt, std::string unistyleID);
// Thread-safe wipe of the global registry.
// Must be called when _no other thread_ might read / write the maps.
void destroy();
🤖 Prompt for AI Agents
In cxx/core/UnistylesRegistry.h around lines 50 to 53, the public destroy()
method modifies shared state variables without any thread-safety mechanisms,
unlike other public APIs that use trafficController.withLock for
synchronization. To fix this, update the destroy() implementation to acquire the
same mutex or lock used by trafficController before mutating _states,
_styleSheetRegistry, _shadowRegistry, and _scopedTheme, ensuring consistent
thread-safe access during teardown.

@jpudysz jpudysz merged commit 174aae2 into main Jun 13, 2025
5 checks passed
@jpudysz jpudysz deleted the feature/cleanup branch June 13, 2025 18:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Crash when customizing StyleSheet.configure with Unistyles 3
1 participant