Skip to content

feat(TcpSocket): remove SetDataPackageAdapter method#550

Merged
ArgoZhang merged 10 commits intomasterfrom
refactor-socket
Aug 27, 2025
Merged

feat(TcpSocket): remove SetDataPackageAdapter method#550
ArgoZhang merged 10 commits intomasterfrom
refactor-socket

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented Aug 27, 2025

Link issues

fixes #549

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

Remove SetDataPackageAdapter methods in favor of AddDataPackageAdapter overloads, add support for multiple adapters and generic callbacks via caching, and improve data conversion error handling

New Features:

  • Introduce unified AddDataPackageAdapter extension methods and remove all SetDataPackageAdapter overloads
  • Support registering multiple data package adapters and generic entity callbacks via a new EntityCache

Enhancements:

  • Rename internal adapter cache from _cache to Cache and restructure callback registration with local delegates
  • Enhance DataConverter.TryConvertTo to catch exceptions and safely return default on parse errors

Tests:

  • Update unit tests to replace SetDataPackageAdapter calls with the new AddDataPackageAdapter methods

Copilot AI review requested due to automatic review settings August 27, 2025 07:22
@bb-auto bb-auto Bot added the enhancement New feature or request label Aug 27, 2025
@bb-auto bb-auto Bot added this to the v9.2.0 milestone Aug 27, 2025
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Aug 27, 2025

Reviewer's Guide

This PR removes the legacy SetDataPackageAdapter API in favor of unified AddDataPackageAdapter overloads, refactors the internal caching and callback registration logic, and enhances data conversion error handling.

File-Level Changes

Change Details Files
Removed SetDataPackageAdapter methods and replaced them with AddDataPackageAdapter overloads
  • Deleted all SetDataPackageAdapter extensions
  • Renamed various SetDataPackageAdapter calls to AddDataPackageAdapter
  • Updated test cases to call AddDataPackageAdapter
ITcpSocketClientExtensions.cs
TcpSocketFactoryTest.cs
Refactored adapter callback caching and registration
  • Renamed private _cache field to Cache
  • Introduced EntityCache for generic callbacks
  • Changed registration to store ReceivedCallback lambdas
  • Updated removal logic to use Cache and EntityCache
ITcpSocketClientExtensions.cs
Streamlined callback delegates to named ReceivedCallback lambdas
  • Replaced anonymous cb functions with ReceivedCallback async lambdas
  • Centralized adapter.HandlerAsync invocation
  • Simplified adapter.ReceivedCallBack assignments
ITcpSocketClientExtensions.cs
Enhanced TryConvertTo with exception safety and clearer flow
  • Wrapped entity creation and parsing in try-catch
  • Initialized return flag and entity to default
  • Cleaned up attribute lookup formatting
DataConverter.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#549 Remove the SetDataPackageAdapter method from the TcpSocket extension codebase.
#549 Update all usages and references of SetDataPackageAdapter to use AddDataPackageAdapter or equivalent methods.

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
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR removes the SetDataPackageAdapter method from the TcpSocket library and replaces it with AddDataPackageAdapter methods. The main purpose is to change from a "set" paradigm that clears existing adapters to an "add" paradigm that accumulates adapters, allowing multiple data package adapters to be registered.

  • Removed SetDataPackageAdapter method and its overloads
  • Added corresponding AddDataPackageAdapter methods with similar functionality
  • Updated all test cases to use the new AddDataPackageAdapter methods

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
TcpSocketFactoryTest.cs Updates all test method calls from SetDataPackageAdapter to AddDataPackageAdapter
ITcpSocketClientExtensions.cs Removes SetDataPackageAdapter methods, adds AddDataPackageAdapter methods and improves caching logic
DataConverter.cs Minor code formatting improvements and error handling enhancement

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment thread test/UnitTestTcpSocket/TcpSocketFactoryTest.cs
Copy link
Copy Markdown

