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

Merge qiannan 8 #1553

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Merge qiannan 8 #1553

wants to merge 3 commits into from

Conversation

LovePlayCode
Copy link
Contributor

@LovePlayCode LovePlayCode commented Aug 30, 2024

  1. analyze添加了热更新功能,在开发环境可以根据引入的包同步热更新

Summary by CodeRabbit

  • 新功能

    • 增强了图表数据处理和WebSocket集成,支持实时更新图表数据。
    • 新增配置选项,允许分析过程跟踪布尔值,提升配置能力。
    • 开发服务器新增WebSocket端点,实时发送统计数据给连接的客户端。
    • 生成的HTML输出中增加了与热模块重载相关的JavaScript变量。
  • 修复

    • 修正了测试函数名称中的拼写错误,提升了准确性和清晰度。

Copy link
Contributor

coderabbitai bot commented Aug 30, 2024

Walkthrough

此次更改涉及多个文件,主要增强了应用程序的图表数据处理和WebSocket集成。新增了处理图表数据的函数,并在useEffect中加入WebSocket连接的逻辑。同时,修改了配置结构以支持新的布尔字段,更新了开发服务器以处理统计数据,并调整了分析输出的函数签名以支持动态行为。测试函数名称也进行了修正。

Changes

文件路径 更改摘要
client/index.tsx 新增getFoamTreeData函数以处理图表数据,修改useEffect以支持WebSocket连接和清理逻辑。
crates/mako/src/config/config.rs AnalyzeConfig结构中新增watch字段,增强配置功能。
crates/mako/src/dev.rs 修改DevServer以支持WebSocket连接,新增handle_websocket_stats_data函数并更新消息结构。
crates/mako/src/generate.rs 更新write_analyze方法,新增is_watch参数以支持动态分析输出。
crates/mako/src/generate/analyze.rs 修改write_analyze函数,新增is_watch参数并在生成的HTML中包含window.hmrWatch变量。
crates/mako/src/visitors/env_replacer.rs 修正测试函数名称test_complited_computed_as_member_keytest_completed_computed_as_member_key

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant WebSocket

    Client->>Server: 请求数据
    Server->>WebSocket: 建立连接
    WebSocket-->>Server: 连接成功
    Server->>WebSocket: 发送统计数据
    WebSocket-->>Client: 接收统计数据
    Client->>Server: 更新图表数据
    Server-->>Client: 返回处理结果
Loading

在兔子洞里,数据飞舞,
新增功能,真是妙趣无穷。
WebSocket连接,实时更新,
配置增强,兔子欢腾。
让我们一起跳跃欢呼,
代码如歌,兔子最爱这场盛宴! 🐇✨


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

