Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented Jun 20, 2025

Link issues

fixes #6263

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Refactor TCP socket client and data package handler APIs to leverage ReadOnlyMemory and ValueTask, aiming to enhance performance and resource efficiency across the implementation and tests.

Enhancements:

  • Refactor TcpSocket client and data package handler interfaces and implementations to use ReadOnlyMemory and ValueTask for improved performance and efficiency.

Tests:

  • Update unit tests to use ReadOnlyMemory and ValueTask in accordance with the refactored interfaces.

@bb-auto bb-auto bot added the enhancement New feature or request label Jun 20, 2025
@bb-auto bb-auto bot added this to the 9.7.0 milestone Jun 20, 2025
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jun 20, 2025

Reviewer's Guide

Refactors TCP socket client and data package handler APIs and implementations from Task/Memory to ValueTask/ReadOnlyMemory for improved performance, updating interfaces, default client, handlers, and unit tests accordingly.

Class diagram for updated ITcpSocketClient and DefaultTcpSocketClient APIs

classDiagram
    class ITcpSocketClient {
        +ValueTask<bool> ConnectAsync(string host, int port, CancellationToken token = default)
        +ValueTask<bool> ConnectAsync(IPEndPoint endPoint, CancellationToken token = default)
        +ValueTask<bool> SendAsync(ReadOnlyMemory<byte> data, CancellationToken token = default)
        +void Dispose()
    }
    class DefaultTcpSocketClient {
        +ValueTask<bool> ConnectAsync(string host, int port, CancellationToken token = default)
        +ValueTask<bool> ConnectAsync(IPEndPoint endPoint, CancellationToken token = default)
        +ValueTask<bool> SendAsync(ReadOnlyMemory<byte> data, CancellationToken token = default)
        -ValueTask ReceiveAsync()
        +void SetDataHandler(IDataPackageHandler handler)
    }
    ITcpSocketClient <|.. DefaultTcpSocketClient
Loading

Class diagram for updated IDataPackageHandler and DataPackageHandlerBase

classDiagram
    class IDataPackageHandler {
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
        +ValueTask<ReadOnlyMemory<byte>> SendAsync(ReadOnlyMemory<byte> data)
        +ValueTask ReceiveAsync(ReadOnlyMemory<byte> data)
    }
    class DataPackageHandlerBase {
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
        +virtual ValueTask<ReadOnlyMemory<byte>> SendAsync(ReadOnlyMemory<byte> data)
        +virtual ValueTask ReceiveAsync(ReadOnlyMemory<byte> data)
        -void SlicePackage(ReadOnlyMemory<byte> buffer, int length)
        -ReadOnlyMemory<byte> ConcatBuffer(ReadOnlyMemory<byte> buffer)
    }
    IDataPackageHandler <|.. DataPackageHandlerBase
Loading

Class diagram for updated DelimiterDataPackageHandler and FixLengthDataPackageHandler

classDiagram
    class DelimiterDataPackageHandler {
        +override ValueTask ReceiveAsync(ReadOnlyMemory<byte> data)
    }
    class FixLengthDataPackageHandler {
        +override ValueTask ReceiveAsync(ReadOnlyMemory<byte> data)
    }
    DataPackageHandlerBase <|-- DelimiterDataPackageHandler
    DataPackageHandlerBase <|-- FixLengthDataPackageHandler
Loading

File-Level Changes

Change Details Files
Migrate public API signatures to ValueTask and ReadOnlyMemory
  • Replace Task, Task<Memory>, Task with ValueTask, ValueTask<ReadOnlyMemory>, ValueTask
  • Change method parameters from Memory to ReadOnlyMemory
  • Update ReceivedCallBack delegate from Func<Memory, Task> to Func<ReadOnlyMemory, ValueTask>
src/BootstrapBlazor/Services/TcpSocket/ITcpSocketClient.cs
src/BootstrapBlazor/Services/TcpSocket/DataPackage/IDataPackageHandler.cs
src/BootstrapBlazor/Services/TcpSocket/DataPackage/DataPackageHandlerBase.cs
Refactor DefaultTcpSocketClient implementation to use ValueTask and ReadOnlyMemory
  • Convert ConnectAsync/SendAsync methods to return ValueTask and accept ReadOnlyMemory
  • Adapt private ReceiveAsync loop to return ValueTask and use ReadOnlyMemory
  • Maintain cancellation token handling with updated method signatures
