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

feat: 使用cola重构grpc的例子,对cola实践的rpc例子进行补充 #2913

Merged
merged 1 commit into from
Nov 17, 2024

Conversation

KouShenhai
Copy link
Owner

@KouShenhai KouShenhai commented Nov 17, 2024

Sourcery总结

使用Cola框架重构gRPC示例,通过引入新的类来处理和转换用户数据。增强GrpcServerInterceptor以更好地管理跟踪,并更新用户服务以处理不存在的用户。调整log4j2模块的构建依赖。

新功能:

  • 引入新的UserMapper类来处理gRPC调用以检索用户数据。
  • 添加UserConvertor类以在User、UserDO和UserCO对象之间进行转换。
  • 实现UserServiceImpl以通过gRPC提供用户检索功能。

增强:

  • 重构GrpcServerInterceptor以使用新的executeWithTrace方法进行更清晰的跟踪处理。
  • 更新UserServiceImpl以处理用户不存在的情况,返回特定的错误消息。

构建:

  • 在laokou-common-log4j2模块中为jackson-dataformat-xml依赖添加provided范围。
Original summary in English

Summary by Sourcery

Refactor the gRPC example using the Cola framework by introducing new classes for user data handling and conversion. Enhance the GrpcServerInterceptor for better trace management and update the user service to handle non-existent users. Adjust build dependencies for the log4j2 module.

New Features:

  • Introduce a new UserMapper class to handle gRPC calls for user data retrieval.
  • Add UserConvertor class to convert between User, UserDO, and UserCO objects.
  • Implement UserServiceImpl to provide user retrieval functionality via gRPC.

Enhancements:

  • Refactor GrpcServerInterceptor to use a new executeWithTrace method for cleaner trace handling.
  • Update UserServiceImpl to handle cases where a user does not exist, returning a specific error message.

Build:

  • Add a provided scope to the jackson-dataformat-xml dependency in the laokou-common-log4j2 module.

Summary by CodeRabbit

  • New Features

    • Introduced a new user service interface and implementation for improved user data retrieval.
    • Added support for dynamic profile activation in the application configuration.
  • Bug Fixes

    • Enhanced error handling in transaction management to improve clarity and response accuracy.
  • Documentation

    • Updated logging configuration to support dynamic profiles for better environment management.
  • Chores

    • Refactored code for clarity, including renaming classes and methods related to tracing functionality.

Copy link

gitguardian bot commented Nov 17, 2024

⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secret in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
9282265 Triggered Username Password 928729e laokou-sample/laokou-sample-grpc/laokou-sample-grpc-server/src/main/java/org/laokou/app/service/UserServiceImpl.java View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

Copy link

coderabbitai bot commented Nov 17, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces several modifications across multiple files in the laokou project, primarily enhancing dependency management, error handling, and user service functionality. Key changes include updating the scope of a dependency in pom.xml, modifying error message identifiers in exception handling, and transitioning the UserController to a RESTful approach. Additionally, new classes for user data handling and conversion are added, alongside updates to configuration files to support dynamic profile activation.

Changes

File Change Summary
laokou-common/laokou-common-log4j2/pom.xml Updated scope of jackson-dataformat-xml to provided.
laokou-common/laokou-common-mybatis-plus/src/main/java/.../MybatisUtil.java Changed error message key from "S_Datasource_TransactionRolledBack" to "S_DS_TransactionRolledBack".
laokou-common/laokou-common-mybatis-plus/src/main/java/.../TransactionalUtil.java Updated exception message from "S_Datasource_OperationError" to "S_DS_OperationError" in executeInTransaction.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/.../UserController.java Refactored to use UserServiceI, updated method signature for getById to accept @PathVariable("id") Long id.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/.../UserGetQryExe.java Added new class UserGetQryExe with method execute(UserGetQry qry) for user retrieval.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/.../UserServiceImpl.java Introduced UserServiceImpl class implementing UserServiceI, with getById method for user queries.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/.../UserServiceI.java Added new interface UserServiceI with method getById(UserGetQry qry).
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/.../UserGetQry.java Added new class UserGetQry for user query parameters.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/.../UserCO.java Added new DTO class UserCO for user data transfer.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/.../GrpcClientInterceptor.java Renamed inner class WrapperStart to WrapperTraceListener, updated constructor and method references accordingly.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/.../UserConvertor.java Added UserConvertor class with methods for converting between User and UserDO.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/.../UserMapper.java Added UserMapper class for interacting with gRPC user service, including getById(Long id) method.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/.../UserDO.java Added new data object class UserDO for user-related information.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/resources/application.yml Updated to include dynamic profile activation and logging configuration.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-server/src/main/java/.../UserServiceImpl.java Updated getUserById method parameter name from request to qry, added conditional logic for user retrieval.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-server/src/main/java/.../GrpcServerInterceptor.java Introduced executeWithTrace method for managing MDC context, renamed classes for clarity.
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-server/src/main/resources/application.yml Added active profile configuration and updated logging configuration for dynamic profile reference.