@@ -226,7 +226,9 @@ pub struct StatsConfig {
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct AnalyzeConfig {}
pub struct AnalyzeConfig {
pub watch: Option<bool>,
Copy link
Member

Choose a reason for hiding this comment

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

这个配置是不是可以去掉,跟随 mako 启动是否开启 watch

Copy link
Contributor Author

Choose a reason for hiding this comment

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

这个具体怎么整啊

Copy link

codecov bot commented Aug 30, 2024

Codecov Report

Attention: Patch coverage is 11.11111% with 16 lines in your changes missing coverage. Please review.

Project coverage is 61.58%. Comparing base (aad4580) to head (7186312).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
crates/mako/src/dev.rs 0.00% 10 Missing ⚠️
crates/mako/src/generate.rs 20.00% 4 Missing ⚠️
crates/mako/src/config/config.rs 0.00% 1 Missing ⚠️
crates/mako/src/generate/analyze.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1553      +/-   ##
==========================================
- Coverage   61.63%   61.58%   -0.06%     
==========================================
  Files         127      127              
  Lines       15294    15308      +14     
==========================================
  Hits         9427     9427              
- Misses       5867     5881      +14     

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

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8b79017 and 7186312.

Files selected for processing (6)
  • client/index.tsx (4 hunks)
  • crates/mako/src/config/config.rs (1 hunks)
  • crates/mako/src/dev.rs (8 hunks)
  • crates/mako/src/generate.rs (1 hunks)
  • crates/mako/src/generate/analyze.rs (2 hunks)
  • crates/mako/src/visitors/env_replacer.rs (1 hunks)
Files skipped from review due to trivial changes (1)
  • crates/mako/src/visitors/env_replacer.rs
Additional context used
GitHub Check: codecov/patch
crates/mako/src/generate/analyze.rs

[warning] 11-11: crates/mako/src/generate/analyze.rs#L11
Added line #L11 was not covered by tests

crates/mako/src/dev.rs

[warning] 271-272: crates/mako/src/dev.rs#L271-L272
Added lines #L271 - L272 were not covered by tests


[warning] 274-274: crates/mako/src/dev.rs#L274
Added line #L274 was not covered by tests


[warning] 294-294: crates/mako/src/dev.rs#L294
Added line #L294 was not covered by tests


[warning] 467-470: crates/mako/src/dev.rs#L467-L470
Added lines #L467 - L470 were not covered by tests


[warning] 475-475: crates/mako/src/dev.rs#L475
Added line #L475 was not covered by tests


[warning] 486-486: crates/mako/src/dev.rs#L486
Added line #L486 was not covered by tests

crates/mako/src/generate.rs

[warning] 196-199: crates/mako/src/generate.rs#L196-L199
Added lines #L196 - L199 were not covered by tests

crates/mako/src/config/config.rs

[warning] 230-230: crates/mako/src/config/config.rs#L230
Added line #L230 was not covered by tests

Additional comments not posted (2)
crates/mako/src/generate/analyze.rs (1)

Line range hint 11-32: 增强错误处理并验证新参数的使用

此函数现在包括一个新的参数 is_watch,用于控制是否启用热重载功能。建议增加错误处理,避免潜在的运行时错误。同时,需要验证整个代码库中此函数的使用情况,确保新参数被正确使用。

建议对 serde_json::to_string_prettyfs::write 的调用添加错误处理逻辑,以避免程序在运行时崩溃。例如:

let stats_json = serde_json::to_string_pretty(&stats).map_err(|e| e.to_string())?;
let report_path = path.join("analyze-report.html");
fs::write(&report_path, html_str).map_err(|e| e.to_string())?;

运行以下脚本以验证函数的使用情况:

Verification successful

验证 write_analyze 函数的使用情况

在代码库中,write_analyze 函数的新参数 is_watch 已正确使用。请确保在 serde_json::to_string_prettyfs::write 的调用中添加错误处理逻辑,以避免潜在的运行时错误。

  • crates/mako/src/generate.rs 中,write_analyze 函数已使用新签名。
  • 建议在 serde_json::to_string_prettyfs::write 中添加错误处理。

请根据建议更新代码以增强错误处理。

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 描述:验证整个代码库中 `write_analyze` 函数的使用情况。
# 测试:搜索函数的使用。预期:只有新签名的出现。
rg --type rust -A 5 $'write_analyze'

Length of output: 980

crates/mako/src/config/config.rs (1)

229-231: 审查 AnalyzeConfig 结构体中 watch 字段的添加

添加的 watch 字段允许配置分析过程中的特定行为,这是一个正向的改进。建议更新相关文档和示例,以展示如何使用这一新的配置选项。

Tools
GitHub Check: codecov/patch

[warning] 230-230: crates/mako/src/config/config.rs#L230
Added line #L230 was not covered by tests

Comment on lines +108 to +112
const getFoamTreeData = (chartData: any) => {
const formatData = format(chartData?.chunkModules || []);
const resData = filterModulesForSize(formatData, 'statSize');
return { groups: resData };
};
Copy link
Contributor

Choose a reason for hiding this comment

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

审查新添加的数据处理函数

新增的 getFoamTreeData 函数用于处理图表数据。需要确保此函数的逻辑正确无误,并且性能合理。

建议对此函数进行单元测试,以验证其正确性和性能。此外,考虑使用类型注解来增强代码的可读性和可维护性。

Comment on lines +169 to +178
// 如果开启了热更新,那么启动 websocket 服务。
if (window?.hmrWatch) {
const socket = new WebSocket('ws://localhost:3000/__/sendStatsData');

socket.addEventListener('message', (rawMessage) => {
const msg = JSON.parse(rawMessage.data);
console.log('msg==', msg);
setChartData(msg);
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

增强 WebSocket 逻辑的健壮性

此段代码添加了 WebSocket 逻辑,用于实时更新图表数据。建议添加错误处理和连接管理逻辑,以提高代码的健壮性。

建议在 WebSocket 连接和消息处理中添加异常处理逻辑,例如:

socket.addEventListener('message', (rawMessage) => {
  try {
    const msg = JSON.parse(rawMessage.data);
    console.log('msg==', msg);
    setChartData(msg);
  } catch (error) {
    console.error('Failed to parse message data:', error);
  }
});

Comment on lines +166 to +187
"/__/sendStatsData" => {
if hyper_tungstenite::is_upgrade_request(&req) {
debug!("new websocket connection");
let (response, websocket) = hyper_tungstenite::upgrade(req, None).unwrap();
let txws = txws.clone();
tokio_runtime::spawn(async move {
let receiver = txws.subscribe();
if txws.receiver_count() > 0 {
let stats = compiler.create_stats_info();
let json_data = serde_json::to_string_pretty(&stats).unwrap();
txws.send(WsMessage {
hash: 0,
stats_data: json_data,
})
.unwrap();
}
Self::handle_websocket_stats_data(websocket, receiver)
.await
.unwrap();
});
Ok(response)
} else {
Copy link
Contributor

Choose a reason for hiding this comment

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

审查新的 WebSocket 端点和消息处理逻辑

此代码段添加了一个新的 WebSocket 端点 /__/sendStatsData,用于处理实时统计数据的发送。建议增强安全性和错误处理。

建议在 WebSocket 消息处理中添加更严格的错误处理和安全检查,例如验证消息的完整性和格式。此外,考虑对敏感数据进行加密处理,以保护在 WebSocket 通信中传输的数据。

Comment on lines +270 to +294
// 发送热更新之后的数据
async fn handle_websocket_stats_data(
websocket: hyper_tungstenite::HyperWebsocket,
mut receiver: broadcast::Receiver<WsMessage>,
) -> Result<()> {
let websocket = websocket.await?;
let (mut sender, mut ws_recv) = websocket.split();
let task = tokio_runtime::spawn(async move {
loop {
if let Ok(msg) = receiver.recv().await {
if sender.send(Message::text(msg.stats_data)).await.is_err() {
break;
}
}
}
});
while let Some(message) = ws_recv.next().await {
if let Ok(Message::Close(_)) = message {
break;
}
}
debug!("websocket connection disconnected");
task.abort();
Ok(())
}
Copy link
Contributor

Choose a reason for hiding this comment

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

增强 WebSocket 统计数据处理功能的健壮性

此函数 handle_websocket_stats_data 负责处理通过 WebSocket 发送的统计数据。建议增加错误处理和资源管理逻辑,以提高代码的健壮性和性能。

建议在此函数中添加对 WebSocket 连接和消息发送的异常处理逻辑,以防止潜在的资源泄露和运行时错误。例如:

if let Ok(msg) = receiver.recv().await {
    if sender.send(Message::text(msg.stats_data)).await.is_err() {
        break;
    }
} else {
    // 处理接收错误
    debug!("Failed to receive message");
}
Tools
GitHub Check: codecov/patch

[warning] 271-272: crates/mako/src/dev.rs#L271-L272
Added lines #L271 - L272 were not covered by tests


[warning] 274-274: crates/mako/src/dev.rs#L274
Added line #L274 was not covered by tests


[warning] 294-294: crates/mako/src/dev.rs#L294
Added line #L294 was not covered by tests

Comment on lines +196 to +201
let analyze = &self.context.config.analyze.clone().unwrap();
let mut is_watch = false;
if analyze.watch.is_some() && analyze.watch.unwrap() {
is_watch = true;
}
Analyze::write_analyze(&stats, &self.context.config.output.path, is_watch)?;
Copy link
Contributor

Choose a reason for hiding this comment

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

审查 write_analyze 方法调用的更改

代码正确地添加了 is_watch 参数来根据配置处理不同的行为。建议显式处理 analyze.watchNone 的情况,虽然当前逻辑默认为 false。此外,由于这是一个新逻辑,建议增加相关的单元测试以确保功能的正确性和鲁棒性。

- if analyze.watch.is_some() && analyze.watch.unwrap() {
+ if analyze.watch.unwrap_or(false) {
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 analyze = &self.context.config.analyze.clone().unwrap();
let mut is_watch = false;
if analyze.watch.is_some() && analyze.watch.unwrap() {
is_watch = true;
}
Analyze::write_analyze(&stats, &self.context.config.output.path, is_watch)?;
let analyze = &self.context.config.analyze.clone().unwrap();
let mut is_watch = false;
if analyze.watch.unwrap_or(false) {
is_watch = true;
}
Analyze::write_analyze(&stats, &self.context.config.output.path, is_watch)?;
Tools
GitHub Check: codecov/patch

[warning] 196-199: crates/mako/src/generate.rs#L196-L199
Added lines #L196 - L199 were not covered by tests

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.

2 participants