Skip to content

Refactor Boilerplate http client pipeline (#9966)#9967

Merged
msynk merged 1 commit intobitfoundation:developfrom
yasmoradi:9966
Feb 20, 2025
Merged

Refactor Boilerplate http client pipeline (#9966)#9967
msynk merged 1 commit intobitfoundation:developfrom
yasmoradi:9966

Conversation

@yasmoradi
Copy link
Member

@yasmoradi yasmoradi commented Feb 20, 2025

closes #9966
closes #9959

@yasmoradi yasmoradi requested a review from msynk February 20, 2025 15:34
@coderabbitai
Copy link

coderabbitai bot commented Feb 20, 2025

Walkthrough

The changes reinstate and adjust key functionality across several projects. The push notification subscription in the ClientAppCoordinator is re-enabled by uncommenting its registration in the PropagateUserId method. Multiple service configuration files have been updated to replace direct HttpClientHandler registrations with retrieval via keyed HttpMessageHandler services. Additionally, the HTTP request version is now set to HTTP/3.0 in the RequestHeadersDelegatingHandler, and HTTP client configurations across Maui, Web, Windows, and Server projects have been enhanced with updated connection and TLS settings.

Changes

File(s) Change Summary
.../Client/Boilerplate.Client.Core/Components/ClientAppCoordinator.cs Re-enabled push notification subscription in PropagateUserId under conditional notifications.
.../Client/Boilerplate.Client.Core/Extensions/IClientCoreServiceCollectionExtensions.cs Removed direct HttpClientHandler registration; replaced with GetRequiredKeyedService<HttpMessageHandler>("PrimaryHttpMessageHandler") for flexible handler retrieval.
.../Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/RequestHeadersDelegatingHandler.cs Added using System.Net and set request.Version to HttpVersion.Version30 in SendAsync for HTTP/3.0 support.
.../Client/Boilerplate.Client.Maui/MauiProgram.Services.cs, .../Client/Boilerplate.Client.Web/Program.Services.cs, .../Client/Boilerplate.Client.Windows/Program.Services.cs, .../Server/Boilerplate.Server.Web/Program.Services.cs Updated service registration: registered scoped HttpClient with DefaultVersionPolicy=RequestVersionOrLower; added keyed scoped HttpMessageHandler (using SocketsHttpHandler or HttpClientHandler) with enhanced connection, TLS, and multiple HTTP/2/3 connections settings; improved readability in client BaseAddress assignment and removed redundant conditional directives.

Sequence Diagram(s)

sequenceDiagram
    participant CA as ClientAppCoordinator
    participant PNS as PushNotificationService

    CA->>PNS: PropagateUserId(userId)
    PNS-->>CA: Subscribe(userId) confirmed
Loading
sequenceDiagram
    participant App as Application Startup
    participant DI as Dependency Injection Container
    participant HMH as HttpMessageHandler (Keyed Service)
    participant HC as HttpClient

    App->>DI: ConfigureServices (Register HttpClient & HttpMessageHandler)
    DI->>DI: Register key "PrimaryHttpMessageHandler"
    HC->>DI: Resolve HttpMessageHandler via key "PrimaryHttpMessageHandler"
    DI-->>HC: Return configured HMH (SocketsHttpHandler/HttpClientHandler)
Loading

Poem

I'm a rabbit leaping with glee,
Code changes hop in perfect harmony.
Push notifications now bounce with cheer,
HTTP handlers in line, oh so clear.
With TLS and settings crisp like a spring,
My little paws tap to the code they bring.
🐇✨


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/ClientAppCoordinator.cs (1)

143-146: Consider adding unsubscription logic and deduplication.

The push notification subscription could benefit from:

  1. Unsubscribing from previous subscription before creating a new one to prevent potential duplicate subscriptions.
  2. Deduplication logic to avoid unnecessary resubscriptions when the user ID hasn't changed.
 //#if (notification == true)
+            if (isAuthenticated)
+            {
+                await pushNotificationService.Unsubscribe(CurrentCancellationToken);
                await pushNotificationService.Subscribe(CurrentCancellationToken);
+            }
 //#endif
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Web/Program.Services.cs (1)

37-37: Consider using SocketsHttpHandler for consistency.

HttpClientHandler is used here while other platforms use SocketsHttpHandler. For consistency and better performance, consider using SocketsHttpHandler with HTTP/2 and HTTP/3 support.

-services.AddKeyedScoped<HttpMessageHandler, HttpClientHandler>("PrimaryHttpMessageHandler");
+services.AddKeyedScoped<HttpMessageHandler, SocketsHttpHandler>("PrimaryHttpMessageHandler", (sp, key) => new()
+{
+    EnableMultipleHttp2Connections = true,
+    EnableMultipleHttp3Connections = true,
+    PooledConnectionLifetime = TimeSpan.FromMinutes(15),
+    AutomaticDecompression = System.Net.DecompressionMethods.All
+});
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Maui/MauiProgram.Services.cs (1)

36-50: Consider extracting shared HTTP client configuration.

The HTTP client configuration is identical to the Windows implementation. Consider extracting this into a shared extension method to reduce code duplication.

Create a new extension method in a shared location:

public static class HttpClientConfigurationExtensions
{
    public static SocketsHttpHandler CreateDefaultHandler()
    {
        return new()
        {
            EnableMultipleHttp2Connections = true,
#if NET9_0
            EnableMultipleHttp3Connections = true,
#endif
            PooledConnectionLifetime = TimeSpan.FromMinutes(15),
            AutomaticDecompression = System.Net.DecompressionMethods.All,
            SslOptions = new()
            {
                EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13
            }
        };
    }
}

Then simplify both Windows and Maui implementations:

-services.AddKeyedScoped<HttpMessageHandler, SocketsHttpHandler>("PrimaryHttpMessageHandler", (sp, key) => new()
-{
-    EnableMultipleHttp2Connections = true,
-    EnableMultipleHttp3Connections = true,
-    PooledConnectionLifetime = TimeSpan.FromMinutes(15),
-    AutomaticDecompression = System.Net.DecompressionMethods.All,
-    SslOptions = new()
-    {
-        EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13
-    }
-});
+services.AddKeyedScoped<HttpMessageHandler, SocketsHttpHandler>("PrimaryHttpMessageHandler", 
+    (sp, key) => HttpClientConfigurationExtensions.CreateDefaultHandler());
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Extensions/IClientCoreServiceCollectionExtensions.cs (1)

90-93: Good refactoring to use keyed service for HttpMessageHandler!

The change from direct HttpClientHandler registration to keyed service retrieval provides better flexibility and consistency with server-side configuration.

Consider adding a code comment explaining the keyed service pattern, similar to the existing comment about the handler chain:

 services.AddScoped(serviceProvider =>
 {
+    // Retrieve the primary HTTP message handler (SocketsHttpHandler/HttpClientHandler) from keyed services
+    // This allows for different implementations in various environments (e.g., Test Host for integration tests)
     var transportHandler = serviceProvider.GetRequiredKeyedService<HttpMessageHandler>("PrimaryHttpMessageHandler");
     var constructedHttpMessageHandler = serviceProvider.GetRequiredService<HttpMessageHandlersChainFactory>().Invoke(transportHandler);
     return constructedHttpMessageHandler;
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e621bf2 and 7136ccc.

📒 Files selected for processing (7)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/ClientAppCoordinator.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Extensions/IClientCoreServiceCollectionExtensions.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Services/HttpMessageHandlers/RequestHeadersDelegatingHandler.cs (2 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Maui/MauiProgram.Services.cs (3 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Web/Program.Services.cs (1 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Windows/Program.Services.cs (3 hunks)
  • src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Web/Program.Services.cs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (4)
src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Core/Components/ClientAppCoordinator.cs (1)

143-146: LGTM! Push notification subscription re-enabled.

The subscription is properly placed after SignalR initialization, wrapped in the correct conditional compilation directive, and protected by error handling.

src/Templates/Boilerplate/Bit.Boilerplate/src/Client/Boilerplate.Client.Windows/Program.Services.cs (1)

32-46: Well-configured HTTP client with modern security and performance settings!

The configuration includes:

  • Multiple HTTP/2 and HTTP/3 connections for improved performance
  • Connection pooling with 15-minute lifetime
  • Modern TLS protocols (1.2 and 1.3)
  • Automatic compression
src/Templates/Boilerplate/Bit.Boilerplate/src/Server/Boilerplate.Server.Web/Program.Services.cs (2)

125-126: LGTM! Enhanced HTTP version negotiation.

The addition of DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower improves HTTP version negotiation by allowing graceful fallback to lower versions when needed.


160-168:

Details

❓ Verification inconclusive

Excellent choice of SocketsHttpHandler with enhanced connection settings!

The configuration enables multiple HTTP/2 connections and conditionally supports HTTP/3, which can significantly improve performance for concurrent requests.

Let's verify the framework version and HTTP/3 support:


🏁 Script executed:

#!/bin/bash
# Check .NET SDK version and HTTP/3 support
dotnet --version

Length of output: 115


🌐 Web query:

What are the minimum requirements for HTTP/3 support in .NET?

💡 Result:

To enable HTTP/3 support in .NET applications, specific requirements must be met depending on the target platform and .NET version:

.NET Version Requirements

  • Full support starts with ASP.NET Core 7.0+ (no longer a preview feature)[1][2][3].
  • Preview functionality was available in ASP.NET Core 6.0 but required manual configuration via runtime flags[1][4].

Operating System Requirements

Platform Requirements
Windows - Windows 11 Build 22000+ or Windows Server 2022
- TLS 1.3+ connection[2][3][9]
Linux - libmsquic package installed (version 1.9.x for .NET 6 compatibility)
- TLS 1.3+[2][3][9]
macOS Not currently supported[2][3]

Additional Requirements

  1. HTTPS Enforcement:
    HTTP/3 requires HTTPS to be enabled on Kestrel endpoints[2][3]:

    listenOptions.UseHttps();
  2. Protocol Configuration:
    Explicitly enable HTTP/3 in Kestrel alongside fallback protocols:

    options.ListenAnyIP(5001, listenOptions => 
    {
        listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
    });
  3. Client Configuration:
    For HttpClient to use HTTP/3:

    var client = new HttpClient 
    { 
        DefaultRequestVersion = HttpVersion.Version30,
        DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher
    };

Platform-Specific Notes

  • Linux: Install libmsquic via Microsoft's package repository:
    apt install libmsquic=1.9*
  • Legacy .NET 6: Requires runtime flag System.Net.SocketsHttpHandler.Http3Support=true in project file or environment variables[4][6].

Applications should always maintain backward compatibility with HTTP/1.1 and HTTP/2 due to uneven client/server support for HTTP/3[1][2].

Citations:


Optimize HTTP Connection Settings – Please Verify HTTP/3 Requirements

Excellent use of SocketsHttpHandler to boost HTTP/2 and conditionally enable HTTP/3 connections! The configuration looks solid; however, note that the automated check for the .NET SDK version returned “dotnet: command not found.” Please ensure:

  • Your deployment environment has a supported .NET runtime (ideally ASP.NET Core 7.0+ for full HTTP/3 support or the necessary manual configurations in earlier versions).
  • HTTPS is properly enforced and any platform-specific HTTP/3 prerequisites (such as required OS or library installations) are met.

Please manually verify your .NET installation and HTTP/3 support based on Microsoft’s HTTP/3 documentation.

@msynk msynk merged commit 90298bc into bitfoundation:develop Feb 20, 2025
3 checks passed
@yasmoradi yasmoradi deleted the 9966 branch February 20, 2025 17:03
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.

Boilerplate project template's http client pipeline needs improvements Boilerplate project template ObjectDisposedException in Android clients

2 participants