Poem

In the code where rabbits play,
Changes hop in bright array.
From gRPC to REST we glide,
User queries now with pride.
With each new class, we build and grow,
A lively dance, our code's new flow! 🐇✨


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.

@KouShenhai KouShenhai merged commit 5414fdc into master Nov 17, 2024
6 of 12 checks passed
Copy link

sourcery-ai bot commented Nov 17, 2024

审核指南由 Sourcery 提供

此 PR 使用 COLA 架构模式重构了 gRPC 示例。主要更改包括重构客户端代码以遵循 COLA 的分层架构、改进错误处理以及增强客户端和服务器拦截器中的跟踪功能。

gRPC 用户检索过程的序列图

sequenceDiagram
    actor User
    participant UserController
    participant UserServiceI
    participant UserGetQryExe
    participant UserMapper
    participant UserServiceGrpc

    User->>UserController: GET /user/{id}
    UserController->>UserServiceI: getById(UserGetQry)
    UserServiceI->>UserGetQryExe: execute(UserGetQry)
    UserGetQryExe->>UserMapper: getById(Long)
    UserMapper->>UserServiceGrpc: getUserById(UserGetQry)
    UserServiceGrpc-->>UserMapper: Result
    UserMapper-->>UserGetQryExe: UserDO
    UserGetQryExe-->>UserServiceI: Result<UserCO>
    UserServiceI-->>UserController: Result<UserCO>
    UserController-->>User: JSON Response
Loading

更新的 gRPC 服务器拦截器的类图

classDiagram
    class GrpcServerInterceptor {
        +<ReqT, RespT> interceptCall(ServerCall<ReqT, RespT>, Metadata, ServerCallHandler<ReqT, RespT>)
    }

    class WrapperTraceListener {
        +WrapperTraceListener(ServerCall<R, S>, ServerCallHandler<R, S>, Metadata, TraceLogV)
        +onMessage(R)
        +onHalfClose()
        +onComplete()
    }

    class Wrapper {
        +Wrapper(ServerCall<R, S>)
    }

    GrpcServerInterceptor --> WrapperTraceListener
    WrapperTraceListener --> Wrapper
    note for WrapperTraceListener "替换 WrapperTrace 并添加 executeWithTrace 方法"
    note for Wrapper "替换 WrapperListener"
Loading

新用户服务实现的类图

classDiagram
    class UserServiceImpl {
        +getById(UserGetQry): Result<UserCO>
    }

    class UserGetQryExe {
        +execute(UserGetQry): Result<UserCO>
    }

    class UserMapper {
        +getById(Long): UserDO
    }

    class UserConvertor {
        +toDataObject(User): UserDO
        +toClientObject(UserDO): UserCO
    }

    UserServiceImpl --> UserGetQryExe
    UserGetQryExe --> UserMapper
    UserMapper --> UserConvertor
    note for UserServiceImpl "实现 UserServiceI 接口"
Loading

文件级更改