@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 there - I've reviewed your changes - here's some feedback:

  • Consider using a thread-safe collection (e.g., ConcurrentDictionary) or adding locks around Cache/EntityCache operations to avoid race conditions when registering/removing adapters concurrently.
  • After removing adapters, you may want to remove the client key when its adapter list becomes empty to prevent memory leaks from unused client entries in Cache and EntityCache.
  • Silently catching all exceptions in DataConverter.TryConvertTo can obscure parsing issues—consider logging or handling specific exceptions so conversion failures are visible during debugging.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider using a thread-safe collection (e.g., ConcurrentDictionary) or adding locks around Cache/EntityCache operations to avoid race conditions when registering/removing adapters concurrently.
- After removing adapters, you may want to remove the client key when its adapter list becomes empty to prevent memory leaks from unused client entries in Cache and EntityCache.
- Silently catching all exceptions in DataConverter.TryConvertTo can obscure parsing issues—consider logging or handling specific exceptions so conversion failures are visible during debugging.

## Individual Comments

### Comment 1
<location> `src/extensions/BootstrapBlazor.TcpSocket/Extensions/ITcpSocketClientExtensions.cs:114` </location>
<code_context>
+        client.AddDataPackageAdapter(new DataPackageAdapter(handler), callback);
     }

+    private static readonly Dictionary<ITcpSocketClient, List<(Func<ReadOnlyMemory<byte>, ValueTask> ReceivedCallback, Delegate EntityCallback)>> EntityCache = [];
+
     /// <summary>
</code_context>

<issue_to_address>
Storing Delegate in EntityCache may introduce type safety risks.

Consider replacing 'Delegate' with a specific delegate type to ensure type safety and reduce the risk of runtime errors.
</issue_to_address>

### Comment 2
<location> `src/extensions/BootstrapBlazor.TcpSocket/Extensions/ITcpSocketClientExtensions.cs:168` </location>
<code_context>
+    {
+        if (EntityCache.TryGetValue(client, out var list))
+        {
+            var items = list.Where(i => i.EntityCallback.Equals(callback)).ToList();
+            foreach (var c in items)
+            {
</code_context>

<issue_to_address>
Using Delegate.Equals for callback matching may not reliably identify the correct callback.

Delegate.Equals may not match callbacks that are functionally identical but not the same instance. Consider using reference equality or another method to ensure accurate callback removal.
</issue_to_address>

### Comment 3
<location> `src/extensions/BootstrapBlazor.Socket/DataConverter/DataConverter.cs:32` </location>
<code_context>
-        entity = ret ? v : default;
+        var ret = false;
+        entity = default;
+        try
+        {
+            var v = CreateEntity();
+            if (Parse(data, v))
+            {
+                entity = v;
+                ret = true;
+            }
+        }
+        catch { }
+
         return ret;
</code_context>

<issue_to_address>
Swallowing all exceptions in TryConvertTo may obscure underlying issues.

Catching all exceptions without logging or handling can hinder debugging and mask critical errors. Please log the exception or catch only specific, expected exception types.
</issue_to_address>

### Comment 4
<location> `test/UnitTestTcpSocket/TcpSocketFactoryTest.cs:500` </location>
<code_context>
         // 设置数据适配器
         var adapter = new DataPackageAdapter(new FixLengthDataPackageHandler(7));
-        client.SetDataPackageAdapter(adapter, buffer =>
+        var callback = new Func<ReadOnlyMemory<byte>, ValueTask>(buffer =>
         {
             // buffer 即是接收到的数据
</code_context>

<issue_to_address>
Consider adding a test for removing a data package adapter after adding it.

Adding a test for adapter removal will confirm that callbacks are not triggered post-removal, validating the new registration and deregistration logic.
</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.

Comment thread test/UnitTestTcpSocket/TcpSocketFactoryTest.cs
@ArgoZhang ArgoZhang closed this Aug 27, 2025
@ArgoZhang ArgoZhang deleted the refactor-socket branch August 27, 2025 07:28
@ArgoZhang ArgoZhang restored the refactor-socket branch August 27, 2025 07:29
@ArgoZhang ArgoZhang reopened this Aug 27, 2025
@ArgoZhang ArgoZhang merged commit b10cb87 into master Aug 27, 2025
1 check passed
@ArgoZhang ArgoZhang deleted the refactor-socket branch August 27, 2025 07:40
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(TcpSocket): remove SetDataPackageAdapter method

2 participants