Skip to content

Conversation

@zstack-robot-2
Copy link
Collaborator

Resolves: ZSTAC-12345

Change-Id: I76726765796c6b7167617a666c68797668736a75

sync from gitlab !8943

Resolves: ZSTAC-12345

Change-Id: I76726765796c6b7167617a666c68797668736a75
@MatheMatrix MatheMatrix force-pushed the sync/ye.zou/upgrade-servlet@@2 branch from a15c0e6 to 6e765ef Compare December 24, 2025 08:34
@coderabbitai
Copy link

coderabbitai bot commented Dec 24, 2025

Walkthrough

将消息超时配置提取到新工具类 TestConfigUtils,并在 TestLibController 中将 HTTP 处理改为基于 AsyncContext 的异步处理,使用固定线程池执行请求处理,增加异常处理与日志记录。

Changes

Cohort / File(s) 变更摘要
配置提取
\testlib/src/main/java/org/zstack/testlib/Test.groovy``
移除本地常量与静态方法 DEFAULT_MESSAGE_TIMEOUT_SECS / getMessageTimeoutMillsConfig(),改为导入并调用 TestConfigUtils.getMessageTimeoutMillsConfig()
新增工具类
\testlib/src/main/java/org/zstack/testlib/util/TestConfigUtils.groovy``
新增公共工具类 TestConfigUtils,提供 static long getMessageTimeoutMillsConfig(),支持 maven.surefire.debugmsgTimeoutMins 系统属性,默认 25s,调试模式下 30min
异步请求处理
\testlib/src/main/java/org/zstack/testlib/TestLibController.java``
引入 AsyncContext、固定大小 ExecutorService 线程池与日志器;将同步 Test.handleHttp(request,response) 替换为:启动异步上下文→设置超时(来自 TestConfigUtils)→提交到线程池执行→在工作线程中调用 Test.handleHttp→在 finally 中完成 asyncContext;增加错误捕获和 500 响应逻辑
配置调用调整
\testlib/src/main/java/org/zstack/testlib/WebBeanConstructor.groovy``
将默认轮询/超时相关配置调用从 Test.getMessageTimeoutMillsConfig() 改为 TestConfigUtils.getMessageTimeoutMillsConfig()

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller as TestLibController
    participant Config as TestConfigUtils
    participant Pool as ThreadPool
    participant Handler as Test.handleHttp

    Client->>Controller: 发起 HTTP 请求
    Controller->>Config: getMessageTimeoutMillsConfig()
    Config-->>Controller: 超时(ms)
    Controller->>Controller: startAsync() 并设置 timeout
    Controller->>Pool: submit 工作任务
    Pool->>Handler: 调用 handleHttp(request,response)
    Handler-->>Pool: 处理完成 / 抛出异常
    Pool->>Controller: asyncContext.complete()
    Controller-->>Client: 返回 HTTP 响应
Loading

Estimated code review effort

🎯 3 (中等) | ⏱️ ~20 分钟

Poem

🐰 我是一只代码兔,

新配置挪一处,超时更明晰,
异步线程忙又巧,日志护航不迷路,
小小改动稳步行,测试花开在春初。

Pre-merge checks and finishing touches

Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 error, 2 warnings)
Check name Status Explanation Resolution
Title check ❌ Error PR标题格式正确且完全符合要求,但与实际变更内容不符。标题声称升级servlet到3.1,但实际变更涉及消息超时配置重构、异步处理引入和工具类提取,与servlet升级无关。 更新PR标题以准确反映实际变更内容,例如'[testlib]: Extract message timeout config to utility class'或类似的能够准确描述配置重构和异步处理改进的标题。
Description check ⚠️ Warning PR描述与实际变更内容完全无关。描述仅包含Jira ID、Change-Id和Gitlab同步信息,完全未说明涉及配置重构、异步处理和工具类提取等实际技术变更。 补充详细的PR描述,说明主要变更包括:从Test.groovy提取消息超时配置到TestConfigUtils、在TestLibController中引入异步处理、配置参数的整合等关键改动。
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch sync/ye.zou/upgrade-servlet@@2

📜 Recent review details