更改 详情 文件
重构 gRPC 客户端代码以遵循 COLA 架构
  • 添加 UserServiceI 接口以定义服务契约
  • 实现 UserServiceImpl 作为应用服务层
  • 创建 UserMapper 用于 RPC 通信
  • 添加 UserConvertor 用于对象转换
  • 引入 UserGetQryExe 进行查询处理
  • 添加数据对象 (DO) 和客户端对象 (CO)
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/client/api/UserServiceI.java
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/app/service/UserServiceImpl.java
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/infrastructure/gatewayimpl/rpc/UserMapper.java
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/infrastructure/convertor/UserConvertor.java
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/app/command/query/UserGetQryExe.java
增强 gRPC 拦截器实现
  • 将通用跟踪执行逻辑提取到 executeWithTrace 方法中
  • 重命名类以提高清晰度
  • 使用 lambda 表达式简化跟踪处理代码
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-server/src/main/java/org/laokou/infrastructure/config/GrpcServerInterceptor.java
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/infrastructure/config/GrpcClientInterceptor.java
改进错误处理和响应逻辑
  • 在服务器实现中添加用户存在性检查
  • 更新错误代码以更具体
  • 增强 RPC 调用中的错误消息处理
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-server/src/main/java/org/laokou/app/service/UserServiceImpl.java
laokou-common/laokou-common-mybatis-plus/src/main/java/org/laokou/common/mybatisplus/utils/MybatisUtil.java
laokou-common/laokou-common-mybatis-plus/src/main/java/org/laokou/common/mybatisplus/utils/TransactionalUtil.java

提示和命令

与 Sourcery 互动

  • 触发新审核: 在拉取请求中评论 @sourcery-ai review
  • 继续讨论: 直接回复 Sourcery 的审核评论。
  • 从审核评论生成 GitHub 问题: 通过回复审核评论请求 Sourcery 创建问题。
  • 生成拉取请求标题: 在拉取请求标题中任意位置写 @sourcery-ai 以随时生成标题。
  • 生成拉取请求摘要: 在拉取请求正文中任意位置写 @sourcery-ai summary 以随时生成 PR 摘要。您也可以使用此命令指定摘要插入的位置。

自定义您的体验

访问您的仪表板以:

  • 启用或禁用审核功能,例如 Sourcery 生成的拉取请求摘要、审核指南等。
  • 更改审核语言。
  • 添加、删除或编辑自定义审核说明。
  • 调整其他审核设置。

获取帮助

Original review guide in English

Reviewer's Guide by Sourcery

This PR refactors the gRPC example using the COLA architecture pattern. The main changes include restructuring the client-side code to follow COLA's layered architecture, improving error handling, and enhancing the tracing functionality in both client and server interceptors.

Sequence diagram for gRPC user retrieval process

sequenceDiagram
    actor User
    participant UserController
    participant UserServiceI
    participant UserGetQryExe
    participant UserMapper
    participant UserServiceGrpc

    User->>UserController: GET /user/{id}
    UserController->>UserServiceI: getById(UserGetQry)
    UserServiceI->>UserGetQryExe: execute(UserGetQry)
    UserGetQryExe->>UserMapper: getById(Long)
    UserMapper->>UserServiceGrpc: getUserById(UserGetQry)
    UserServiceGrpc-->>UserMapper: Result
    UserMapper-->>UserGetQryExe: UserDO
    UserGetQryExe-->>UserServiceI: Result<UserCO>
    UserServiceI-->>UserController: Result<UserCO>
    UserController-->>User: JSON Response
Loading

Class diagram for updated gRPC server interceptor

classDiagram
    class GrpcServerInterceptor {
        +<ReqT, RespT> interceptCall(ServerCall<ReqT, RespT>, Metadata, ServerCallHandler<ReqT, RespT>)
    }

    class WrapperTraceListener {
        +WrapperTraceListener(ServerCall<R, S>, ServerCallHandler<R, S>, Metadata, TraceLogV)
        +onMessage(R)
        +onHalfClose()
        +onComplete()
    }

    class Wrapper {
        +Wrapper(ServerCall<R, S>)
    }

    GrpcServerInterceptor --> WrapperTraceListener
    WrapperTraceListener --> Wrapper
    note for WrapperTraceListener "Replaces WrapperTrace and adds executeWithTrace method"
    note for Wrapper "Replaces WrapperListener"
Loading

Class diagram for new User service implementation

