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: async module in circular dependence #1659

Merged
merged 3 commits into from
Oct 30, 2024

Conversation

stormslowly
Copy link
Member

@stormslowly stormslowly commented Oct 25, 2024

close #1656

  1. mark modules by traversaling from all known async module sto its syns esm dependants
  2. records only async modules' dep, to save memory

Summary by CodeRabbit

  • 新功能

    • 引入了异步模块处理的新逻辑,支持异步依赖的动态创建和导出。
    • 新增了多个测试用例,增强了异步模块行为的测试覆盖率。
    • 添加了新的配置文件以指定模块的入口点。
  • 文档

    • 新增了多个 JavaScript 文件以支持异步行为和模块测试。

Copy link
Contributor

coderabbitai bot commented Oct 25, 2024

Walkthrough

该拉取请求主要对处理异步依赖的逻辑进行了修改,特别是在 transform_modules_in_thread 函数中,改用了更安全的方式来处理模块 ID 的异步依赖,避免了因未找到模块 ID 而导致的恐慌。此外,AsyncModule 结构及其方法也进行了显著改进,以更有效地管理异步依赖。新文件和测试用例的引入增强了对异步模块行为的覆盖。

Changes

文件路径 变更摘要
crates/mako/src/generate/transform.rs 修改 transform_modules_in_thread 函数,改用 cloned()unwrap_or(vec![]) 处理异步依赖。
crates/mako/src/visitors/async_module.rs 更新 AsyncModule 结构,添加新字段和逻辑,改进 mark_async 函数,增强对 CommonJS require 的处理。
e2e/fixtures/javascript.async_module_in_loop/async.js 新增文件,定义异步行为,导出默认和命名变量。
e2e/fixtures/javascript.async_module_in_loop/component.js 新增模块,导入并导出配置对象和函数。
e2e/fixtures/javascript.async_module_in_loop/expect.js 新增测试文件,设置 Jest 测试框架,准备测试环境。
e2e/fixtures/javascript.async_module_in_loop/index.js 新增测试用例,验证 displayConfig 函数的功能。
e2e/fixtures/javascript.async_module_in_loop/mako.config.json 新增配置文件,定义入口点。
e2e/fixtures/javascript.async_module_in_loop/utils.js 新增 listKeys 函数,检查并返回 config 对象的键。

Assessment against linked issues

