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 { /// /// Middleware which attempts to reads / creates a Trace ID that can then be used in logs and /// passed to upstream requests. /// public class TraceIdMiddleware { private readonly RequestDelegate next; private readonly TraceIdOptions options; private readonly ITraceContextAccessor traceContextAccessor; /// /// Creates a new instance of the TraceIdMiddleware. /// /// The next middleware in the pipeline. /// The configuration options. public TraceIdMiddleware(RequestDelegate next, IOptions 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)); } /// /// Processes a request to synchronise TraceIdentifier and Trace ID headers. Also creates a /// for the current request and disposes of it when the request is completing. /// /// The for the current request. /// The which can create a . 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(); } } }