Skip to content

HeaderPropagation: add support for hosted services #12170

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

Closed
Closed
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 @@ -14,10 +14,10 @@ namespace Microsoft.AspNetCore.HeaderPropagation
public readonly partial struct HeaderPropagationContext
{
private readonly object _dummy;
public HeaderPropagationContext(Microsoft.AspNetCore.Http.HttpContext httpContext, string headerName, Microsoft.Extensions.Primitives.StringValues headerValue) { throw null; }
public HeaderPropagationContext(System.Collections.Generic.IDictionary<string, Microsoft.Extensions.Primitives.StringValues> requestHeaders, string headerName, Microsoft.Extensions.Primitives.StringValues headerValue) { throw null; }
public string HeaderName { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public Microsoft.Extensions.Primitives.StringValues HeaderValue { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public Microsoft.AspNetCore.Http.HttpContext HttpContext { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public System.Collections.Generic.IDictionary<string, Microsoft.Extensions.Primitives.StringValues> RequestHeaders { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
public partial class HeaderPropagationEntry
{
Expand Down Expand Up @@ -58,19 +58,28 @@ public HeaderPropagationMessageHandlerOptions() { }
}
public partial class HeaderPropagationMiddleware
{
public HeaderPropagationMiddleware(Microsoft.AspNetCore.Http.RequestDelegate next, Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.HeaderPropagation.HeaderPropagationOptions> options, Microsoft.AspNetCore.HeaderPropagation.HeaderPropagationValues values) { }
public HeaderPropagationMiddleware(Microsoft.AspNetCore.Http.RequestDelegate next, Microsoft.AspNetCore.HeaderPropagation.IHeaderPropagationProcessor processor) { }
public System.Threading.Tasks.Task Invoke(Microsoft.AspNetCore.Http.HttpContext context) { throw null; }
}
public partial class HeaderPropagationOptions
{
public HeaderPropagationOptions() { }
public Microsoft.AspNetCore.HeaderPropagation.HeaderPropagationEntryCollection Headers { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class HeaderPropagationProcessor : Microsoft.AspNetCore.HeaderPropagation.IHeaderPropagationProcessor
{
public HeaderPropagationProcessor(Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.HeaderPropagation.HeaderPropagationOptions> options, Microsoft.AspNetCore.HeaderPropagation.HeaderPropagationValues values) { }
public void ProcessRequest(System.Collections.Generic.IDictionary<string, Microsoft.Extensions.Primitives.StringValues> requestHeaders) { }
}
public partial class HeaderPropagationValues
{
public HeaderPropagationValues() { }
public System.Collections.Generic.IDictionary<string, Microsoft.Extensions.Primitives.StringValues> Headers { get { throw null; } set { } }
}
public partial interface IHeaderPropagationProcessor
{
void ProcessRequest(System.Collections.Generic.IDictionary<string, Microsoft.Extensions.Primitives.StringValues> requestHeaders);
}
}
namespace Microsoft.Extensions.DependencyInjection
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.HeaderPropagation;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;

namespace HeaderPropagationSample
{
public class SampleHostedService : IHostedService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly HeaderPropagationProcessor _headerPropagationProcessor;
private readonly ILogger _logger;

public SampleHostedService(IHttpClientFactory httpClientFactory, HeaderPropagationProcessor headerPropagationProcessor, ILogger<SampleHostedService> logger)
{
_httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
_headerPropagationProcessor = headerPropagationProcessor ?? throw new ArgumentNullException(nameof(headerPropagationProcessor));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

public Task StartAsync(CancellationToken cancellationToken)
{
return DoWorkAsync();
}

private async Task DoWorkAsync()
{
_logger.LogInformation("Background Service is working.");

_headerPropagationProcessor.ProcessRequest(new Dictionary<string, StringValues>());
var client = _httpClientFactory.CreateClient("test");
var result = await client.GetAsync("http://localhost:62013/forwarded");

_logger.LogInformation("Background Service:\n{result}", result);
}

public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ public void ConfigureServices(IServiceCollection services)
services
.AddHttpClient("another")
.AddHeaderPropagation(options => options.Headers.Add("X-BetaFeatures", "X-Experiments"));

services.AddHostedService<SampleHostedService>();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHttpClientFactory clientFactory)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public static IServiceCollection AddHeaderPropagation(this IServiceCollection se
}

services.TryAddSingleton<HeaderPropagationValues>();
services.TryAddSingleton<IHeaderPropagationProcessor, HeaderPropagationProcessor>();

return services;
}
Expand Down
26 changes: 8 additions & 18 deletions src/Middleware/HeaderPropagation/src/HeaderPropagationContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Primitives;

namespace Microsoft.AspNetCore.HeaderPropagation
Expand All @@ -14,32 +14,22 @@ public readonly struct HeaderPropagationContext
{
/// <summary>
/// Initializes a new instance of <see cref="HeaderPropagationContext"/> with the provided
/// <paramref name="httpContext"/>, <paramref name="headerName"/> and <paramref name="headerValue"/>.
/// <paramref name="requestHeaders"/>, <paramref name="headerName"/> and <paramref name="headerValue"/>.
/// </summary>
/// <param name="httpContext">The <see cref="Http.HttpContext"/> associated with the current request.</param>
/// <param name="requestHeaders">The headers associated with the current request.</param>
/// <param name="headerName">The header name.</param>
/// <param name="headerValue">The header value present in the current request.</param>
public HeaderPropagationContext(HttpContext httpContext, string headerName, StringValues headerValue)
public HeaderPropagationContext(IDictionary<string, StringValues> requestHeaders, string headerName, StringValues headerValue)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}

if (headerName == null)
{
throw new ArgumentNullException(nameof(headerName));
}

HttpContext = httpContext;
HeaderName = headerName;
RequestHeaders = requestHeaders ?? throw new ArgumentNullException(nameof(requestHeaders));
HeaderName = headerName ?? throw new ArgumentNullException(nameof(headerName));
HeaderValue = headerValue;
}

/// <summary>
/// Gets the <see cref="Http.HttpContext"/> associated with the current request.
/// Gets the headers associated with the current request.
/// </summary>
public HttpContext HttpContext { get; }
public IDictionary<string, StringValues> RequestHeaders { get; }

/// <summary>
/// Gets the header name.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ namespace Microsoft.AspNetCore.HeaderPropagation
/// </summary>
public class HeaderPropagationMessageHandler : DelegatingHandler
{
private readonly HeaderPropagationValues _values;
private readonly HeaderPropagationMessageHandlerOptions _options;
private readonly HeaderPropagationValues _values;

/// <summary>
/// Creates a new instance of the <see cref="HeaderPropagationMessageHandler"/>.
Expand Down Expand Up @@ -47,9 +47,10 @@ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage reques
if (captured == null)
{
var message =
$"The {nameof(HeaderPropagationValues)}.{nameof(HeaderPropagationValues.Headers)} property has not been " +
$"initialized. Register the header propagation middleware by adding 'app.{nameof(HeaderPropagationApplicationBuilderExtensions.UseHeaderPropagation)}() " +
$"in the 'Configure(...)' method.";
$"The {nameof(HeaderPropagationValues)}.{nameof(HeaderPropagationValues.Headers)} property has not been initialized. " +
$"If using this {nameof(HttpClient)} as part of an http request, register the header propagation middleware by adding " +
$"'app.{nameof(HeaderPropagationApplicationBuilderExtensions.UseHeaderPropagation)}() in the 'Configure(...)' method. " +
$"Otherwise, use {nameof(HeaderPropagationProcessor)}.{nameof(HeaderPropagationProcessor.ProcessRequest)}() before using the {nameof(HttpClient)}.";
throw new InvalidOperationException(message);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;

namespace Microsoft.AspNetCore.HeaderPropagation
{
Expand All @@ -17,61 +14,19 @@ namespace Microsoft.AspNetCore.HeaderPropagation
public class HeaderPropagationMiddleware
{
private readonly RequestDelegate _next;
private readonly HeaderPropagationOptions _options;
private readonly HeaderPropagationValues _values;
private readonly IHeaderPropagationProcessor _processor;

public HeaderPropagationMiddleware(RequestDelegate next, IOptions<HeaderPropagationOptions> options, HeaderPropagationValues values)
public HeaderPropagationMiddleware(RequestDelegate next, IHeaderPropagationProcessor processor)
{
_next = next ?? throw new ArgumentNullException(nameof(next));

if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_options = options.Value;

_values = values ?? throw new ArgumentNullException(nameof(values));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
}

public Task Invoke(HttpContext context)
{
// We need to intialize the headers because the message handler will use this to detect misconfiguration.
var headers = _values.Headers ??= new Dictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase);

// Perf: avoid foreach since we don't define a struct enumerator.
var entries = _options.Headers;
for (var i = 0; i < entries.Count; i++)
{
var entry = entries[i];

// We intentionally process entries in order, and allow earlier entries to
// take precedence over later entries when they have the same output name.
if (!headers.ContainsKey(entry.CapturedHeaderName))
{
var value = GetValue(context, entry);
if (!StringValues.IsNullOrEmpty(value))
{
headers.Add(entry.CapturedHeaderName, value);
}
}
}
_processor.ProcessRequest(context.Request.Headers);

return _next.Invoke(context);
}

private static StringValues GetValue(HttpContext context, HeaderPropagationEntry entry)
{
context.Request.Headers.TryGetValue(entry.InboundHeaderName, out var value);
if (entry.ValueFilter != null)
{
var filtered = entry.ValueFilter(new HeaderPropagationContext(context, entry.InboundHeaderName, value));
if (!StringValues.IsNullOrEmpty(filtered))
{
value = filtered;
}
}

return value;
}
}
}
79 changes: 79 additions & 0 deletions src/Middleware/HeaderPropagation/src/HeaderPropagationProcessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;

namespace Microsoft.AspNetCore.HeaderPropagation
{
public class HeaderPropagationProcessor : IHeaderPropagationProcessor
{
private readonly HeaderPropagationOptions _options;
private readonly HeaderPropagationValues _values;

public HeaderPropagationProcessor(IOptions<HeaderPropagationOptions> options, HeaderPropagationValues values)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_options = options.Value;

_values = values;
}

public void ProcessRequest(IDictionary<string, StringValues> requestHeaders)
{
if (requestHeaders == null)
{
throw new ArgumentNullException(nameof(requestHeaders));
}

if (_values.Headers != null)
{
var message =
$"The {nameof(HeaderPropagationValues)}.{nameof(HeaderPropagationValues.Headers)} was already initialized. "
+ $"Each invocation of {nameof(HeaderPropagationProcessor)}.{nameof(HeaderPropagationProcessor.ProcessRequest)}() must be in a separate async context.";
throw new InvalidOperationException(message);
}

// We need to intialize the headers because the message handler will use this to detect misconfiguration.
var headers = _values.Headers = new Dictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase);

// Perf: avoid foreach since we don't define a struct enumerator.
var entries = _options.Headers;
for (var i = 0; i < entries.Count; i++)
{
var entry = entries[i];

// We intentionally process entries in order, and allow earlier entries to
// take precedence over later entries when they have the same output name.
if (!headers.ContainsKey(entry.CapturedHeaderName))
{
var value = GetValue(requestHeaders, entry);
if (!StringValues.IsNullOrEmpty(value))
{
headers.Add(entry.CapturedHeaderName, value);
}
}
}
}

private static StringValues GetValue(IDictionary<string, StringValues> requestHeaders, HeaderPropagationEntry entry)
{
requestHeaders.TryGetValue(entry.InboundHeaderName, out var value);
if (entry.ValueFilter != null)
{
var filtered = entry.ValueFilter(new HeaderPropagationContext(requestHeaders, entry.InboundHeaderName, value));
if (!StringValues.IsNullOrEmpty(filtered))
{
value = filtered;
}
}

return value;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

namespace Microsoft.AspNetCore.HeaderPropagation
{
public interface IHeaderPropagationProcessor
{
void ProcessRequest(System.Collections.Generic.IDictionary<string, Extensions.Primitives.StringValues> requestHeaders);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ public async Task HeaderPropagation_WithoutMiddleware_Throws()
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.IsType<InvalidOperationException>(captured);
Assert.Equal(
"The HeaderPropagationValues.Headers property has not been initialized. Register the header propagation middleware " +
"by adding 'app.UseHeaderPropagation() in the 'Configure(...)' method.",
"The HeaderPropagationValues.Headers property has not been initialized. If using this HttpClient as part of an http request, " +
"register the header propagation middleware by adding 'app.UseHeaderPropagation() in the 'Configure(...)' method. " +
"Otherwise, use HeaderPropagationProcessor.ProcessRequest() before using the HttpClient.",
captured.Message);
}

Expand Down
Loading