src/BootstrapBlazor/Services/TcpSocket/DefaultTcpSocketClient.cs
Update data package handlers and mocks to new async and memory types
  • Override SendAsync/ReceiveAsync in FixLengthDataPackageHandler and DelimiterDataPackageHandler to use ValueTask and ReadOnlyMemory
  • Adjust mock handlers (MockSendErrorHandler, MockReceiveErrorHandler) to match new signatures
  • Change internal helper methods to write ReadOnlyMemory blocks
src/BootstrapBlazor/Services/TcpSocket/DataPackage/FixLengthDataPackageHandler.cs
src/BootstrapBlazor/Services/TcpSocket/DataPackage/DelimiterDataPackageHandler.cs
test/UnitTest/Services/TcpSocketFactoryTest.cs
Revise unit tests for ReadOnlyMemory and ValueTask usage
  • Replace Memory initializations with ReadOnlyMemory
  • Update Assert.ThrowsAsync invocations and SendAsync calls to await new ValueTask patterns
  • Remove extraneous blank lines after Dispose calls
test/UnitTest/Services/TcpSocketFactoryTest.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#6263 Improve performance of ITcpSocketClient by using ReadOnlyMemory.

Possibly linked issues


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. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the 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 exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

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
Contributor

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

Hey @ArgoZhang - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `test/UnitTest/Services/TcpSocketFactoryTest.cs:75` </location>
<code_context>
         // 测试未建立连接前调用 SendAsync 方法报异常逻辑
-        var data = new Memory<byte>([1, 2, 3, 4, 5]);
-        var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(data));
+        var data = new ReadOnlyMemory<byte>([1, 2, 3, 4, 5]);
+        var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.SendAsync(data));
         Assert.Equal("TCP Socket is not connected 127.0.0.1:0", ex.Message);
</code_context>

<issue_to_address>
Consider adding tests for empty ReadOnlyMemory<byte> input.

Testing with empty ReadOnlyMemory<byte> will verify that SendAsync and ReceiveAsync handle empty buffers correctly and do not throw unexpected exceptions.

Suggested implementation:

```csharp
        var data = new ReadOnlyMemory<byte>([1, 2, 3, 4, 5]);
        var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.SendAsync(data));
        Assert.Equal("TCP Socket is not connected 127.0.0.1:0", ex.Message);

        // 测试未建立连接前调用 SendAsync 方法,传入空的 ReadOnlyMemory<byte>
        var emptyData = ReadOnlyMemory<byte>.Empty;
        var exEmpty = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.SendAsync(emptyData));
        Assert.Equal("TCP Socket is not connected 127.0.0.1:0", exEmpty.Message);

        // 测试未建立连接前调用 ReceiveAsync 方法,传入空的 Memory<byte>
        var emptyBuffer = Memory<byte>.Empty;
        var exReceive = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.ReceiveAsync(emptyBuffer));
        Assert.Equal("TCP Socket is not connected 127.0.0.1:0", exReceive.Message);
    }

```

```csharp
        var data = new ReadOnlyMemory<byte>([1, 2, 3, 4, 5]);
        var result = await client.SendAsync(data, cst.Token);
        Assert.False(result);

        // 测试取消时传入空的 ReadOnlyMemory<byte>
        var emptyData = ReadOnlyMemory<byte>.Empty;
        var resultEmpty = await client.SendAsync(emptyData, cst.Token);
        Assert.False(resultEmpty);

        // 测试取消时传入空的 Memory<byte> 给 ReceiveAsync
        var emptyBuffer = Memory<byte>.Empty;
        var receiveResult = await client.ReceiveAsync(emptyBuffer, cst.Token);
        Assert.Equal(0, receiveResult);

```
</issue_to_address>

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.

@codecov
Copy link

codecov bot commented Jun 20, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (c2343f5) to head (3fc2e7b).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #6264   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          711       711           
  Lines        31374     31374           
  Branches      4431      4431           
=========================================
  Hits         31374     31374           
Flag Coverage Δ
BB 100.00% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ArgoZhang ArgoZhang merged commit 31a2a95 into main Jun 20, 2025
6 checks passed
@ArgoZhang ArgoZhang deleted the refactor-socket branch June 20, 2025 03:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(ITcpSocketClient): use ReadOnlyMemory improve performance

2 participants