Skip to content
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

fix: eslintInstance may not be initialized when calling lintFiles in the worker #40

Merged
merged 3 commits into from
Sep 25, 2024

Conversation

fuxichen
Copy link
Contributor

@fuxichen fuxichen commented Sep 24, 2024

Description 描述

修复在worker模式下因异步问题导致经常报错 Cannot read properties of undefined (reading 'lintFiles')

Linked Issues 关联的 Issues

Additional context 额外上下文

image

Summary by CodeRabbit

  • New Features

    • Improved initialization logic for ESLint, enhancing control flow and ensuring readiness before processing messages.
  • Bug Fixes

    • Resolved issues related to asynchronous handling during ESLint initialization.

修复在worker模式下因异步问题导致经常报错 Cannot read properties of undefined (reading 'lintFiles')
Copy link

coderabbitai bot commented Sep 24, 2024

Walkthrough

The changes involve restructuring the initialization logic for ESLint in the worker.ts file. The previous immediate function has been replaced with a promise-based approach, initPromise, which ensures that the ESLint instance is fully initialized before any linting operations occur. The message handling logic has been updated to wait for this initialization, ensuring that it only processes messages after ESLint is ready.

Changes

File Change Summary
packages/core/src/worker.ts Restructured ESLint initialization using a promise to manage asynchronous flow and updated message handling to ensure ESLint readiness.

Poem

In the burrow where code does hop,
A new init makes linting stop,
With promises bright,
It sets things right,
Now messages wait, till the ESLint's on top! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 285ca82 and cdca14b.

📒 Files selected for processing (1)
  • packages/core/src/worker.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/worker.ts

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>, please review it.
    • 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 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 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 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 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: 0

Outside diff range and nitpick comments (1)
packages/core/src/worker.ts (1)

Line range hint 31-48: Well-structured initialization function with room for improvement

The new init function is a well-structured approach to handling the ESLint initialization. It properly sets up the eslintInstance, formatter, and outputFixes, effectively addressing the issue of undefined eslintInstance. The use of resolve() ensures that the Promise is fulfilled after initialization, which is crucial for the asynchronous flow.

Consider adding error handling to the init function, especially around the initializeESLint call and the lintOnStart operation. This would make the initialization process more robust. For example:

const init = async () => {
  try {
    debug("Initialize ESLint");
    const result = await initializeESLint(options);
    eslintInstance = result.eslintInstance;
    formatter = result.formatter;
    outputFixes = result.outputFixes;
    resolve();
    if (options.lintOnStart) {
      debug("Lint on start");
      await lintFiles({
        files: options.include,
        eslintInstance,
        formatter,
        outputFixes,
        options,
      });
    }
  } catch (error) {
    debug(`Initialization error: ${error}`);
    // Consider how to handle initialization failures
  }
};
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 31e4cdc and a3f4f56.

Files selected for processing (1)
  • packages/core/src/worker.ts (2 hunks)
Additional comments not posted (3)
packages/core/src/worker.ts (3)

27-30: Excellent addition of asynchronous control flow

The introduction of a Promise and its resolve function is a good approach to manage the asynchronous initialization of ESLint. This change directly addresses the issue of eslintInstance being undefined in worker mode by ensuring that the initialization is complete before any linting operations are performed.


52-52: Critical fix for race condition

The addition of await p; at the beginning of the message event handler is a crucial fix. This ensures that the ESLint instance is fully initialized before processing any messages, effectively resolving the race condition that was causing the eslintInstance to be undefined.

This change directly addresses the issue mentioned in the PR objectives and should prevent the "Cannot read properties of undefined (reading 'lintFiles')" error.


Line range hint 27-52: Overall excellent solution to the reported issue

The changes implemented in this file effectively address the problem of eslintInstance being undefined in worker mode. The introduction of a Promise-based initialization process and the restructuring of the code provide a robust solution to the race condition that was causing the issue.

Key improvements:

  1. Asynchronous control flow with Promise
  2. Well-structured init function
  3. Proper sequencing of initialization and message processing

These changes should resolve the "Cannot read properties of undefined (reading 'lintFiles')" error and improve the overall reliability of the plugin in worker mode.

While there's room for minor improvements in error handling, the core issue has been successfully addressed. Great work on this fix!

@ModyQyW
Copy link
Owner

ModyQyW commented Sep 24, 2024

请先提供一个最小复现demo

@fuxichen
Copy link
Contributor Author

请先提供一个最小复现demo

https://github.com/fuxichen/c419136d

@ModyQyW
Copy link
Owner

ModyQyW commented Sep 25, 2024

由于 cjs 里面无法做到顶层 await,所以只能用 iife 来处理。当 worker 线程启动时,它会执行代码,直到到达 await initializeESLint(options)。由于 initializeESLint 是异步函数,触发事件循环。如果此时主线程向 worker 线程发送消息,则 worker 线程会暂停当前执行的异步操作,转而处理 message 事件,执行 parentPort.on("message", ...) 中的回调函数。

当你设置了 server.open 为 true,vite 会自动预热入口和对应的相关文件,这时候就会导致主线程在 initializeESLint 完成之前发送消息,进而导致报错。

目前的修复方案我认为不太好,可以参考 https://github.com/nabla/vite-plugin-eslint/blob/main/src/worker.cjs#L12-L25 改一下吗?谢谢

@fuxichen
Copy link
Contributor Author

由于 cjs 里面无法做到顶层 await,所以只能用 iife 来处理。当 worker 线程启动时,它会执行代码,直到到达 await initializeESLint(options)。由于 initializeESLint 是异步函数,触发事件循环。如果此时主线程向 worker 线程发送消息,则 worker 线程会暂停当前执行的异步操作,转而处理 message 事件,执行 parentPort.on("message", ...) 中的回调函数。

当你设置了 server.open 为 true,vite 会自动预热入口和对应的相关文件,这时候就会导致主线程在 initializeESLint 完成之前发送消息,进而导致报错。

目前的修复方案我认为不太好,可以参考 https://github.com/nabla/vite-plugin-eslint/blob/main/src/worker.cjs#L12-L25 改一下吗?谢谢

已调整

@ModyQyW ModyQyW changed the title fix: 修复 worker 模式下 eslintInstance 为undefind的问题 fix: eslintInstance may not be initialized when calling lintFiles in the worker Sep 25, 2024
Copy link

pkg-pr-new bot commented Sep 25, 2024

Open in Stackblitz

pnpm add https://pkg.pr.new/vite-plugin-eslint2@40

commit: cdca14b

@ModyQyW
Copy link
Owner

ModyQyW commented Sep 25, 2024

Thank you♥️

@ModyQyW ModyQyW merged commit afc7bee into ModyQyW:main Sep 25, 2024
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants