Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented Jul 2, 2025

Link issues

fixes #6344

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

Add IDataPackageAdapter and DataPackageAdapter to abstract packet assembly, refactor the TCP client to use callback-based data handling, and update the Adapters sample page and mock server to showcase the adapter pattern.

New Features:

  • Introduce IDataPackageAdapter and DataPackageAdapter implementation for assembling and handling fragmented data packages.
  • Add sample code and UI switch in the Adapters component to demonstrate using DataPackageAdapter for fixed-length socket packets.

Enhancements:

  • Refactor TcpSocketClientBase and ITcpSocketClient to remove built-in DataPackageHandler in favor of ReceivedCallBack-driven data processing.
  • Update FixLengthDataPackageHandler to integrate with the new DataPackageAdapter.
  • Modify mock socket server to simulate fragmented packet writes for adapter demonstration.

Documentation:

  • Enrich the Adapters sample page with inline documentation, code snippets, and a toggle for DataPackageAdapter usage.

@bb-auto bb-auto bot added the documentation Improvements or additions to documentation label Jul 2, 2025
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jul 2, 2025

Reviewer's Guide

This PR introduces a new DataPackageAdapter and interface, refactors the TCP socket client to remove built-in package handling in favor of the adapter pattern, updates the sample component and UI to demonstrate toggling and using the adapter for fixed-length data packets, simulates packet fragmentation in the mock server, and refines the IDataPackageHandler interface.

Sequence diagram for data receiving with DataPackageAdapter

sequenceDiagram
    participant Client as TcpSocketClientBase
    participant Adapter as DataPackageAdapter
    participant Handler as FixLengthDataPackageHandler
    participant UI as UI/Log
    Client->>Adapter: OnReceivedAsync(data)
    Adapter->>Handler: ReceiveAsync(data)
    Handler->>Adapter: ReceivedCallBack(data) (when complete packet)
    Adapter->>UI: ReceivedCallBack(data)
Loading

Class diagram for DataPackageAdapter and related interfaces

classDiagram
    class IDataPackageHandler {
        +ValueTask<ReadOnlyMemory<byte>> SendAsync(ReadOnlyMemory<byte> data, CancellationToken token)
        +ValueTask ReceiveAsync(ReadOnlyMemory<byte> data, CancellationToken token)
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
    }
    class IDataPackageAdapter {
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
        +IDataPackageHandler? DataPackageHandler
        +ValueTask ReceiveAsync(ReadOnlyMemory<byte> data, CancellationToken token)
    }
    class DataPackageAdapter {
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
        +IDataPackageHandler? DataPackageHandler
        +ValueTask ReceiveAsync(ReadOnlyMemory<byte> data, CancellationToken token)
        -ValueTask OnHandlerReceivedCallBack(ReadOnlyMemory<byte> data)
    }
    IDataPackageAdapter <|.. DataPackageAdapter
    IDataPackageHandler <.. DataPackageAdapter: uses
    IDataPackageHandler <.. IDataPackageAdapter: uses
Loading

Class diagram for refactored TcpSocketClientBase

classDiagram
    class ITcpSocketClient {
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
        +ValueTask<bool> SendAsync(ReadOnlyMemory<byte> data, CancellationToken token)
        +ValueTask ReceiveAsync(Memory<byte> buffer, CancellationToken token)
        +ValueTask CloseAsync()
        +ValueTask DisposeAsync()
    }
    class TcpSocketClientBase {
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
        +ValueTask<bool> SendAsync(ReadOnlyMemory<byte> data, CancellationToken token)
        +ValueTask ReceiveAsync(Memory<byte> buffer, CancellationToken token)
        +ValueTask CloseAsync()
        +ValueTask DisposeAsync()
    }
    ITcpSocketClient <|.. TcpSocketClientBase
Loading

File-Level Changes

Change Details Files
Introduce DataPackageAdapter and adapter interface
  • Add DataPackageAdapter class with ReceiveAsync and callback handling
  • Define IDataPackageAdapter interface
  • Remove old DataPackageHandler integration from client base
  • Integrate adapter into sample code (instantiation and callbacks)
src/BootstrapBlazor/Services/TcpSocket/DataPackage/DataPackageAdapter.cs
src/BootstrapBlazor/Services/TcpSocket/DataPackage/IDataPackageAdapter.cs
src/BootstrapBlazor.Server/Components/Samples/Sockets/Adapters.razor.cs
src/BootstrapBlazor.Server/Components/Samples/Sockets/Adapters.razor
Refactor TcpSocketClientBase and ITcpSocketClient to streamline callbacks
  • Remove DataPackageHandler property and SetDataHandler method
  • Eliminate handler invocation in SendAsync and Receive loops
  • Rely solely on ReceivedCallBack for incoming data
src/BootstrapBlazor/Services/TcpSocket/TcpSocketClientBase.cs
src/BootstrapBlazor/Services/TcpSocket/ITcpSocketClient.cs
Refine sample component logic for sending/receiving
  • Add OnReceivedAsync to route data through adapter or direct log
  • Implement UpdateReceiveLog to format and limit log entries
  • Improve send logging with success/failure state
src/BootstrapBlazor.Server/Components/Samples/Sockets/Adapters.razor.cs
Enhance sample UI and documentation
  • Add switch control to toggle adapter usage
  • Embed code snippet and explanatory paragraph
  • Introduce HeadContent style for label width
src/BootstrapBlazor.Server/Components/Samples/Sockets/Adapters.razor
Simulate packet fragmentation in mock server
  • Split header and body writes around an artificial delay
  • Use Encoding in server for data writes
src/BootstrapBlazor.Server/Services/MockCustomProtocalSocketServerService.cs
Update IDataPackageHandler interface documentation
  • Revise ReceiveAsync signature and remarks
  • Adjust return type semantics to boolean status
src/BootstrapBlazor/Services/TcpSocket/DataPackage/IDataPackageHandler.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#6344 Add sample code demonstrating the use of DataPackageAdapter.

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.8.0 milestone Jul 2, 2025
@ArgoZhang ArgoZhang merged commit 1dd1e19 into main Jul 2, 2025
3 of 4 checks passed
@ArgoZhang ArgoZhang deleted the refactor-socket branch July 2, 2025 11:40
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/DataPackageAdapter.cs:25` </location>
<code_context>
+    /// <summary>
+    /// <inheritdoc/>
+    /// </summary>
+    public IDataPackageHandler? DataPackageHandler { get; set; }
+
+    /// <summary>
</code_context>

<issue_to_address>
DataPackageHandler is settable on the adapter, but only gettable on the interface.

This inconsistency may confuse consumers who expect to set DataPackageHandler via the interface.
</issue_to_address>

### Comment 2
<location> `src/BootstrapBlazor/Services/TcpSocket/DataPackage/DataPackageAdapter.cs:15` </location>
<code_context>
+/// common methods for sending, receiving, and handling data packages, as well as a property for accessing the
+/// associated data package handler. Derived classes should override the virtual methods to provide specific behavior
+/// for handling data packages.</remarks>
+public class DataPackageAdapter : IDataPackageAdapter
+{
+    /// <summary>
</code_context>

<issue_to_address>
Consider simplifying callback assignment and method logic by wiring the handler callback in the setter and streamlining ReceiveAsync and the protected callback method.

Here’s one way to keep exactly the same behavior but collapse the two-step “hook up callback on first receive” into a single, simpler setter and eliminate the nested null‐checks in `ReceiveAsync`:

```csharp
public class DataPackageAdapter : IDataPackageAdapter
{
    public Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack { get; set; }

    private IDataPackageHandler? _handler;
    public IDataPackageHandler? DataPackageHandler
    {
        get => _handler;
        set
        {
            _handler = value;
            if (_handler != null)
            {
                // Wire up once at assignment time
                _handler.ReceivedCallBack = OnHandlerReceivedCallBack;
            }
        }
    }

    public virtual ValueTask ReceiveAsync(ReadOnlyMemory<byte> data, CancellationToken token = default)
    {
        // Single-line forward, no extra async state machine if handler is null
        if (DataPackageHandler is null)
            return default;
        return DataPackageHandler.ReceiveAsync(data, token);
    }

    protected virtual ValueTask OnHandlerReceivedCallBack(ReadOnlyMemory<byte> data)
    {
        // Null-conditional invoke
        return ReceivedCallBack != null
            ? ReceivedCallBack(data)
            : default;
    }
}
```

Benefits:

- You assign the handler’s callback exactly once in the setter instead of on every receive.
- `ReceiveAsync` becomes a single-line forward, avoiding nested `if`/`await` and the extra generated state machine when there’s no handler.
- The protected callback leverages a null‐conditional return to remove the `async`/`await` boilerplate.
</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.

/// <summary>
/// <inheritdoc/>
/// </summary>
public IDataPackageHandler? DataPackageHandler { get; set; }
Copy link
Contributor

Choose a reason for hiding this comment

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

nitpick: DataPackageHandler is settable on the adapter, but only gettable on the interface.

This inconsistency may confuse consumers who expect to set DataPackageHandler via the interface.

/// common methods for sending, receiving, and handling data packages, as well as a property for accessing the
/// associated data package handler. Derived classes should override the virtual methods to provide specific behavior
/// for handling data packages.</remarks>
public class DataPackageAdapter : IDataPackageAdapter
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (complexity): Consider simplifying callback assignment and method logic by wiring the handler callback in the setter and streamlining ReceiveAsync and the protected callback method.

Here’s one way to keep exactly the same behavior but collapse the two-step “hook up callback on first receive” into a single, simpler setter and eliminate the nested null‐checks in ReceiveAsync:

public class DataPackageAdapter : IDataPackageAdapter
{
    public Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack { get; set; }

    private IDataPackageHandler? _handler;
    public IDataPackageHandler? DataPackageHandler
    {
        get => _handler;
        set
        {
            _handler = value;
            if (_handler != null)
            {
                // Wire up once at assignment time
                _handler.ReceivedCallBack = OnHandlerReceivedCallBack;
            }
        }
    }

    public virtual ValueTask ReceiveAsync(ReadOnlyMemory<byte> data, CancellationToken token = default)
    {
        // Single-line forward, no extra async state machine if handler is null
        if (DataPackageHandler is null)
            return default;
        return DataPackageHandler.ReceiveAsync(data, token);
    }

    protected virtual ValueTask OnHandlerReceivedCallBack(ReadOnlyMemory<byte> data)
    {
        // Null-conditional invoke
        return ReceivedCallBack != null
            ? ReceivedCallBack(data)
            : default;
    }
}

Benefits:

  • You assign the handler’s callback exactly once in the setter instead of on every receive.
  • ReceiveAsync becomes a single-line forward, avoiding nested if/await and the extra generated state machine when there’s no handler.
  • The protected callback leverages a null‐conditional return to remove the async/await boilerplate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

doc(IDataPackageAdapter): add DataPackageAdapter sample code

2 participants