Skip to content

fix: failsafe JavaScript event emitter notifyListeners#3695

Merged
leaanthony merged 3 commits intowailsapp:masterfrom
mrf345:fix_js_event_emitter
Aug 20, 2024
Merged

fix: failsafe JavaScript event emitter notifyListeners#3695
leaanthony merged 3 commits intowailsapp:masterfrom
mrf345:fix_js_event_emitter

Conversation

@mrf345
Copy link
Contributor

@mrf345 mrf345 commented Aug 20, 2024

Description

Failsafe JavaScript event emitter v2/internal/frontend/runtime/desktop/events.js:notifyListeners()

Fixes #3694

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Locally with following steps:

  1. Create multiple listeners with runtime.EventsOn() on the frontend
  2. Emit lots of events from the backend with runtime.EventsEmit()
  3. Terminate the listeners on the frontend with runtime.EventsOf()
  • Windows
  • macOS
  • Linux

Test Configuration

# Wails
Version         | v2.9.1
Package Manager | pacman

# System
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
| OS           | Arch Linux                                                                                                        |
| Version      | Unknown                                                                                                           |
| ID           | arch                                                                                                              |
| Go Version   | go1.23.0                                                                                                          |
| Platform     | linux                                                                                                             |
| Architecture | amd64                                                                                                             |
| CPU          | AMD Ryzen 7 4800H with Radeon Graphics                                                                            |
| GPU 1        | Navi 14 [Radeon RX 5500/5500M / Pro 5500M] (Advanced Micro Devices, Inc. [AMD/ATI]) - Driver: amdgpu              |
| GPU 2        | Renoir [Radeon Vega Series / Radeon Vega Mobile Series] (Advanced Micro Devices, Inc. [AMD/ATI]) - Driver: amdgpu |
| Memory       | 15GB                                                                                                              |
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

# Dependencies
┌───────────────────────────────────────────────────────────────────┐
| Dependency | Package Name | Status    | Version                   |
| *docker    | docker       | Installed | 1:27.1.1-1                |
| gcc        | gcc          | Installed | 14.2.1+r32+geccf707e5ce-1 |
| libgtk-3   | gtk3         | Installed | 1:3.24.43-1               |
| libwebkit  | webkit2gtk   | Installed | 2.44.3-3                  |
| npm        | npm          | Installed | 10.8.2-1                  |
| pkg-config | pkgconf      | Installed | 2.1.1-1                   |
└───────────────────── * - Optional Dependency ─────────────────────┘

Checklist:

  • I have updated website/src/pages/changelog.mdx with details of this PR
  • My code follows the general coding style of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • Bug Fixes

    • Resolved issues with file drop events on Windows.
    • Improved drag-and-drop functionality with enhanced nil checks on Windows.
    • Fixed a race condition in the event notification system.
  • Improvements

    • Enhanced logic for managing event listeners for better performance and reliability.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2024

Warning

Rate limit exceeded

@mrf345 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 58 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 463608a and 8740a56.

Walkthrough

This update enhances event listener management in the codebase, focusing on the notifyListeners function to prevent race conditions and improve error handling. Key changes include the use of shallow copies of listener arrays and optional chaining for safer access. Additionally, the changelog reflects various bug fixes, particularly for file drop events on Windows and improvements to thread safety.

Changes

Files Change Summary
v2/internal/frontend/runtime/desktop/events.js, v2/internal/frontend/runtime/runtime_debug_desktop.js Modified event listener handling logic to prevent race conditions, using shallow copies and optional chaining for safer array access.
website/src/pages/changelog.mdx Updated changelog to document bug fixes, including enhancements to Windows file drop events and the resolution of race conditions in listeners.

Assessment against linked issues

Objective Addressed Explanation
JavaScript event emitter race condition not to throw errors (#3694)
Ensure notifyListeners does not cause undefined errors (#3694)

Poem

🐇 In the code beneath the moonlit glow,
Event whispers dance, no need for woe.
With gentle hops, we fix the race,
Listeners shine in their rightful place!
So let the changes spread their cheer,
In our code, we hold them dear! 🌙✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @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.

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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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
Contributor

@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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 868931f and 463608a.

Files selected for processing (3)
  • v2/internal/frontend/runtime/desktop/events.js (1 hunks)
  • v2/internal/frontend/runtime/runtime_debug_desktop.js (1 hunks)
  • website/src/pages/changelog.mdx (1 hunks)
Additional comments not posted (4)
v2/internal/frontend/runtime/desktop/events.js (1)

93-94: LGTM! Verify the usage of notifyListeners.

The changes to use a shallow copy and optional chaining are correct and improve the function's robustness against race conditions.

Ensure that the usage of notifyListeners throughout the codebase aligns with these changes.

Verification successful

Usage of notifyListeners is consistent and correct.

The function notifyListeners is used in multiple places within the codebase, and the changes to use a shallow copy and optional chaining are properly implemented. No issues were found regarding its usage.

  • v2/internal/frontend/runtime/runtime_debug_desktop.js: The function is used consistently with the new implementation.
  • v2/internal/frontend/runtime/desktop/events.js: The function is correctly updated and used.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `notifyListeners` to ensure compatibility with the changes.

# Test: Search for the function usage. Expect: No issues with the new implementation.
rg --type javascript -A 5 $'notifyListeners'

Length of output: 78


Script:

#!/bin/bash
# Description: Verify the usage of `notifyListeners` to ensure compatibility with the changes.

# Test: Search for the function usage. Expect: No issues with the new implementation.
rg -A 5 'notifyListeners'

Length of output: 3302

website/src/pages/changelog.mdx (1)

26-26: Changelog entry approved.

The entry for fixing the notifyListeners() race condition is clear and provides a useful reference to the related pull request.

v2/internal/frontend/runtime/runtime_debug_desktop.js (2)

86-89: LGTM! Optional chaining and shallow copy enhance robustness.

The use of optional chaining with ?. and creating a shallow copy of the listener list with slice() ensures that the code handles undefined lists gracefully, preventing potential runtime errors.


Line range hint 87-99: Verify listener list update logic.

Ensure that the logic correctly updates the eventListeners array after processing. The splice operation on newEventListenerList should not affect the original list unless reassigned.

Verification successful

Listener list update logic is correctly implemented.

The eventListeners[eventName] is correctly reassigned after processing, ensuring that the modifications to newEventListenerList are properly applied. This confirms that the splice operation does not affect the original list unless reassigned, which is handled correctly in the code.

  • The line eventListeners[eventName] = newEventListenerList; confirms the correct update logic.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the `eventListeners` array is correctly updated after processing in `notifyListeners`.

# Test: Search for the assignment to `eventListeners[eventName]` after processing.
rg --type javascript -A 5 $'eventListeners[eventName] = '

Length of output: 93


Script:

#!/bin/bash
# Description: Verify that the `eventListeners` array is correctly updated after processing in `notifyListeners`.

# Find all JavaScript files and search for the assignment to `eventListeners[eventName]` after processing.
fd -e js | xargs rg -A 5 'eventListeners\[eventName\] = '

Length of output: 3042

@sonarqubecloud
Copy link

@leaanthony leaanthony enabled auto-merge (squash) August 20, 2024 21:00
@leaanthony leaanthony merged commit 4b6a8e1 into wailsapp:master Aug 20, 2024
therealsamf pushed a commit to therealsamf/wails that referenced this pull request Aug 29, 2024
* fix: failsafe JavaScript event emitter `notifyListeners`

* chore: update change log
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.

JavaScript event emitter race condition

2 participants