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: Modify block group api #182

Merged
merged 43 commits into from
Feb 13, 2025
Merged

fix: Modify block group api #182

merged 43 commits into from
Feb 13, 2025

Conversation

lu-yg
Copy link
Collaborator

@lu-yg lu-yg commented Feb 13, 2025

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • Refactor
    • Improved history record responses by renaming a key to "block_id" for clearer API output.
    • Updated block group endpoints to return more comprehensive and consistent details, including accurate version information for related blocks.
    • Streamlined return types in block group services and controllers to reflect entity objects directly.
  • Bug Fixes
    • Adjusted logic in block group methods to ensure correct handling of entity retrieval and deletion.
  • Chores
    • Modified workflow configuration for Checkstyle checks to perform a clean build instead.

lu-yg and others added 30 commits December 26, 2024 00:15
Copy link

coderabbitai bot commented Feb 13, 2025

Walkthrough

This pull request introduces several changes across the codebase. In the common base module, the refId field in the HistoryEntity class is updated with a new JSON serialization annotation. In the controller, service, service implementation, and test classes, the return types of methods have been updated from data transfer objects (DTOs) to direct entity objects. Additionally, the service implementation now retrieves associated blocks using a new query method with a default user identifier and updates block version information accordingly.

Changes

File(s) Change Summary
base/.../common/base/HistoryEntity.java Added @JsonProperty("block_id") annotation on the refId field for JSON serialization.
base/.../controller/BlockGroupController.java,
base/.../service/material/BlockGroupService.java,
base/.../service/material/impl/BlockGroupServiceImpl.java
Updated method return types from Result<List<BlockGroupDto>> to Result<List<BlockGroup>>; modified logic in BlockGroupServiceImpl to use queryBlockGroupAndBlockById with a new DEFAULT_USER_ID constant and set block currentVersion via an iteration over associated blocks.
base/.../test/java/com/tinyengine/it/controller/BlockGroupControllerTest.java,
base/.../test/java/com/tinyengine/it/service/material/impl/BlockGroupServiceImplTest.java
Updated tests to reflect the new return types from DTOs to entity objects, including changes in mocked responses and assertions.
.github/.../checkstyle.yml Changed Checkstyle command from mvn checkstyle:check to mvn clean package, altering the workflow to perform a clean build instead of just running Checkstyle checks.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant CTRL as BlockGroupController
    participant SVC as BlockGroupServiceImpl
    participant M as BlockCarriersRelationMapper

    C->>CTRL: Request to createBlockGroups(BlockGroup)
    CTRL->>SVC: Call createBlockGroup(BlockGroup)
    SVC->>SVC: Execute findBlockGroupById(id, DEFAULT_USER_ID)
    SVC->>M: queryBlockGroupAndBlockById(blockId, DEFAULT_USER_ID)
    M-->>SVC: Return block carrier relation
    SVC->>SVC: Set block currentVersion (iterating if needed)
    SVC-->>CTRL: Return Result<List<BlockGroup>>
    CTRL-->>C: Respond with updated BlockGroup entity list
Loading

Suggested reviewers

  • zhangjuncao

Poem

Oh, I’m a hopping rabbit in the code,
With blocks and versions in my humble abode.
Annotations and entities now dance in delight,
As my little paws tap keys day and night.
Code paths bloom like springtime glee 🐰🌸!
Happy hops to changes, so fresh and free!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 3

🧹 Nitpick comments (6)
base/src/main/java/com/tinyengine/it/service/material/impl/BlockGroupServiceImpl.java (3)

54-54: Externalize the DEFAULT_USER_ID.

Hardcoding a user ID might cause maintenance and security issues in production environments. Consider externalizing it (e.g., configuration file, environment variable) to improve flexibility and avoid potential leaks.


73-90: Validate the block version retrieval logic.

Currently, the loop retrieves only the first BlockCarriersRelation record and applies its version as currentVersion. If multiple relations exist, only the first is used. Verify this is intended behavior, or consider retrieving the relevant version explicitly (e.g., the latest) to avoid potential data inconsistencies.


164-173: Revisit returning a single BlockGroup in a list.

This method returns a list containing only one newly created BlockGroup. If only one group is created here, consider returning a single entity or updating the method signature and surrounding logic to avoid wrapping a single result in a list. Also, handle concurrency carefully if multiple threads attempt to create the same block group concurrently.

base/src/test/java/com/tinyengine/it/service/material/impl/BlockGroupServiceImplTest.java (1)

104-112: Enhance test coverage for createBlockGroup method.

While the test verifies the basic functionality, it could be more comprehensive by:

  1. Verifying the size of the returned list
  2. Checking the properties of the returned BlockGroup object
  3. Validating that the returned BlockGroup matches the input parameters
 @Test
 void testCreateBlockGroup() {
     BlockGroup param = new BlockGroup();
     when(blockGroupMapper.createBlockGroup(param)).thenReturn(1);
     BlockGroup blockGroupParam = new BlockGroup();
     blockGroupParam.setId(1);
     Result<List<BlockGroup>> result = blockGroupServiceImpl.createBlockGroup(blockGroupParam);
     Assertions.assertNotNull(result.getData());
+    Assertions.assertEquals(1, result.getData().size(), "Should return a singleton list");
+    BlockGroup returnedGroup = result.getData().get(0);
+    Assertions.assertEquals(1, returnedGroup.getId(), "ID should match the input");
 }
