Skip to content

Commit

Permalink
Move request cloning to a more suitable place
Browse files Browse the repository at this point in the history
  • Loading branch information
Tyrrrz committed Oct 27, 2023
1 parent 397c72e commit 0ce7d53
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
18 changes: 15 additions & 3 deletions YoutubeExplode/Utils/ClientDelegatingHandler.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using YoutubeExplode.Utils.Extensions;

namespace YoutubeExplode.Utils;

// Used to extend an externally provided HttpClient with additional behavior
// Like DelegatingHandler, but wraps an HttpClient instead of an HttpMessageHandler.
// Used to extend an externally provided HttpClient with additional behavior.
internal abstract class ClientDelegatingHandler : HttpMessageHandler
{
private readonly HttpClient _http;
Expand All @@ -19,8 +21,18 @@ protected ClientDelegatingHandler(HttpClient http, bool disposeClient = false)
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken
) =>
await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
)
{
// Clone the request to reset its completion status, which is required
// in order to pass the request from one HttpClient to another.
using var clonedRequest = request.Clone();

return await _http.SendAsync(
clonedRequest,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken
);
}

protected override void Dispose(bool disposing)
{
Expand Down
1 change: 1 addition & 0 deletions YoutubeExplode/Utils/Extensions/HttpExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public static async ValueTask<HttpResponseMessage> HeadAsync(
)
{
using var request = new HttpRequestMessage(HttpMethod.Head, requestUri);

return await http.SendAsync(
request,
HttpCompletionOption.ResponseHeadersRead,
Expand Down
8 changes: 5 additions & 3 deletions YoutubeExplode/YoutubeHttpHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,12 @@ CancellationToken cancellationToken
{
try
{
using var clonedRequest = request.Clone();

var response = HandleResponse(
await base.SendAsync(HandleRequest(clonedRequest), cancellationToken)
await base.SendAsync(
// Request will be cloned by the base handler
HandleRequest(request),
cancellationToken
)
);

// Retry on 5XX errors
Expand Down

0 comments on commit 0ce7d53

Please sign in to comment.