Objective Addressed Explanation
将 M2 处理成 async module (#1656)
处理循环依赖的异步模块 (#1656) 代码中未明确处理循环依赖的逻辑。

Possibly related PRs

🐇 在月光下我跳跃,
异步模块新气象,
依赖不再恐慌,
代码更为清晰亮,
兔子欢唱乐无疆! 🌙✨


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

🧹 Outside diff range and nitpick comments (8)
e2e/fixtures/javascript.async_module_in_loop/index.js (1)

1-6: 建议添加测试用例说明

为了提高代码的可维护性,建议在测试用例前添加注释,说明测试的目的和预期行为。

建议添加如下注释:

+/**
+ * 测试异步模块在循环依赖中的行为
+ * 验证 displayConfig 函数是否正确返回配置键数组
+ */
import {displayConfig} from "./component";

it("should require looped async module", async () => {
e2e/fixtures/javascript.async_module_in_loop/utils.js (1)

8-8: 改进错误处理的返回值

使用 "oops" 作为回退值缺乏实际意义,建议使用更有意义的错误提示。

建议修改为:

-    return ["oops"]
+    return ["配置未定义"]
e2e/fixtures/javascript.async_module_in_loop/component.js (1)

5-7: 建议添加类型注释

为了提高代码的可维护性,建议为导出的配置对象添加类型注释。

+/** @type {{ key: string }} */
 export const config = {
     key: "value"
 }
crates/mako/src/generate/transform.rs (2)

81-83: 改进了异步依赖处理的健壮性!

代码改动通过使用 cloned()unwrap_or(vec![]) 替代了之前可能导致程序崩溃的 expect 调用,这是一个很好的改进。这样的改动使得在处理循环依赖时更加安全。

建议考虑添加调试日志,以便于在开发环境中追踪模块依赖的处理过程:

 let async_deps = async_deps_by_module_id
     .get(&module_id)
     .cloned()
-    .unwrap_or(vec![]);
+    .unwrap_or_else(|| {
+        debug!("No async dependencies found for module: {}", module_id);
+        vec![]
+    });

79-84: 建议添加关于异步模块处理的文档说明

当前的实现很好地解决了循环依赖的问题,但建议添加注释说明这段代码在处理异步模块依赖时的具体行为,特别是在处理循环依赖的场景下。这将有助于其他开发者理解代码的意图。

建议添加如下注释:

+    // 获取模块的异步依赖
+    // 在循环依赖的情况下,即使模块ID不存在也不会导致panic
+    // 而是返回空的依赖列表,确保转换过程可以安全继续
     let async_deps = async_deps_by_module_id
         .get(&module_id)
         .cloned()
         .unwrap_or(vec![]);
crates/mako/src/visitors/async_module.rs (3)

226-227: 建议:修改注释以更准确传达意图

第226行的注释// polluted async to dependants可能词不达意。建议修改为// 将异步状态传播给依赖模块,以更清晰地表达代码的作用。


Line range hint 296-314: 建议:增强测试用例的覆盖范围

当前测试用例test_default_import_async_module仅验证了单个异步依赖的情况。为了确保代码的健壮性,建议增加测试用例,包含以下场景:

  • 多个异步依赖的情况
  • 异步模块之间存在循环依赖的情况
  • 异步和同步模块混合依赖的情况

您是否需要我协助编写这些测试用例或者创建一个新的GitHub issue来跟踪这一任务?


Line range hint 415-434: 注意:变量名可能引起混淆

test_mix_async_module测试用例中,变量async被用作变量名,但async在Rust中是保留关键字。虽然在此上下文中可能不会导致语法错误,但是使用保留关键字作为变量名可能会降低代码的可读性,建议更改变量名以避免潜在的混淆。

建议修改如下:

-const async = require('./miexed_async');
+const mixed_async = require('./mixed_async');
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 532f9b5 and 16e8927.

📒 Files selected for processing (8)
  • crates/mako/src/generate/transform.rs (1 hunks)
  • crates/mako/src/visitors/async_module.rs (10 hunks)
  • e2e/fixtures/javascript.async_module_in_loop/async.js (1 hunks)
  • e2e/fixtures/javascript.async_module_in_loop/component.js (1 hunks)
  • e2e/fixtures/javascript.async_module_in_loop/expect.js (1 hunks)
  • e2e/fixtures/javascript.async_module_in_loop/index.js (1 hunks)
  • e2e/fixtures/javascript.async_module_in_loop/mako.config.json (1 hunks)
  • e2e/fixtures/javascript.async_module_in_loop/utils.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • e2e/fixtures/javascript.async_module_in_loop/mako.config.json
🔇 Additional comments (7)
e2e/fixtures/javascript.async_module_in_loop/index.js (1)

1-1: 导入语句看起来没有问题!

导入语句正确地从相对路径导入了 displayConfig 函数。

e2e/fixtures/javascript.async_module_in_loop/async.js (2)

5-7: 相同的优化建议适用于此处

这段代码与前面的模式相同,存在相同的优化空间。

请参考上面关于 x 变量的优化建议。


9-11: 导出语句实现正确

默认导出和命名导出的语法使用恰当。

e2e/fixtures/javascript.async_module_in_loop/component.js (2)

9-11: 考虑异步处理

由于该模块导入了异步模块,displayConfig 函数可能需要考虑异步操作的情况。建议验证 listKeys 函数是否正确处理了异步依赖。


1-3: 验证模块导入的循环依赖关系

这里同时导入了同步模块 ./utils 和异步模块 ./async,需要确保在循环依赖场景下能正确处理异步行为。

✅ Verification successful

Let's examine the specific imports to understand the circular dependency pattern better.


已确认存在循环依赖,但属于预期测试场景

这是一个有意设计的测试用例,用于验证异步模块在循环依赖场景下的行为:

  • component.js 导入 utils.jsasync.js
  • utils.js 反向导入 component.js
  • 测试文件 index.js 验证在这种循环依赖下的模块加载

这种循环引用结构是该测试用例的预期设计,用于确保构建工具能正确处理异步模块的循环依赖情况。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查模块间的依赖关系
echo "检查 utils.js 是否导入了 component.js 或 async.js,形成循环依赖"
rg -l "import.*from.*['\"]\./(component|async)['\"]" --type js

echo "检查 async.js 是否导入了 component.js 或 utils.js,形成循环依赖"
rg -l "import.*from.*['\"]\./(component|utils)['\"]" --type js

Length of output: 683


Script:

#!/bin/bash
# 检查具体的导入语句
echo "utils.js 中的导入语句:"
rg "import.*from.*['\"]\./(component|async)['\"]" e2e/fixtures/javascript.async_module_in_loop/utils.js

echo "\nasync.js 中的导入语句:"
rg "import.*from.*['\"]\./(component|utils)['\"]" e2e/fixtures/javascript.async_module_in_loop/async.js

echo "\nindex.js 中的导入语句:"
cat e2e/fixtures/javascript.async_module_in_loop/index.js

Length of output: 598

e2e/fixtures/javascript.async_module_in_loop/expect.js (2)

1-5: 导入语句结构清晰,符合最佳实践!

解构导入的方式使代码更加简洁和可维护。


9-9: 🛠️ Refactor suggestion

考虑使用动态导入以支持异步模块测试

由于这是异步模块的测试,建议使用动态导入来确保异步行为的正确性。

建议修改为:

-require("./dist/index.js");
+await import("./dist/index.js");

注意:需要将包含此代码的函数标记为 async。

Comment on lines +3 to +5
it("should require looped async moule", () => {
expect(displayConfig()).toStrictEqual(["key"])
})
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

测试用例需要进行一些改进

以下几点建议:

  1. 测试描述中 "moule" 应该改为 "module"
  2. 由于测试的是异步模块,应该使用 async/await 语法
  3. 建议添加错误处理

建议按如下方式修改代码:

-it("should require looped async moule", () => {
-    expect(displayConfig()).toStrictEqual(["key"])
-})
+it("should require looped async module", async () => {
+    try {
+        const result = await displayConfig();
+        expect(result).toStrictEqual(["key"]);
+    } catch (error) {
+        throw new Error(`测试失败: ${error.message}`);
+    }
+});
📝 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
it("should require looped async moule", () => {
expect(displayConfig()).toStrictEqual(["key"])
})
it("should require looped async module", async () => {
try {
const result = await displayConfig();
expect(result).toStrictEqual(["key"]);
} catch (error) {
throw new Error(`测试失败: ${error.message}`);
}
});

Comment on lines +4 to +7
if(config){

return Object.keys(config)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

改进代码格式和错误处理

代码存在以下问题:

  1. if 条件后的括号间距不一致
  2. 第5行空行可以删除
  3. 缺少对 config 类型的检查

建议按如下方式修改:

-    if(config){
-        
-    return Object.keys(config)
+    if (config && typeof config === 'object') {
+        return Object.keys(config)
📝 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
if(config){
return Object.keys(config)
}
if (config && typeof config === 'object') {
return Object.keys(config)
}

@@ -0,0 +1,9 @@
import {config} from "./component"
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

存在循环依赖问题需要注意

经验证,确实存在循环依赖关系:

  • utils.js./component 导入 config
  • component.js./utils 导入 listKeys

这种循环依赖可能会在异步模块加载时造成问题:

  • 模块初始化顺序不确定
  • 可能出现未定义的引用
  • 影响代码的可维护性

建议:

  • 考虑重构代码结构,打破循环依赖
  • 可以将共享的配置抽取到单独的配置文件中
  • 或者使用依赖注入的方式重组代码
🔗 Analysis chain

验证循环依赖关系

由于该文件从 ./component 导入 config,需要确认是否存在循环依赖,以确保异步模块的正确处理。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 描述:检查是否存在循环依赖
# 预期:查找 component.js 中是否引用了 utils.js

rg -l "import.*from.*['\"]\.\/utils['\"]" "$(dirname $(fd -t f utils.js))/component.js"

Length of output: 341


Script:

#!/bin/bash
# 检查 component.js 中是否引用了 utils.js
rg "import.*from.*[\"']./utils[\"']" "$(dirname $(fd -t f utils.js))/component.js"

# 查看 component.js 的完整内容以分析依赖关系
cat "$(dirname $(fd -t f utils.js))/component.js"

Length of output: 612


Script:

#!/bin/bash
# 修复路径问题,正确查找和检查文件
fd -t f "component.js" "e2e/fixtures/javascript.async_module_in_loop" -x cat {}

Length of output: 250

Comment on lines +1 to +3
let x = await new Promise((resolve)=>{
resolve("default")
})
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议优化 Promise 的创建方式

当前的 Promise 创建方式过于冗长。对于简单的值,可以使用更简洁的方式。

建议使用以下方式之一:

-let x = await new Promise((resolve)=>{
-    resolve("default")
-})
+let x = await Promise.resolve("default")

或者更简单的:

-let x = await new Promise((resolve)=>{
-    resolve("default")
-})
+let x = "default"
📝 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
let x = await new Promise((resolve)=>{
resolve("default")
})
let x = await Promise.resolve("default")

Comment on lines +6 to +7
const { files } = parseBuildResult(__dirname);
injectSimpleJest();
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

建议增加错误处理机制

在解析构建结果时,建议添加错误处理来提高测试的健壮性。

建议修改为:

-const { files } = parseBuildResult(__dirname);
+let files;
+try {
+  ({ files } = parseBuildResult(__dirname));
+} catch (error) {
+  console.error('构建结果解析失败:', error);
+  throw error;
+}
📝 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
const { files } = parseBuildResult(__dirname);
injectSimpleJest();
let files;
try {
({ files } = parseBuildResult(__dirname));
} catch (error) {
console.error('构建结果解析失败:', error);
throw error;
}
injectSimpleJest();

Comment on lines +248 to +249
let m = module_graph.get_module_mut(module_id).unwrap();
m.info.as_mut().unwrap().is_async = true;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

注意:unwrap()可能引发潜在的崩溃

在第248行,let m = module_graph.get_module_mut(module_id).unwrap();中使用了unwrap()。如果get_module_mut返回None,程序将会崩溃。建议添加错误处理以防止这种情况:

建议修改如下:

-let m = module_graph.get_module_mut(module_id).unwrap();
+if let Some(m) = module_graph.get_module_mut(module_id) {
+    // 后续操作
+} else {
+    // 处理模块不存在的情况,例如记录日志或跳过
+}

Committable suggestion was skipped due to low confidence.

Comment on lines +249 to +250
m.info.as_mut().unwrap().is_async = true;

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

注意:再次使用unwrap()可能引发潜在的崩溃

第249行的m.info.as_mut().unwrap().is_async = true;中,再次使用了unwrap()。如果infoNone,程序将崩溃。建议增加对info的存在性检查:

建议修改如下:

-if let Some(m) = module_graph.get_module_mut(module_id) {
-    m.info.as_mut().unwrap().is_async = true;
+if let Some(m) = module_graph.get_module_mut(module_id) {
+    if let Some(info) = m.info.as_mut() {
+        info.is_async = true;
+    } else {
+        // 处理info为None的情况,例如记录日志或设置默认值
+    }
+} else {
+    // 处理模块不存在的情况
+}

Committable suggestion was skipped due to low confidence.

Copy link

codecov bot commented Oct 25, 2024

Codecov Report

Attention: Patch coverage is 50.00000% with 15 lines in your changes missing coverage. Please review.

Project coverage is 55.57%. Comparing base (532f9b5) to head (16e8927).
Report is 7 commits behind head on master.

Files with missing lines Patch % Lines
crates/mako/src/visitors/async_module.rs 48.27% 15 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1659      +/-   ##
==========================================
- Coverage   55.61%   55.57%   -0.04%     
==========================================
  Files         173      173              
  Lines       17502    17523      +21     
==========================================
+ Hits         9733     9739       +6     
- Misses       7769     7784      +15     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Member

@PeachScript PeachScript left a comment

Choose a reason for hiding this comment

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

+1

@PeachScript PeachScript merged commit 9ac5ddf into master Oct 30, 2024
19 of 21 checks passed
@PeachScript PeachScript deleted the fix/async_module_in_circular_dependence branch October 30, 2024 07:55
Copy link

@Anthonyblaise Anthonyblaise left a comment

Choose a reason for hiding this comment

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

Please everybody I need money

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.

async module in a circular dependencies
3 participants