base/src/main/java/com/tinyengine/it/controller/BlockGroupController.java (2)

141-148: Update API documentation to reflect singleton list return.

The implementation correctly returns a singleton list containing the updated block group, but the API documentation could be clearer about this behavior.

     @Operation(summary = "修改区块分组",
             description = "修改区块分组",
             parameters = {
                     @Parameter(name = "id", description = "分组id"),
-                    @Parameter(name = "blockGroups", description = "入参对象")
+                    @Parameter(name = "blockGroup", description = "入参对象")
             },
             responses = {
                     @ApiResponse(responseCode = "200", description = "返回信息",
                             content = @Content(mediaType = "application/json",
-                                    schema = @Schema(implementation = BlockGroup.class))),
+                                    schema = @Schema(implementation = List.class, description = "Returns a singleton list containing the updated BlockGroup"))),
                     @ApiResponse(responseCode = "400", description = "请求失败")}
     )

170-178:

❓ Verification inconclusive

Potential race condition in delete operation.

The current implementation has a potential race condition between checking for existence and performing the deletion. Consider using a transactional approach or implementing optimistic locking.

Here's a script to check if transactions are being used in the service layer:


🏁 Script executed:

#!/bin/bash
# Description: Check for @Transactional annotations in the service implementation
ast-grep --pattern 'class $_ {
  $$$
  @Transactional
  $$$
  deleteBlockGroupById($_) {
    $$$
  }
  $$$
}'

Length of output: 111


Action Required: Address Potential Race Condition in Delete Operation

The deletion method in BlockGroupController.java (lines 170-178) performs an existence check before deleting without any clear transactional safeguards. Our initial automated search for a @Transactional annotation in the service method did not return any confirmations. This raises the risk of a race condition if a concurrent deletion occurs between the check and deletion steps. Please manually verify whether transactional management or optimistic locking is implemented elsewhere in the service layer and consider wrapping the deletion within a transaction if not.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5bae788 and 8a89475.

📒 Files selected for processing (6)
  • base/src/main/java/com/tinyengine/it/common/base/HistoryEntity.java (2 hunks)
  • base/src/main/java/com/tinyengine/it/controller/BlockGroupController.java (4 hunks)
  • base/src/main/java/com/tinyengine/it/service/material/BlockGroupService.java (1 hunks)
  • base/src/main/java/com/tinyengine/it/service/material/impl/BlockGroupServiceImpl.java (4 hunks)
  • base/src/test/java/com/tinyengine/it/controller/BlockGroupControllerTest.java (2 hunks)
  • base/src/test/java/com/tinyengine/it/service/material/impl/BlockGroupServiceImplTest.java (1 hunks)
🔇 Additional comments (3)
base/src/main/java/com/tinyengine/it/common/base/HistoryEntity.java (1)

15-15: LGTM!

Clean addition of the required import for JsonProperty annotation.

base/src/main/java/com/tinyengine/it/service/material/BlockGroupService.java (1)

74-74: Ensure consumers of the revised return type are updated.

Switching from Result<List<BlockGroupDto>> to Result<List<BlockGroup>> affects all callers of this method. Confirm that all references, especially test assertions, have been correctly updated to handle entity objects instead of DTOs.

base/src/main/java/com/tinyengine/it/controller/BlockGroupController.java (1)

115-118: LGTM! Return type change aligns with service layer.

The return type change from DTO to entity object is consistent with the service layer changes.

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

♻️ Duplicate comments (1)
base/src/test/java/com/tinyengine/it/controller/BlockGroupControllerTest.java (1)

89-92: ⚠️ Potential issue

Fix incorrect assertion in delete test.

The test compares a populated block group with an empty one, which will fail. Additionally, it should verify the success of the delete operation.

Apply this diff to fix the test:

-BlockGroup resultData = new BlockGroup();
+BlockGroup expectedGroup = new BlockGroup();
+expectedGroup.setId(1);
 
 Result<List<BlockGroup>> result = blockGroupController.deleteBlockGroups(1);
-Assertions.assertEquals(resultData, result.getData().get(0));
+Assertions.assertNotNull(result, "Result should not be null");
+Assertions.assertNotNull(result.getData(), "Result data should not be null");
+Assertions.assertEquals(1, result.getData().size(), "Should return exactly one block group");
+Assertions.assertEquals(expectedGroup.getId(), result.getData().get(0).getId(), 
+    "Deleted block group should have the expected ID");
+// Verify that the delete operation was successful
+Assertions.assertEquals(0, blockGroupService.findBlockGroupById(1), 
+    "Block group should be deleted");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a89475 and baa4eeb.

📒 Files selected for processing (2)
  • base/src/main/java/com/tinyengine/it/common/base/HistoryEntity.java (2 hunks)
  • base/src/test/java/com/tinyengine/it/controller/BlockGroupControllerTest.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • base/src/main/java/com/tinyengine/it/common/base/HistoryEntity.java