Configuration used: Path: http://open.zstack.ai:20001/code-reviews/zstack-cloud.yaml (via .coderabbit.yaml)

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e765ef and 3144aaa.

📒 Files selected for processing (4)
  • testlib/src/main/java/org/zstack/testlib/Test.groovy
  • testlib/src/main/java/org/zstack/testlib/TestLibController.java
  • testlib/src/main/java/org/zstack/testlib/WebBeanConstructor.groovy
  • testlib/src/main/java/org/zstack/testlib/util/TestConfigUtils.groovy
🚧 Files skipped from review as they are similar to previous changes (3)
  • testlib/src/main/java/org/zstack/testlib/TestLibController.java
  • testlib/src/main/java/org/zstack/testlib/Test.groovy
  • testlib/src/main/java/org/zstack/testlib/util/TestConfigUtils.groovy
🧰 Additional context used
📓 Path-based instructions (1)
**/*.*

⚙️ CodeRabbit configuration file

**/*.*: - 代码里不应当有有中文,包括报错、注释等都应当使用正确的、无拼写错误的英文来写

Files:

  • testlib/src/main/java/org/zstack/testlib/WebBeanConstructor.groovy
🧠 Learnings (2)
📓 Common learnings
Learnt from: zstack-robot-1
Repo: MatheMatrix/zstack PR: 2360
File: network/src/main/java/org/zstack/network/l3/L3BasicNetwork.java:449-490
Timestamp: 2025-08-04T04:48:19.103Z
Learning: ZStack项目在cherry-pick操作中,即使发现了性能优化机会(如IP地址批量保存的内存优化),也严格遵循不做额外修改的政策,优先保证cherry-pick的完整性和一致性。
📚 Learning: 2025-09-01T08:16:10.006Z
Learnt from: MatheMatrix
Repo: MatheMatrix/zstack PR: 2541
File: testlib/src/main/java/org/zstack/testlib/ApiHelper.groovy:30889-30893
Timestamp: 2025-09-01T08:16:10.006Z
Learning: ApiHelper.groovy in testlib/src/main/java/org/zstack/testlib/ApiHelper.groovy is auto-generated and should not be manually modified or receive code change suggestions.

Applied to files:

  • testlib/src/main/java/org/zstack/testlib/WebBeanConstructor.groovy
🔇 Additional comments (2)
testlib/src/main/java/org/zstack/testlib/WebBeanConstructor.groovy (2)

17-17: 导入语句正确添加

新增的 TestConfigUtils 工具类导入是必要的,用于支持第 89 行的配置重构。


89-89: 配置迁移已完整实现,无需进一步调整

Test.getMessageTimeoutMillsConfig() 迁移到 TestConfigUtils.getMessageTimeoutMillsConfig() 的重构已完整完成。验证结果:

  • 所有旧方法引用已清除
  • 新工具类在4处被一致使用(WebBeanConstructor.groovy、Test.groovy、TestLibController.java)
  • 无遗留的中文代码、注释或错误信息
  • 实现逻辑完整且正确

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🧹 Nitpick comments (2)
testlib/src/main/java/org/zstack/testlib/util/TestConfigUtils.groovy (1)

5-21: 建议添加 JavaDoc 注释。

工具类及其公共方法应该添加 JavaDoc 注释,说明用途、参数含义和返回值,提高代码可读性。

