Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add methods allowing retrieval of HttpRequestMessage from ResilienceContext #5460

Merged
merged 3 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ protected override async ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState
ResilienceContext context,
TState state)
{
if (!context.Properties.TryGetValue(ResilienceKeys.RequestMessage, out var request) || request is null)
HttpRequestMessage? request = context.GetRequestMessage();

if (request is null)
{
Throw.InvalidOperationException("The HTTP request message was not found in the resilience context.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public static IStandardHedgingHandlerBuilder AddStandardHedgingHandler(this IHtt
requestMessage.SetResilienceContext(args.ActionContext);

// replace the request message
args.ActionContext.Properties.Set(ResilienceKeys.RequestMessage, requestMessage);
args.ActionContext.SetRequestMessage(requestMessage);

if (args.PrimaryContext.Properties.TryGetValue(ResilienceKeys.RoutingStrategy, out var routingPipeline))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Microsoft.Extensions.Http.Resilience.Internal;

internal static class ResilienceKeys
{
public static readonly ResiliencePropertyKey<HttpRequestMessage> RequestMessage = new("Resilience.Http.RequestMessage");
public static readonly ResiliencePropertyKey<HttpRequestMessage?> RequestMessage = new("Resilience.Http.RequestMessage");

public static readonly ResiliencePropertyKey<RequestRoutingStrategy> RoutingStrategy = new("Resilience.Http.RequestRoutingStrategy");

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using Microsoft.Extensions.Http.Resilience.Internal;
using Microsoft.Shared.DiagnosticIds;
using Microsoft.Shared.Diagnostics;
using Polly;

namespace Polly;

/// <summary>
/// Provides utility methods for working with <see cref="ResilienceContext"/>.
/// </summary>
[Experimental(diagnosticId: DiagnosticIds.Experiments.Resilience, UrlFormat = DiagnosticIds.UrlFormat)]
public static class HttpResilienceContextExtensions
{
/// <summary>
/// Gets the request message from the <see cref="ResilienceContext"/>.
/// </summary>
/// <param name="context">The resilience context.</param>
/// <returns>
/// The request message.
/// If the request message is not present in the <see cref="ResilienceContext"/> the method returns <see langword="null"/>.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="context"/> is <see langword="null"/>.</exception>
public static HttpRequestMessage? GetRequestMessage(this ResilienceContext context)
{
_ = Throw.IfNull(context);
return context.Properties.GetValue(ResilienceKeys.RequestMessage, default);
}

/// <summary>
/// Sets the request message on the <see cref="ResilienceContext"/>.
/// </summary>
/// <param name="context">The resilience context.</param>
/// <param name="requestMessage">The request message.</param>
/// <exception cref="ArgumentNullException"><paramref name="context"/> is <see langword="null"/>.</exception>
public static void SetRequestMessage(this ResilienceContext context, HttpRequestMessage? requestMessage)
{
_ = Throw.IfNull(context);
context.Properties.Set(ResilienceKeys.RequestMessage, requestMessage);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage

ResilienceContext context = GetOrSetResilienceContext(request, cancellationToken, out bool created);
TrySetRequestMetadata(context, request);
SetRequestMessage(context, request);
context.SetRequestMessage(request);

try
{
Expand Down Expand Up @@ -117,7 +117,7 @@ protected override HttpResponseMessage Send(HttpRequestMessage request, Cancella

ResilienceContext context = GetOrSetResilienceContext(request, cancellationToken, out bool created);
TrySetRequestMetadata(context, request);
SetRequestMessage(context, request);
context.SetRequestMessage(request);

try
{
Expand Down Expand Up @@ -165,11 +165,8 @@ private static void TrySetRequestMetadata(ResilienceContext context, HttpRequest
}
}

private static void SetRequestMessage(ResilienceContext context, HttpRequestMessage request)
=> context.Properties.Set(ResilienceKeys.RequestMessage, request);

private static HttpRequestMessage GetRequestMessage(ResilienceContext context, HttpRequestMessage request)
=> context.Properties.GetValue(ResilienceKeys.RequestMessage, request);
=> context.GetRequestMessage() ?? request;

private static void RestoreResilienceContext(ResilienceContext context, HttpRequestMessage request, bool created)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Http.Resilience.Internal;
using Microsoft.Shared.Diagnostics;
Expand All @@ -26,7 +27,9 @@ protected override async ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState
ResilienceContext context,
TState state)
{
if (!context.Properties.TryGetValue(ResilienceKeys.RequestMessage, out var request))
HttpRequestMessage? request = context.GetRequestMessage();

if (request is null)
{
Throw.InvalidOperationException("The HTTP request message was not found in the resilience context.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public async Task ExecuteAsync_EnsureSnapshotAttached()
var strategy = Create();
var context = ResilienceContextPool.Shared.Get();
using var request = new HttpRequestMessage();
context.Properties.Set(ResilienceKeys.RequestMessage, request);
context.SetRequestMessage(request);

using var response = await strategy.ExecuteAsync(
context =>
Expand All @@ -39,5 +39,15 @@ public void ExecuteAsync_RequestMessageNotFound_Throws()
strategy.Invoking(s => s.Execute(() => { })).Should().Throw<InvalidOperationException>();
}

[Fact]
public void ExecuteAsync_RequestMessageIsNull_Throws()
{
var strategy = Create();
var context = ResilienceContextPool.Shared.Get();
context.SetRequestMessage(null);

strategy.Invoking(s => s.Execute(_ => { }, context)).Should().Throw<InvalidOperationException>();
}

private static ResiliencePipeline Create() => new ResiliencePipelineBuilder().AddStrategy(_ => new RequestMessageSnapshotStrategy(), Mock.Of<ResilienceStrategyOptions>()).Build();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Net.Http;
using Microsoft.Extensions.Http.Resilience.Internal;
using Polly;
using Xunit;

namespace Microsoft.Extensions.Http.Resilience.Test.Resilience;

public class HttpResilienceContextExtensionsTests
{
[Fact]
public void GetRequestMessage_ResilienceContextIsNull_Throws()
{
ResilienceContext context = null!;
Assert.Throws<ArgumentNullException>(context.GetRequestMessage);
}

[Fact]
public void GetRequestMessage_RequestMessageIsMissing_ReturnsNull()
{
var context = ResilienceContextPool.Shared.Get();

Assert.Null(context.GetRequestMessage());
}

[Fact]
public void GetRequestMessage_RequestMessageIsNull_ReturnsNull()
{
var context = ResilienceContextPool.Shared.Get();
context.Properties.Set(ResilienceKeys.RequestMessage, null);

Assert.Null(context.GetRequestMessage());
}

[Fact]
public void GetRequestMessage_RequestMessageIsPresent_ReturnsRequestMessage()
{
var context = ResilienceContextPool.Shared.Get();
using var request = new HttpRequestMessage();
context.Properties.Set(ResilienceKeys.RequestMessage, request);

Assert.Same(request, context.GetRequestMessage());
}

[Fact]
public void SetRequestMessage_ResilienceContextIsNull_Throws()
{
ResilienceContext context = null!;
using var request = new HttpRequestMessage();

Assert.Throws<ArgumentNullException>(() => context.SetRequestMessage(request));
}

[Fact]
public void SetRequestMessage_RequestMessageIsNull_SetsNullRequestMessage()
{
var context = ResilienceContextPool.Shared.Get();
context.SetRequestMessage(null);

Assert.True(context.Properties.TryGetValue(ResilienceKeys.RequestMessage, out HttpRequestMessage? request));
Assert.Null(request);
}

[Fact]
public void SetRequestMessage_RequestMessageIsNotNull_SetsRequestMessage()
{
var context = ResilienceContextPool.Shared.Get();
using var request = new HttpRequestMessage();
context.SetRequestMessage(request);

Assert.True(context.Properties.TryGetValue(ResilienceKeys.RequestMessage, out HttpRequestMessage? actualRequest));
Assert.Same(request, actualRequest);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.Http.Diagnostics;
using Microsoft.Extensions.Http.Resilience.Internal;
using Microsoft.Extensions.Http.Resilience.Test.Helpers;
using Polly;
using Xunit;
Expand Down Expand Up @@ -108,7 +107,7 @@ public async Task Send_EnsureInvoker(bool executionContextSet, bool asynchronous
handler.InnerHandler = new TestHandlerStub((r, _) =>
{
r.GetResilienceContext().Should().NotBeNull();
r.GetResilienceContext()!.Properties.GetValue(ResilienceKeys.RequestMessage, null!).Should().BeSameAs(r);
r.GetResilienceContext()!.GetRequestMessage().Should().BeSameAs(r);

return Task.FromResult(new HttpResponseMessage { StatusCode = HttpStatusCode.Created });
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System;
using System.Net.Http;
using FluentAssertions;
using Microsoft.Extensions.Http.Resilience.Internal;
using Microsoft.Extensions.Http.Resilience.Routing.Internal;
using Moq;
using Polly;
Expand All @@ -22,14 +21,24 @@ public void NoRequestMessage_Throws()
strategy.Invoking(s => s.Execute(() => { })).Should().Throw<InvalidOperationException>().WithMessage("The HTTP request message was not found in the resilience context.");
}

[Fact]
public void RequestMessageIsNull_Throws()
{
var strategy = Create(() => Mock.Of<RequestRoutingStrategy>());
var context = ResilienceContextPool.Shared.Get();
context.SetRequestMessage(null);

strategy.Invoking(s => s.Execute(_ => { }, context)).Should().Throw<InvalidOperationException>().WithMessage("The HTTP request message was not found in the resilience context.");
}

[Fact]
public void NoRoutingProvider_Ok()
{
using var request = new HttpRequestMessage();

var strategy = Create(null);
var context = ResilienceContextPool.Shared.Get();
context.Properties.Set(ResilienceKeys.RequestMessage, request);
context.SetRequestMessage(request);

strategy.Invoking(s => s.Execute(_ => { }, context)).Should().NotThrow();
}
Expand Down
Loading