zhangjuncao
zhangjuncao previously approved these changes Feb 13, 2025
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: 5

🧹 Nitpick comments (1)
base/src/main/java/com/tinyengine/it/service/material/impl/BlockGroupServiceImpl.java (1)

46-266: Extract duplicate version setting logic into a helper method.

The version setting logic is duplicated between findBlockGroupById and getBlockGroupByIdsOrAppId. Consider extracting it into a helper method to improve maintainability.

Add a helper method:

+/**
+ * Sets the current version for blocks in a block group based on their carrier relations.
+ *
+ * @param blockGroup The block group containing blocks to update
+ * @param hostId The ID of the host (block group)
+ */
+private void setBlockVersions(BlockGroup blockGroup, Integer hostId) {
+    if (blockGroup == null || blockGroup.getBlocks().isEmpty()) {
+        return;
+    }
+
+    List<Integer> blockIds = blockGroup.getBlocks().stream()
+        .map(Block::getId)
+        .collect(Collectors.toList());
+
+    BlockCarriersRelation queryParam = new BlockCarriersRelation();
+    queryParam.setHostId(hostId);
+    queryParam.setHostType(Enums.BlockGroup.BLOCK_GROUP.getValue());
+    queryParam.setBlockIds(blockIds);
+
+    Map<Integer, String> blockVersions = blockCarriersRelationMapper
+        .queryBlockCarriersRelationByCondition(queryParam).stream()
+        .collect(Collectors.toMap(
+            BlockCarriersRelation::getBlockId,
+            BlockCarriersRelation::getVersion,
+            (v1, v2) -> v1
+        ));
+
+    blockGroup.getBlocks().forEach(block ->
+        block.setCurrentVersion(blockVersions.get(block.getId())));
+}

Then use it in both methods:

public BlockGroup findBlockGroupById(@Param("id") Integer id) {
    BlockGroup blockGroupResult = blockGroupMapper.queryBlockGroupAndBlockById(id, null, DEFAULT_USER_ID);
-    // ... version setting logic ...
+    setBlockVersions(blockGroupResult, id);
    return blockGroupResult;
}

public List<BlockGroup> getBlockGroupByIdsOrAppId(...) {
    // ... existing logic ...
    for (BlockGroup blockGroupTemp : blockGroupsListResult) {
-        // ... version setting logic ...
+        setBlockVersions(blockGroupTemp, blockGroupTemp.getId());
    }
    return blockGroupsListResult;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between baa4eeb and 654da8b.

📒 Files selected for processing (4)
  • .github/workflows/checkstyle.yml (1 hunks)
  • base/src/main/java/com/tinyengine/it/service/material/impl/BlockGroupServiceImpl.java (4 hunks)
  • base/src/test/java/com/tinyengine/it/controller/BlockGroupControllerTest.java (3 hunks)
  • base/src/test/java/com/tinyengine/it/service/material/impl/BlockGroupServiceImplTest.java (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • base/src/test/java/com/tinyengine/it/controller/BlockGroupControllerTest.java
  • base/src/test/java/com/tinyengine/it/service/material/impl/BlockGroupServiceImplTest.java
🔇 Additional comments (1)
.github/workflows/checkstyle.yml (1)

13-13: ⚠️ Potential issue

❌ Incorrect review comment

Verify Ubuntu runner version.

The workflow specifies Ubuntu 24.04 which is not yet released. This could cause workflow failures.

Apply this diff to use a stable Ubuntu version:

-    runs-on: ubuntu-24.04
+    runs-on: ubuntu-22.04

🌐 Web query:

What is the latest stable version of Ubuntu available in GitHub Actions runners?

💡 Result:

The latest stable version of Ubuntu available in GitHub Actions runners as of February 2025 is Ubuntu 24.04 LTS (Noble Numbat)[2][5][9]. This became the default image for ubuntu-latest labels following a phased rollout that started in September 2024[9].

Key details:

  • YAML labels: ubuntu-latest or explicit ubuntu-24.04[5]
  • Migration timeline:
    • Announced GA on September 25, 2024[9]
    • Full migration completed by January 17, 2025[8]
  • Previous versions still available but deprecated:
    • Ubuntu 22.04 (explicitly via ubuntu-22.04 label)[5]
    • Ubuntu 20.04 (being phased out by April 1, 2025)[4]

The image includes kernel version 6.5.0-1025-azure and systemd 249.11-0ubuntu3.12[6]. Users should update workflows from older Ubuntu versions like ubuntu-20.04 before April 2025 to avoid disruptions[4].

Citations:


Ubuntu 24.04 is now the correct and supported runner version.

The web query confirms that as of February 2025, Ubuntu 24.04 LTS is the latest stable version available for GitHub Actions and has been fully rolled out. Therefore, no changes are necessary in the workflow file.

  • File: .github/workflows/checkstyle.yml, line 13
  • Remove the suggestion to downgrade to Ubuntu 22.04.

Likely an incorrect or invalid review comment.

@lu-yg lu-yg merged commit 0d2c0af into opentiny:develop Feb 13, 2025
1 check passed
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