🔎 建议添加 JavaDoc
+/**
+ * Utility class for test configuration management.
+ */
 class TestConfigUtils {
     private final static long DEFAULT_MESSAGE_TIMEOUT_SECS = TimeUnit.SECONDS.toMillis(25)
 
+    /**
+     * Gets the message timeout configuration in milliseconds.
+     * 
+     * @return timeout in milliseconds. Returns 30 minutes if maven.surefire.debug is set,
+     *         otherwise returns the value from msgTimeoutMins system property (in minutes converted to millis),
+     *         or the default 25 seconds if not configured.
+     */
     static long getMessageTimeoutMillsConfig(){
testlib/src/main/java/org/zstack/testlib/TestLibController.java (1)

25-25: 建议使线程池大小可配置。

线程池大小硬编码为 32 可能不适合所有测试场景。建议从配置中读取,提高灵活性。

🔎 可选的配置化改进

TestConfigUtils 中添加配置方法:

public static int getThreadPoolSize() {
    String poolSize = System.getProperty("testlib.threadpool.size");
    return poolSize != null ? Integer.parseInt(poolSize) : 32;
}

然后在 TestLibController 中使用:

-    private static final ExecutorService pool = Executors.newFixedThreadPool(32);
+    private static final ExecutorService pool = Executors.newFixedThreadPool(TestConfigUtils.getThreadPoolSize());
📜 Review details

Configuration used: Path: http://open.zstack.ai:20001/code-reviews/zstack-cloud.yaml (via .coderabbit.yaml)

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6605a26 and 6e765ef.

⛔ Files ignored due to path filters (11)
  • conf/web.xml is excluded by !**/*.xml
  • core/pom.xml is excluded by !**/*.xml
  • header/pom.xml is excluded by !**/*.xml
  • pom.xml is excluded by !**/*.xml
  • portal/pom.xml is excluded by !**/*.xml
  • rest/pom.xml is excluded by !**/*.xml
  • sdk/pom.xml is excluded by !sdk/**, !**/*.xml
  • search/pom.xml is excluded by !**/*.xml
  • simulator/pom.xml is excluded by !**/*.xml
  • testlib/pom.xml is excluded by !**/*.xml
  • utils/pom.xml is excluded by !**/*.xml
📒 Files selected for processing (3)
  • testlib/src/main/java/org/zstack/testlib/Test.groovy
  • testlib/src/main/java/org/zstack/testlib/TestLibController.java
  • testlib/src/main/java/org/zstack/testlib/util/TestConfigUtils.groovy
🧰 Additional context used
📓 Path-based instructions (2)
**/*.*

⚙️ CodeRabbit configuration file

**/*.*: - 代码里不应当有有中文,包括报错、注释等都应当使用正确的、无拼写错误的英文来写

Files:

  • testlib/src/main/java/org/zstack/testlib/util/TestConfigUtils.groovy
  • testlib/src/main/java/org/zstack/testlib/Test.groovy
  • testlib/src/main/java/org/zstack/testlib/TestLibController.java
**/*.java

⚙️ CodeRabbit configuration file

**/*.java: ## 1. API 设计要求

  • API 命名:
    • API 名称必须唯一,不能重复。
    • API 消息类需要继承 APIMessage;其返回类必须继承 APIReplyAPIEvent,并在注释中用 @RestResponse 进行标注。
    • API 消息上必须添加注解 @RestRequest,并满足如下规范:
      • path:
        • 针对资源使用复数形式。
        • 当 path 中引用消息类变量时,使用 {variableName} 格式。
      • HTTP 方法对应:
        • 查询操作 → HttpMethod.GET
        • 更新操作 → HttpMethod.PUT
        • 创建操作 → HttpMethod.POST
        • 删除操作 → HttpMethod.DELETE
    • API 类需要实现 __example__ 方法以便生成 API 文档,并确保生成对应的 Groovy API Template 与 API Markdown 文件。

2. 命名与格式规范

  • 类名:

    • 使用 UpperCamelCase 风格。
    • 特殊情况:
      • VO/AO/EO 类型类除外。
      • 抽象类采用 AbstractBase 前缀/后缀。
      • 异常类应以 Exception 结尾。
      • 测试类需要以 TestCase 结尾。
  • 方法名、参数名、成员变量和局部变量:

    • 使用 lowerCamelCase 风格。
  • 常量命名:

    • 全部大写,使用下划线分隔单词。
    • 要求表达清楚,避免使用含糊或不准确的名称。
  • 包名:

    • 统一使用小写,使用点分隔符,每个部分应是一个具有自然语义的英文单词(参考 Spring 框架的结构)。
  • 命名细节:

    • 避免在父子类或同一代码块中出现相同名字的成员或局部变量,防止混淆。
    • 命名缩写:
      • 不允许使用不必要的缩写,如:AbsSchedulerJobcondiFu 等。应使用完整单词提升可读性。

3. 编写自解释代码

  • 意图表达:

    • 避免使用布尔型参数造成含义不明确。例如:
      • 对于 stopAgent(boolean ignoreError),建议拆分为不同函数(如 stopAgentIgnoreError()),或使用枚举表达操作类型。
    • 命名应尽量用完整的单词组合表达意图,并在名称中体现数据类型或用途(例如在常量与变量名称中,将类型词放在末尾)。
    • 避免使用魔法值(Magic Value):
      • 直接使用未经定义的数值或字符串(如 if (status == 5))应替换为枚举或常量。

      • 示例:

      • // 错误示例:魔法值

      • if (user.getStatus() == 5) { ... }

      • // 正确示例:常量或枚举

      • public static final int STATUS_ACTIVE = 5;

      • if (user.getStatus() == STATUS_ACTIVE) { ... }

      • // 或使用枚举

      • enum UserStatus { ACTIVE, INACTIVE }

  • 注释:

    • 代码应尽量做到自解释,对少于两行的说明可以直接写在代码中。
    • 对于较长的注释,需要仔细校对并随代码更新,确保内容正确。
    • 接口方法不应有多余的修饰符(例如 public),且必须配有有效的 Javadoc 注释。

4. 流程控制和结构优化

  • if...else 的使用:

    • 应尽量减少 if...else 结构的使用,建议:
      • 限制嵌套层级最多为两层,且内层不应再出现 else 分支。
      • 尽早返回(Early Return),将条件判断中的处理逻辑提前结束或抽成独立方法。
      • 使用 Java Stream 或 Lambda 表达式代替冗长的循环与条件判断。
  • 条件判断:

    • if 条件表达不宜过长或过于复杂,必要时可以将条件抽成 boolean 变量描述。
  • 代码块长度:
    ...

Files:

  • testlib/src/main/java/org/zstack/testlib/TestLibController.java
🧠 Learnings (2)
📓 Common learnings
Learnt from: zstack-robot-1
Repo: MatheMatrix/zstack PR: 2360
File: network/src/main/java/org/zstack/network/l3/L3BasicNetwork.java:449-490
Timestamp: 2025-08-04T04:48:19.103Z
Learning: ZStack项目在cherry-pick操作中,即使发现了性能优化机会(如IP地址批量保存的内存优化),也严格遵循不做额外修改的政策,优先保证cherry-pick的完整性和一致性。
📚 Learning: 2025-09-01T08:16:10.006Z
Learnt from: MatheMatrix
Repo: MatheMatrix/zstack PR: 2541
File: testlib/src/main/java/org/zstack/testlib/ApiHelper.groovy:30889-30893
Timestamp: 2025-09-01T08:16:10.006Z
Learning: ApiHelper.groovy in testlib/src/main/java/org/zstack/testlib/ApiHelper.groovy is auto-generated and should not be manually modified or receive code change suggestions.

Applied to files:

  • testlib/src/main/java/org/zstack/testlib/Test.groovy
🔇 Additional comments (2)
testlib/src/main/java/org/zstack/testlib/Test.groovy (1)

28-28: 重构到工具类的做法很好。

将消息超时配置逻辑提取到 TestConfigUtils 工具类是一个良好的实践,符合单一职责原则,提高了代码的可维护性。

Also applies to: 306-307

testlib/src/main/java/org/zstack/testlib/TestLibController.java (1)

40-57: 异步处理实现正确。

使用 Servlet 3.1 的 AsyncContext 实现异步请求处理,配合线程池执行,符合升级到 Servlet 3.1 的目标。异常处理和资源清理(asyncContext.complete())都处理得当。

public class TestLibController {
private static final CLogger logger = Utils.getLogger(TestLibController.class);

private static final ExecutorService pool = Executors.newFixedThreadPool(32);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

线程池未关闭可能导致资源泄漏。

ExecutorService 在应用生命周期内创建但从未关闭。虽然在测试环境中可能不是严重问题,但在生产环境或长时间运行的测试套件中可能导致线程泄漏。建议添加关闭机制,例如使用 Spring 的 @PreDestroy 注解或在适当的清理阶段关闭线程池。

🔎 建议添加线程池关闭机制
 @Controller
 public class TestLibController {
     private static final CLogger logger = Utils.getLogger(TestLibController.class);
 
     private static final ExecutorService pool = Executors.newFixedThreadPool(32);
+
+    @PreDestroy
+    public void destroy() {
+        pool.shutdown();
+        try {
+            if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
+                pool.shutdownNow();
+            }
+        } catch (InterruptedException e) {
+            pool.shutdownNow();
+            Thread.currentThread().interrupt();
+        }
+    }

需要在文件开头添加导入:

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;
📝 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
private static final ExecutorService pool = Executors.newFixedThreadPool(32);
@Controller
public class TestLibController {
private static final CLogger logger = Utils.getLogger(TestLibController.class);
private static final ExecutorService pool = Executors.newFixedThreadPool(32);
@PreDestroy
public void destroy() {
pool.shutdown();
try {
if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
pool.shutdownNow();
}
} catch (InterruptedException e) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
🤖 Prompt for AI Agents
In testlib/src/main/java/org/zstack/testlib/TestLibController.java around line
25 the static ExecutorService pool is created but never closed, risking
thread/resource leaks; add a lifecycle/cleanup method (e.g., annotate a public
void shutdown() with @PreDestroy) that calls pool.shutdown(), awaits termination
with a reasonable timeout using TimeUnit (and if necessary calls shutdownNow()
on timeout), and log or handle interrupted exceptions; also add the imports
javax.annotation.PreDestroy and java.util.concurrent.TimeUnit.

class TestConfigUtils {
private final static long DEFAULT_MESSAGE_TIMEOUT_SECS = TimeUnit.SECONDS.toMillis(25)

static long getMessageTimeoutMillsConfig(){
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

方法名拼写错误。

方法名 getMessageTimeoutMillsConfig 中的 "Mills" 应为 "Millis"(毫秒的正确缩写)。

🔎 建议修正拼写错误
-    static long getMessageTimeoutMillsConfig(){
+    static long getMessageTimeoutMillisConfig(){

注意:如果修改方法名,需要同步更新 Test.groovyTestLibController.java 中的调用。

📝 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
static long getMessageTimeoutMillsConfig(){
static long getMessageTimeoutMillisConfig(){
🤖 Prompt for AI Agents
In testlib/src/main/java/org/zstack/testlib/util/TestConfigUtils.groovy around
line 8, the method name getMessageTimeoutMillsConfig is misspelled — "Mills"
should be "Millis"; rename the method to getMessageTimeoutMillisConfig and
update all call sites (including Test.groovy and TestLibController.java) to use
the new name, then run a build to verify no remaining references.

Comment on lines +19 to +20
long msgTimeout = Long.parseLong(msgTimeoutStr)
return TimeUnit.MINUTES.toMillis(msgTimeout)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

缺少异常处理。

Long.parseLong(msgTimeoutStr) 在接收到无效输入时会抛出 NumberFormatException。建议添加 try-catch 处理,并在解析失败时返回默认值或记录警告日志。

🔎 建议添加异常处理
+        try {
             long msgTimeout = Long.parseLong(msgTimeoutStr)
             return TimeUnit.MINUTES.toMillis(msgTimeout)
+        } catch (NumberFormatException e) {
+            // Log warning and return default value
+            return DEFAULT_MESSAGE_TIMEOUT_SECS
+        }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In testlib/src/main/java/org/zstack/testlib/util/TestConfigUtils.groovy around
lines 19-20, Long.parseLong(msgTimeoutStr) can throw NumberFormatException for
invalid input; wrap the parse in a try-catch, catch NumberFormatException (and
any NPE if needed), log a warning with the offending value and exception, and
return a sensible default timeout (e.g., previously expected default) when
parsing fails so the method never propagates the exception.

Resolves: ZSTAC-12345

Change-Id: I626979756873727a637676676b75786e74636a6d
@MatheMatrix MatheMatrix force-pushed the sync/ye.zou/upgrade-servlet@@2 branch from 6e765ef to 3144aaa Compare December 24, 2025 09:30
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.

3 participants