generated from dailydevops/template-dotnet
-
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add Azure Functions middleware for HTTP correlation ID management #562
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,3 @@ | ||
| **/nuget.config | ||
| **/_snapshots/ | ||
| **/_snapshot/ | ||
| **/[Nn]u[Gg]et.config | ||
| **/*.verified.* | ||
| **/*.received.* |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
src/NetEvolve.Http.Correlation.AspNetCore/ApplicationBuilderExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
src/NetEvolve.Http.Correlation.AspNetCore/HttpCorrelationMiddleware.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
src/NetEvolve.Http.Correlation.AspNetCore/ServiceCollectionExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
src/NetEvolve.Http.Correlation.Azure.Functions/FunctionsCorrelationAccessor.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| namespace NetEvolve.Http.Correlation.Azure.Functions; | ||
|
|
||
| using Microsoft.Azure.Functions.Worker; | ||
| using NetEvolve.Http.Correlation.Abstractions; | ||
|
|
||
| internal sealed class FunctionsCorrelationAccessor : IHttpCorrelationAccessor | ||
| { | ||
| private string? _correlationId; | ||
|
|
||
| public FunctionContext Context { get; set; } = default!; | ||
|
|
||
| public string CorrelationId | ||
| { | ||
| get => _correlationId ??= Context.InvocationId; | ||
| set => _correlationId = value; | ||
| } | ||
|
|
||
| public string HeaderName { get; set; } = string.Empty; | ||
| } | ||
97 changes: 97 additions & 0 deletions
97
src/NetEvolve.Http.Correlation.Azure.Functions/FunctionsCorrelationMiddleware.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| namespace NetEvolve.Http.Correlation.Azure.Functions; | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Azure.Functions.Worker; | ||
| using Microsoft.Azure.Functions.Worker.Http; | ||
| using Microsoft.Azure.Functions.Worker.Middleware; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Logging; | ||
| using NetEvolve.Http.Correlation.Abstractions; | ||
| using static NetEvolve.Http.Correlation.CorrelationConstants; | ||
|
|
||
| internal sealed class FunctionsCorrelationMiddleware : IFunctionsWorkerMiddleware | ||
| { | ||
| private readonly ILogger<FunctionsCorrelationMiddleware> _logger; | ||
|
|
||
| public FunctionsCorrelationMiddleware(ILogger<FunctionsCorrelationMiddleware> logger) => _logger = logger; | ||
|
|
||
| public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(context); | ||
|
|
||
| var accessor = context.InstanceServices.GetRequiredService<FunctionsCorrelationAccessor>(); | ||
| accessor.Context = context; | ||
|
|
||
| var httpRequestData = await context.GetHttpRequestDataAsync().ConfigureAwait(false); | ||
|
|
||
| if (httpRequestData is null) | ||
| { | ||
| await next(context).ConfigureAwait(false); | ||
| return; | ||
| } | ||
|
|
||
| if (!GetIdFromHeader(httpRequestData, out var correlationId, out var usedHeaderName)) | ||
| { | ||
| correlationId = GeneratedId(context); | ||
| } | ||
|
|
||
| accessor.CorrelationId = correlationId; | ||
| accessor.HeaderName = usedHeaderName; | ||
|
|
||
| var scopeProperties = new Dictionary<string, object>(StringComparer.Ordinal) | ||
| { | ||
| { usedHeaderName, correlationId }, | ||
| }; | ||
|
|
||
| using (_logger.BeginScope(scopeProperties)) | ||
| { | ||
| await next(context).ConfigureAwait(false); | ||
|
|
||
| // Add correlation ID to response headers after function execution | ||
| var httpResponseData = context.GetInvocationResult().Value as HttpResponseData; | ||
| if (httpResponseData is not null && !httpResponseData.Headers.Contains(usedHeaderName)) | ||
| { | ||
| httpResponseData.Headers.Add(usedHeaderName, correlationId); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static string GeneratedId(FunctionContext context) => | ||
| context.InstanceServices.GetService<IHttpCorrelationIdProvider>()?.GenerateId() ?? context.InvocationId; | ||
|
|
||
| private static bool GetIdFromHeader( | ||
| HttpRequestData httpRequestData, | ||
| out string correlationId, | ||
| out string usedHeaderName | ||
| ) | ||
| { | ||
| usedHeaderName = HeaderName1; | ||
| correlationId = string.Empty; | ||
|
|
||
| if (httpRequestData.Headers.TryGetValues(HeaderName1, out var headerValues1)) | ||
| { | ||
| var firstValue = headerValues1.FirstOrDefault(); | ||
| if (!string.IsNullOrWhiteSpace(firstValue)) | ||
| { | ||
| correlationId = firstValue; | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| if (httpRequestData.Headers.TryGetValues(HeaderName2, out var headerValues2)) | ||
| { | ||
| var firstValue = headerValues2.FirstOrDefault(); | ||
| if (!string.IsNullOrWhiteSpace(firstValue)) | ||
| { | ||
| correlationId = firstValue; | ||
| usedHeaderName = HeaderName2; | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
| } |
35 changes: 35 additions & 0 deletions
35
...NetEvolve.Http.Correlation.Azure.Functions/FunctionsWorkerApplicationBuilderExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| namespace NetEvolve.Http.Correlation.Azure.Functions; | ||
|
|
||
| using System; | ||
| using Microsoft.Azure.Functions.Worker; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Hosting; | ||
| using NetEvolve.Http.Correlation.Abstractions; | ||
|
|
||
| /// <summary> | ||
| /// <see cref="IFunctionsWorkerApplicationBuilder"/> Extensions for <see cref="FunctionsCorrelationMiddleware"/>. | ||
| /// </summary> | ||
| public static class FunctionsWorkerApplicationBuilderExtensions | ||
| { | ||
| /// <summary> | ||
| /// Adds the <see cref="FunctionsCorrelationMiddleware"/> to the Azure Functions worker middleware pipeline. | ||
| /// </summary> | ||
| /// <param name="builder">The <see cref="IFunctionsWorkerApplicationBuilder"/> instance.</param> | ||
| /// <returns>The <see cref="IFunctionsWorkerApplicationBuilder"/> instance.</returns> | ||
| public static IFunctionsWorkerApplicationBuilder UseHttpCorrelation(this IFunctionsWorkerApplicationBuilder builder) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(builder); | ||
|
|
||
| using (var scopedServices = builder.Services.BuildServiceProvider().CreateScope()) | ||
| { | ||
| if (scopedServices.ServiceProvider.GetService<IHttpCorrelationAccessor>() is null) | ||
| { | ||
| throw new InvalidOperationException( | ||
| $"The required services for this function were not found. Please run `services.{nameof(ServiceCollectionExtensions.AddHttpCorrelation)}()` in advance." | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| return builder.UseMiddleware<FunctionsCorrelationMiddleware>(); | ||
| } | ||
| } |
22 changes: 22 additions & 0 deletions
22
...Evolve.Http.Correlation.Azure.Functions/NetEvolve.Http.Correlation.Azure.Functions.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
| <PropertyGroup> | ||
| <TargetFrameworks>$(_TargetFrameworks)</TargetFrameworks> | ||
| </PropertyGroup> | ||
| <PropertyGroup> | ||
| <Description>Implementation of Azure.Functions middleware to use Http.Correlation. Based on the primary Http header `X-Correlation-ID` as well as the alternative Http header `X-Request-ID`.</Description> | ||
| <PackageTags>$(PackageTags);azure;functions</PackageTags> | ||
| </PropertyGroup> | ||
| <ItemGroup> | ||
| <ProjectReference Include="..\NetEvolve.Http.Correlation.Abstractions\NetEvolve.Http.Correlation.Abstractions.csproj" /> | ||
| </ItemGroup> | ||
| <ItemGroup> | ||
| <FrameworkReference Include="Microsoft.AspNetCore.App" /> | ||
| </ItemGroup> | ||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.Azure.Functions.Worker.Core" /> | ||
| </ItemGroup> | ||
| <ItemGroup> | ||
| <InternalsVisibleTo Include="NetEvolve.Http.Correlation.Azure.Functions.Tests.Unit" /> | ||
| <InternalsVisibleTo Include="NetEvolve.Http.Correlation.Azure.Functions.Tests.Integration" /> | ||
| </ItemGroup> | ||
| </Project> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.