classDiagram
    class UserServiceImpl {
        +getById(UserGetQry): Result<UserCO>
    }

    class UserGetQryExe {
        +execute(UserGetQry): Result<UserCO>
    }

    class UserMapper {
        +getById(Long): UserDO
    }

    class UserConvertor {
        +toDataObject(User): UserDO
        +toClientObject(UserDO): UserCO
    }

    UserServiceImpl --> UserGetQryExe
    UserGetQryExe --> UserMapper
    UserMapper --> UserConvertor
    note for UserServiceImpl "Implements UserServiceI interface"
Loading

File-Level Changes

Change Details Files
Refactored gRPC client code to follow COLA architecture
  • Added UserServiceI interface to define service contract
  • Implemented UserServiceImpl as application service layer
  • Created UserMapper for RPC communication
  • Added UserConvertor for object transformations
  • Introduced UserGetQryExe for query handling
  • Added data objects (DO) and client objects (CO)
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/client/api/UserServiceI.java
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/app/service/UserServiceImpl.java
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/infrastructure/gatewayimpl/rpc/UserMapper.java
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/infrastructure/convertor/UserConvertor.java
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/app/command/query/UserGetQryExe.java
Enhanced gRPC interceptor implementation
  • Extracted common trace execution logic into executeWithTrace method
  • Renamed classes for better clarity
  • Simplified trace handling code using lambda expressions
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-server/src/main/java/org/laokou/infrastructure/config/GrpcServerInterceptor.java
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-client/src/main/java/org/laokou/infrastructure/config/GrpcClientInterceptor.java
Improved error handling and response logic
  • Added user existence check in server implementation
  • Updated error codes to be more specific
  • Enhanced error message handling in RPC calls
laokou-sample/laokou-sample-grpc/laokou-sample-grpc-server/src/main/java/org/laokou/app/service/UserServiceImpl.java
laokou-common/laokou-common-mybatis-plus/src/main/java/org/laokou/common/mybatisplus/utils/MybatisUtil.java
laokou-common/laokou-common-mybatis-plus/src/main/java/org/laokou/common/mybatisplus/utils/TransactionalUtil.java

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

@KouShenhai - 我已经审查了你的更改 - 这里有一些反馈:

总体评论

  • 考虑在整个代码库中标准化错误代码格式。目前混合使用了类似 'B_User_NotExist' 和 'S_DS_OperationError' 的格式。建议为所有错误代码选择一种一致的格式。
这是我在审查期间查看的内容
  • 🟡 一般问题:发现2个问题
  • 🟢 安全性:一切看起来都很好
  • 🟢 测试:一切看起来都很好
  • 🟢 复杂性:一切看起来都很好
  • 🟢 文档:一切看起来都很好

Sourcery 对开源项目免费 - 如果你喜欢我们的评论,请考虑分享它们 ✨
帮助我变得更有用!请点击每条评论上的 👍 或 👎,我将使用反馈来改进你的评论。
Original comment in English

Hey @KouShenhai - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider standardizing error code formats across the codebase. Currently mixing formats like 'B_User_NotExist' and 'S_DS_OperationError'. Suggest picking one consistent format for all error codes.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -31,71 +31,70 @@
@Slf4j
public class GrpcServerInterceptor implements ServerInterceptor {

private static void executeWithTrace(TraceLogV traceLog, Runnable action) {
try {
MDCUtil.put(traceLog.traceId(), traceLog.traceId());
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): executeWithTrace 方法在 MDCUtil.put() 的两个参数中都使用了 traceId,应该分别使用 traceId 和 spanId

Original comment in English

issue (bug_risk): The executeWithTrace method is using traceId for both parameters of MDCUtil.put(), which should use traceId and spanId separately

}
else {
throw new SystemException("S_Request_RPCCallFailed",
String.format("RPC调用失败,%s", result.getMsg().split("\\\\")[0]));
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): 使用字符串拆分进行错误消息解析是脆弱的,如果消息格式更改可能会中断

考虑实现一种更健壮的错误处理机制,不依赖于字符串拆分

Original comment in English

issue (bug_risk): Error message parsing using string splitting is fragile and could break if message format changes

Consider implementing a more robust error handling mechanism that doesn't rely on string splitting

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.

1 participant