Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented Jun 20, 2025

Link issues

fixes #6261

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

Enable FixLengthDataPackageHandler to iteratively process all complete fixed-length packages from incoming streams and extend its unit test to validate multiple consecutive callbacks

New Features:

  • Handle multiple concatenated fixed-length packages in a single receive call within FixLengthDataPackageHandler

Bug Fixes:

  • Fix inability to process more than one sticky package per receive in FixLengthDataPackageHandler

Tests:

  • Revise FixLengthDataPackageHandler_Sticky unit test to simulate and assert three back-to-back package receptions, update mock payloads and timing

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

sourcery-ai bot commented Jun 20, 2025

Reviewer's Guide

Refactor the fixed-length data package handler to loop through and dispatch multiple complete packages per receive call, replacing the previous buffer concatenation and slicing logic, and adjust unit tests to simulate and assert reception of multiple sequential packages with updated payloads and timings.

Sequence diagram for handling multiple sticky packages in FixLengthDataPackageHandler.ReceiveAsync

sequenceDiagram
    participant Client
    participant FixLengthDataPackageHandler
    participant ReceivedCallBack

    Client->>FixLengthDataPackageHandler: ReceiveAsync(data)
    loop While data contains at least one full package
        FixLengthDataPackageHandler->>FixLengthDataPackageHandler: Copy segment to buffer
        FixLengthDataPackageHandler->>FixLengthDataPackageHandler: Update _receivedLength
        alt _receivedLength == length
            FixLengthDataPackageHandler->>ReceivedCallBack: await ReceivedCallBack(_data)
            FixLengthDataPackageHandler->>FixLengthDataPackageHandler: Reset _receivedLength
        end
        FixLengthDataPackageHandler->>FixLengthDataPackageHandler: Slice data for next package
    end
Loading

Class diagram for updated FixLengthDataPackageHandler

classDiagram
    class DataPackageHandlerBase {
        <<abstract>>
        +Task ReceiveAsync(Memory<byte> data)
    }
    class FixLengthDataPackageHandler {
        - int length
        - int _receivedLength
        - byte[] _data
        + Func<byte[], Task>? ReceivedCallBack
        + override Task ReceiveAsync(Memory<byte> data)
    }
    DataPackageHandlerBase <|-- FixLengthDataPackageHandler
Loading

File-Level Changes

Change Details Files
Enable processing of multiple fixed-length packages in a single receive operation
  • Wrap receive logic in a while(data.Length > 0) loop to handle all bytes in a chunk
  • Remove ConcatBuffer and SlicePackage methods in favor of manual slicing and buffer management
  • After copying each segment, update data to the remaining bytes and track received length
  • Reset received length and invoke ReceivedCallBack for each complete package within the loop
src/BootstrapBlazor/Services/TcpSocket/DataPackage/FixLengthDataPackageHandler.cs
Update unit test to cover multiple sequential sticky packages
  • Reduce Task.Delay intervals to speed up test execution
  • Modify sent byte sequences to include a third package
  • Add additional await tcs.Task and assertion for the third received package
test/UnitTest/Services/TcpSocketFactoryTest.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#6261 Support the handling of multiple concatenated fixed-length data packages in a single receive operation.
#6261 Correctly slice and dispatch each complete package when multiple packages are received together.
#6261 Update unit tests to validate the handling of sequential packages.

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

@bb-auto bb-auto bot added this to the 9.7.0 milestone Jun 20, 2025
sourcery-ai[bot]
sourcery-ai bot previously approved these changes Jun 20, 2025
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 - here's some feedback:

  • Refactor the ReceiveAsync loop to use a while (data.Length >= length) pattern for full‐package extraction and then handle any remainder outside the loop to reduce nested conditions.
  • Extract the buffer slicing and concatenation steps into a dedicated helper (e.g. TryExtractPackage) so ReceiveAsync stays concise and avoids duplicated length checks.
  • In the unit test, remove the redundant consecutive await tcs.Task calls and adjust the TaskCompletionSource logic to clearly match each expected callback invocation.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Refactor the ReceiveAsync loop to use a `while (data.Length >= length)` pattern for full‐package extraction and then handle any remainder outside the loop to reduce nested conditions.
- Extract the buffer slicing and concatenation steps into a dedicated helper (e.g. `TryExtractPackage`) so ReceiveAsync stays concise and avoids duplicated length checks.
- In the unit test, remove the redundant consecutive `await tcs.Task` calls and adjust the TaskCompletionSource logic to clearly match each expected callback invocation.

## Individual Comments

### Comment 1
<location> `src/BootstrapBlazor/Services/TcpSocket/DataPackage/FixLengthDataPackageHandler.cs:31` </location>
<code_context>
-        segment.CopyTo(_data[_receivedLength..]);
-
-        if (data.Length > len)
+        while (data.Length > 0)
         {
-            SlicePackage(data, data.Length - len);
</code_context>

<issue_to_address>
Consider refactoring the loop to compute copy lengths once, use a single data slice per iteration, and clearly separate full and partial packet handling.

Here’s a shorter version that keeps the exact behavior but collapses the nested‐ifs into a single loop, does the `Slice` only once per iteration, and makes the “full‐packet vs leftover” logic explicit:

```csharp
public override async Task ReceiveAsync(Memory<byte> data)
{
    data = ConcatBuffer(data);

    while (data.Length > 0)
    {
        // copy up to the remaining bytes needed for one packet
        int needed   = length - _receivedLength;
        int toCopy   = Math.Min(needed, data.Length);
        data.Slice(0, toCopy).CopyTo(_data[_receivedLength..]);
        _receivedLength += toCopy;

        // advance the input buffer
        data = data.Slice(toCopy);

        if (_receivedLength == length)
        {
            // complete packet → callback & reset
            _receivedLength = 0;
            if (ReceivedCallBack != null)
                await ReceivedCallBack(_data);
            // continue to consume any further packets in 'data'
            continue;
        }

        // incomplete packet with leftover input → cache and exit
        if (data.Length > 0)
        {
            SlicePackage(data, data.Length);
        }
        break;
    }
}
```

**What changed**  
- Compute `toCopy = Min(needed, data.Length)` once.  
- Always `data = data.Slice(toCopy)` rather than conditional slices in two places.  
- Split the “packet complete” vs “partial packet” paths into two clear branches.  
- No repeated `segment.Length + length` checks—just one `continue` for full packets, one `break` for leftovers.
</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 (62ed6e6) to head (17abdb7).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #6262   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          711       711           
  Lines        31375     31374    -1     
  Branches      4431      4431           
=========================================
- Hits         31375     31374    -1     
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
Copy link
Member Author

@sourcery-ai review

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> `src/BootstrapBlazor/Services/TcpSocket/DataPackage/FixLengthDataPackageHandler.cs:33` </location>
<code_context>
-
-        // 拷贝数据
-        var len = length - _receivedLength;
-        var segment = data.Length > len ? data[..len] : data;
-        segment.CopyTo(_data[_receivedLength..]);
-
</code_context>

<issue_to_address>
Consider validating that 'len' is always positive.

If '_receivedLength' exceeds 'length', 'len' becomes negative, which can cause a slicing exception. Add a check to ensure 'len' is positive before using it.
</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.

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!


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.

@ArgoZhang ArgoZhang merged commit c2343f5 into main Jun 20, 2025
6 checks passed
@ArgoZhang ArgoZhang deleted the feat-socket branch June 20, 2025 02:20
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(FixLengthDataPackageHandler): support multiple sticky package

2 participants