private async Task CorrelateAsync(string correlationId, RootActivity activity, Func <Task> correlatedTask, OnException onException)
        {
            CorrelationContext correlationContext = activity.Start(correlationId ?? _correlationIdFactory.Create());

            try
            {
                await correlatedTask().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                if (correlationContext != null && !ex.Data.Contains(CorrelateConstants.CorrelationIdKey))
                {
                    // Because we're about to lose context scope, enrich exception with correlation id for reference by calling code.
                    ex.Data.Add(CorrelateConstants.CorrelationIdKey, correlationContext.CorrelationId);
                }

                if (onException == null)
                {
                    throw;
                }

                // Allow caller to handle exception inline before losing context scope.
                bool isHandled = onException(correlationContext, ex);
                if (!isHandled)
                {
                    throw;
                }
            }
            finally
            {
                activity.Stop();
            }
        }
Beispiel #2
0
 public async Task InvokeAsync(HttpContext context, RequestDelegate next)
 {
     var correlationId = _correlationIdFactory.Create();
     using (LogContext.PushProperty("CorrelationId", correlationId))
     {
         await next(context);
     }
 }
Beispiel #3
0
        public async Task HandleAsync(TCommand command)
        {
            var correlationId = _correlationIdFactory.Create();

            using (LogContext.PushProperty("CorrelationId", correlationId))
            {
                await _handler.HandleAsync(command);
            }
        }
        public async Task HandleAsync(TEvent @event)
        {
            var correlationId = _correlationIdFactory.Create();

            using (LogContext.PushProperty("CorrelationId", correlationId))
            {
                var name = @event.GetType().Name.Underscore();
                _logger.LogInformation($"Handling an event: '{name}'...");
                await _handler.HandleAsync(@event);
            }
        }
Beispiel #5
0
        public BioworldHttpClient(HttpClient client, HttpClientOptions options,
                                  ICorrelationContextFactory correlationContextFactory, ICorrelationIdFactory correlationIdFactory)
        {
            _client  = client;
            _options = options;
            if (!string.IsNullOrWhiteSpace(_options.CorrelationContextHeader))
            {
                var correlationContext = correlationContextFactory.Create();
                _client.DefaultRequestHeaders.TryAddWithoutValidation(_options.CorrelationContextHeader,
                                                                      correlationContext);
            }

            if (!string.IsNullOrWhiteSpace(_options.CorrelationIdHeader))
            {
                var correlationId = correlationIdFactory.Create();
                _client.DefaultRequestHeaders.TryAddWithoutValidation(_options.CorrelationContextHeader, correlationId);
            }
        }
        /// <summary>
        /// Generates the headers for a message, and sets a correlation ID if the user didn't provide one.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public Dictionary <string, object> HeaderSetup(IAdditionalMessageData data)
        {
            Guard.NotNull(() => data, data);

            //a correlation ID is required. Verify that we have one.
            if (data.CorrelationId == null || !data.CorrelationId.HasValue)
            {
                data.CorrelationId = _correlationIdFactory.Create();
            }

            Dictionary <string, object> additionalHeaders = null;

            if (data.Headers != null && data.Headers.Count > 0)
            {
                additionalHeaders = data.Headers.ToDictionary(entry => entry.Key,
                                                              entry => entry.Value);
            }
            return(additionalHeaders);
        }
Beispiel #7
0
        private async Task SendAsync(IEnumerable <ICommand> commands)
        {
            if (commands is null)
            {
                return;
            }

            var messageProperties   = _messagePropertiesAccessor.MessageProperties;
            var originatedMessageId = messageProperties?.MessageId;
            var correlationId       = _correlationIdFactory.Create();
            var spanContext         = messageProperties?.GetSpanContext(_spanContextHeader);

            if (string.IsNullOrWhiteSpace(spanContext))
            {
                spanContext = _tracer.ActiveSpan is null ? string.Empty : _tracer.ActiveSpan.Context.ToString();
            }

            var correlationContext = _contextAccessor.CorrelationContext ??
                                     _httpContextAccessor.GetCorrelationContext();
            var headers = new Dictionary <string, object>();

            foreach (var @event in commands)
            {
                if (@event is null)
                {
                    continue;
                }

                var messageId = Guid.NewGuid().ToString("N");
                _logger.LogTrace($"Publishing integration event: {@event.GetType().Name.Underscore()} [ID: '{messageId}'].");
                if (_outbox.Enabled)
                {
                    await _outbox.SendAsync(@event, originatedMessageId, messageId, correlationId, spanContext,
                                            correlationContext, headers);

                    continue;
                }

                await _busPublisher.PublishAsync(@event, messageId, correlationId, spanContext, correlationContext,
                                                 headers);
            }
        }
Beispiel #8
0
        public async Task HandleAsync(TCommand command)
        {
            var commandName   = command.GetType().Name.Underscore();
            var correlationId = _correlationIdFactory.Create();

            using var scope = BuildScope(commandName, correlationId);
            var span = scope.Span;

            try
            {
                span.Log($"Handling a command: {commandName}");
                await _handler.HandleAsync(command);

                span.Log($"Handled a command: {commandName}");
            }
            catch (Exception ex)
            {
                span.Log($"There was an error when handling a command: {commandName}");
                span.Log(ex.Message);
                span.SetTag(Tags.Error, true);
                throw;
            }
        }
 private CorrelationContext StartActivity(string correlationId, IActivity activity)
 {
     return(activity.Start(correlationId ?? _correlationContextAccessor?.CorrelationContext?.CorrelationId ?? _correlationIdFactory.Create()));
 }
Beispiel #10
0
        public Task Process(OutgoingStepContext context, Func <Task> next)
        {
            Message message = context.Load <Message>();

            if (message.Headers.ContainsKey(Headers.CorrelationId))
            {
                return(next());
            }

            string correlationId = _correlationContextAccessor.CorrelationContext?.CorrelationId ?? _correlationIdFactory.Create();

            message.Headers[Headers.CorrelationId] = correlationId;

            int correlationSequence = 0;
            ITransactionContext transactionContext  = context.Load <ITransactionContext>();
            IncomingStepContext incomingStepContext = transactionContext.GetOrNull <IncomingStepContext>(StepContext.StepContextKey);

            if (incomingStepContext != null)
            {
                correlationSequence = GetCorrelationSequence(incomingStepContext) + 1;
            }

            message.Headers[Headers.CorrelationSequence] = correlationSequence.ToString(CultureInfo.InvariantCulture);

            _logger.Debug("Correlation ID: {CorrelationId}, sequence: {CorrelationSequence}", correlationId, correlationSequence);

            return(next());
        }