Files
GX.O3.WMS/APP.O3/Infrastructure/Logger/TraceId/TraceIdMiddleware.cs
T

90 lines
3.6 KiB
C#
Executable File

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Opsoft.NetCore.O3App.Domain;
using Opsoft.NetCore.O3App.Domain.Models;
using Opsoft.NetCore.O3App.Shared;
using System;
using System.Threading.Tasks;
namespace Opsoft.NetCore.O3App.Infrastructure
{
/// <summary>
/// Middleware which attempts to reads / creates a Trace ID that can then be used in logs and
/// passed to upstream requests.
/// </summary>
public class TraceIdMiddleware
{
private readonly RequestDelegate next;
private readonly TraceIdOptions options;
private readonly ITraceContextAccessor traceContextAccessor;
/// <summary>
/// Creates a new instance of the TraceIdMiddleware.
/// </summary>
/// <param name="next">The next middleware in the pipeline.</param>
/// <param name="options">The configuration options.</param>
public TraceIdMiddleware(RequestDelegate next, IOptions<TraceIdOptions> options, ITraceContextAccessor traceContextAccessor)
{
this.next = next ?? throw new ArgumentNullException(nameof(next));
this.options = options.Value ?? throw new ArgumentNullException(nameof(options));
this.traceContextAccessor = traceContextAccessor ?? throw new ArgumentNullException(nameof(traceContextAccessor));
}
/// <summary>
/// Processes a request to synchronise TraceIdentifier and Trace ID headers. Also creates a
/// <see cref="TraceContext"/> for the current request and disposes of it when the request is completing.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
/// <param name="traceContextFactory">The <see cref="ITraceContextFactory"/> which can create a <see cref="TraceContext"/>.</param>
public async Task Invoke(HttpContext context, ITraceContextFactory traceContextFactory)
{
var traceId = GetTraceId(context);
if (options.UpdateTraceIdentifier)
context.TraceIdentifier = traceId;
traceContextFactory.Create(traceId, options.Header);
if (options.IncludeInResponse)
{
// apply the Trace ID to the response header for client side tracking
context.Response.OnStarting(() =>
{
if (!context.Response.Headers.ContainsKey(options.Header))
{
context.Response.Headers.Add(options.Header, traceId);
}
return Task.CompletedTask;
});
}
await next(context);
traceContextFactory.Dispose();
}
private StringValues GetTraceId(HttpContext context)
{
var traceIdFoundInRequestHeader = context.Request.Headers.TryGetValue(options.Header, out var traceId);
if (RequiresGenerationOfTraceId(traceIdFoundInRequestHeader, traceId))
traceId = GenerateTraceId(context.TraceIdentifier);
return traceId;
}
private static bool RequiresGenerationOfTraceId(bool idInHeader, StringValues idFromHeader) =>
!idInHeader || StringValues.IsNullOrEmpty(idFromHeader);
private StringValues GenerateTraceId(string traceIdentifier)
{
return new TransactionId(
TraceUtility.GenerateAgentId(),
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
traceContextAccessor.TransactionSequence).ToString();
}
}
}