async void Receiver(IPipe<NamespaceContext> pipe, TaskSupervisor supervisor)
        {
            var inputAddress = _settings.GetInputAddress(_host.Settings.ServiceUri);

            try
            {
                await _host.RetryPolicy.RetryUntilCancelled(async () =>
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Connecting receive transport: {0}", inputAddress);

                    var context = new ServiceBusNamespaceContext(_host, _receiveObservers, _endpointObservers, supervisor);

                    try
                    {
                        await pipe.Send(context).ConfigureAwait(false);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    catch (OperationCanceledException)
                    {
                    }
                    catch (Exception ex)
                    {
                        if (_log.IsErrorEnabled)
                            _log.Error($"Azure Service Bus receiver faulted: {inputAddress}", ex);

                        await _endpointObservers.Faulted(new ReceiveTransportFaultedEvent(inputAddress, ex)).ConfigureAwait(false);

                        throw;
                    }
                }, supervisor.StoppingToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _log.Error($"Unhandled exception on Receiver: {inputAddress}", ex);
            }
        }
        public async Task Send(ConsumeContext <RoutingSlip> context, IPipe <ConsumeContext <RoutingSlip> > next)
        {
            var activity = LogContext.IfEnabled(OperationName.Courier.Compensate)?.StartActivity(new
            {
                ActivityType = TypeMetadataCache <TActivity> .ShortName,
                LogType      = TypeMetadataCache <TLog> .ShortName
            });

            activity?.AddBaggage(DiagnosticHeaders.TrackingNumber, context.Message.TrackingNumber);

            var timer = Stopwatch.StartNew();

            try
            {
                CompensateContext <TLog> compensateContext = new HostCompensateContext <TLog>(context);

                LogContext.Debug?.Log("Compensate Activity: {TrackingNumber} ({Activity}, {Host})", compensateContext.TrackingNumber,
                                      TypeMetadataCache <TActivity> .ShortName, context.ReceiveContext.InputAddress);

                try
                {
                    await Task.Yield();

                    await _compensatePipe.Send(compensateContext).ConfigureAwait(false);

                    var result = compensateContext.Result
                                 ?? compensateContext.Failed(new ActivityCompensationException("The activity compensation did not return a result"));

                    await result.Evaluate().ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    await compensateContext.Failed(ex).Evaluate().ConfigureAwait(false);
                }

                await context.NotifyConsumed(timer.Elapsed, TypeMetadataCache <TActivity> .ShortName).ConfigureAwait(false);

                await next.Send(context).ConfigureAwait(false);
            }
            catch (OperationCanceledException exception)
            {
                await context.NotifyFaulted(timer.Elapsed, TypeMetadataCache <TActivity> .ShortName, exception).ConfigureAwait(false);

                if (exception.CancellationToken == context.CancellationToken)
                {
                    throw;
                }

                throw new ConsumerCanceledException($"The operation was cancelled by the activity: {TypeMetadataCache<TActivity>.ShortName}");
            }
            catch (Exception ex)
            {
                await context.NotifyFaulted(timer.Elapsed, TypeMetadataCache <TActivity> .ShortName, ex).ConfigureAwait(false);

                LogContext.Error?.Log(ex, "Activity {Activity} compensation faulted", TypeMetadataCache <TActivity> .ShortName);

                throw;
            }
            finally
            {
                activity?.Stop();
            }
        }
示例#3
0
        async Task OnMessage(BrokeredMessage message)
        {
            int current = Interlocked.Increment(ref _currentPendingDeliveryCount);

            while (current > _maxPendingDeliveryCount)
            {
                Interlocked.CompareExchange(ref _maxPendingDeliveryCount, current, _maxPendingDeliveryCount);
            }

            long deliveryCount = Interlocked.Increment(ref _deliveryCount);

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Receiving {0}:{1} - {2}", deliveryCount, message.MessageId, _receiveSettings.QueueDescription.Path);
            }

            var context = new ServiceBusReceiveContext(_inputAddress, message, _receiveObserver);

            try
            {
                if (_shuttingDown)
                {
                    await _completeTask.Task.ConfigureAwait(false);

                    throw new TransportException(_inputAddress, "Transport shutdown in progress, abandoning message");
                }

                await _receiveObserver.PreReceive(context).ConfigureAwait(false);

                await _receivePipe.Send(context).ConfigureAwait(false);

                await context.CompleteTask.ConfigureAwait(false);

                await message.CompleteAsync().ConfigureAwait(false);

                await _receiveObserver.PostReceive(context).ConfigureAwait(false);

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Receive completed: {0}", message.MessageId);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsErrorEnabled)
                {
                    _log.Error($"Received faulted: {message.MessageId}", ex);
                }

                await message.AbandonAsync().ConfigureAwait(false);

                await _receiveObserver.ReceiveFault(context, ex).ConfigureAwait(false);
            }
            finally
            {
                int pendingCount = Interlocked.Decrement(ref _currentPendingDeliveryCount);
                if (pendingCount == 0 && _shuttingDown)
                {
                    _completeTask.TrySetResult(this);
                }
            }
        }
        async Task SendUsingExistingConnection(IPipe<ConnectionContext> connectionPipe, ConnectionScope scope, CancellationToken cancellationToken)
        {
            try
            {
                using (var context = await scope.Attach(cancellationToken).ConfigureAwait(false))
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Using connection: {0}", ((ConnectionContext)context).HostSettings.ToDebugString());

                    await connectionPipe.Send(context).ConfigureAwait(false);
                }
            }
            catch (BrokerUnreachableException ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The broker was unreachable", ex);

                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.ConnectFaulted(ex);

                throw new RabbitMqConnectionException("Connect failed: " + _settings.ToDebugString(), ex);
            }
            catch (Exception ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The connection usage threw an exception", ex);

                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.ConnectFaulted(ex);

                throw;
            }
        }
示例#5
0
            Task IFilter <SendContext> .Send(SendContext context, IPipe <SendContext> next)
            {
                Interlocked.Increment(ref _count);

                return(next.Send(context));
            }
示例#6
0
        async Task SendUsingExistingConnection(IPipe<OwinHostContext> connectionPipe, OwinHostScope scope, CancellationToken cancellationToken)
        {
            try
            {
                using (var context = await scope.Attach(cancellationToken).ConfigureAwait(false))
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Using host: {0}", context.HostSettings.ToDebugString());

                    await connectionPipe.Send(context).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The host usage threw an exception", ex);

                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.ConnectFaulted(ex);

                throw;
            }
        }
        async Task SendUsingNewConnection(IPipe<ConnectionContext> connectionPipe, ConnectionScope scope, CancellationToken cancellationToken)
        {
            try
            {
                if (_signal.CancellationToken.IsCancellationRequested)
                    throw new TaskCanceledException($"The connection is being disconnected: {_settings.ToDebugString()}");

                if (_log.IsDebugEnabled)
                    _log.DebugFormat("Connecting: {0}", _connectionFactory.ToDebugString());

                IConnection connection = _connectionFactory.CreateConnection();

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Connected: {0} (address: {1}, local: {2}", _connectionFactory.ToDebugString(),
                        connection.RemoteEndPoint, connection.LocalEndPoint);
                }

                EventHandler<ShutdownEventArgs> connectionShutdown = null;
                connectionShutdown = (obj, reason) =>
                {
                    connection.ConnectionShutdown -= connectionShutdown;

                    Interlocked.CompareExchange(ref _scope, null, scope);

                    scope.Close();
                };

                connection.ConnectionShutdown += connectionShutdown;

                var connectionContext = new RabbitMqConnectionContext(connection, _settings, _signal.CancellationToken);

                connectionContext.GetOrAddPayload(() => _settings);

                scope.Connected(connectionContext);
            }
            catch (BrokerUnreachableException ex)
            {
                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.ConnectFaulted(ex);

                throw new RabbitMqConnectionException("Connect failed: " + _connectionFactory.ToDebugString(), ex);
            }

            try
            {
                using (SharedConnectionContext context = await scope.Attach(cancellationToken))
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Using new connection: {0}", ((ConnectionContext)context).HostSettings.ToDebugString());

                    await connectionPipe.Send(context);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The connection usage threw an exception", ex);

                throw;
            }
        }
示例#8
0
        async Task OnMessage(BrokeredMessage message)
        {
            if (_shuttingDown)
            {
                await WaitAndAbandonMessage(message).ConfigureAwait(false);

                return;
            }

            var current = Interlocked.Increment(ref _currentPendingDeliveryCount);

            while (current > _maxPendingDeliveryCount)
            {
                Interlocked.CompareExchange(ref _maxPendingDeliveryCount, current, _maxPendingDeliveryCount);
            }

            var deliveryCount = Interlocked.Increment(ref _deliveryCount);

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("Receiving {0}:{1} - {2}", deliveryCount, message.MessageId, _receiveSettings.QueueDescription.Path);
            }

            var context = new ServiceBusReceiveContext(_inputAddress, message, _receiveObserver);

            try
            {
                await _receiveObserver.PreReceive(context).ConfigureAwait(false);

                await _receivePipe.Send(context).ConfigureAwait(false);

                await context.CompleteTask.ConfigureAwait(false);

                await message.CompleteAsync().ConfigureAwait(false);

                await _receiveObserver.PostReceive(context).ConfigureAwait(false);

                if (_log.IsDebugEnabled)
                {
                    _log.DebugFormat("Receive completed: {0}", message.MessageId);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsErrorEnabled)
                {
                    _log.Error($"Received faulted: {message.MessageId}", ex);
                }

                await message.AbandonAsync().ConfigureAwait(false);

                await _receiveObserver.ReceiveFault(context, ex).ConfigureAwait(false);
            }
            finally
            {
                var pendingCount = Interlocked.Decrement(ref _currentPendingDeliveryCount);
                if (pendingCount == 0 && _shuttingDown)
                {
                    if (_log.IsDebugEnabled)
                    {
                        _log.DebugFormat("Receiver shutdown completed: {0}", _inputAddress);
                    }

                    _participant.SetComplete();
                }
            }
        }
示例#9
0
            public async Task Send(ClientContext context)
            {
                LogContext.SetCurrentIfNull(_context.LogContext);

                await _context.ConfigureTopologyPipe.Send(context).ConfigureAwait(false);

                var sendContext = new TransportAmazonSqsSendContext <T>(_message, _cancellationToken);

                await _pipe.Send(sendContext).ConfigureAwait(false);

                StartedActivity?activity = LogContext.IfEnabled(OperationName.Transport.Send)?.StartSendActivity(sendContext);

                try
                {
                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PreSend(sendContext).ConfigureAwait(false);
                    }

                    var request = await context.CreatePublishRequest(_context.EntityName, sendContext.Body).ConfigureAwait(false);

                    _context.SnsSetHeaderAdapter.Set(request.MessageAttributes, sendContext.Headers);

                    _context.SnsSetHeaderAdapter.Set(request.MessageAttributes, "Content-Type", sendContext.ContentType.MediaType);
                    _context.SnsSetHeaderAdapter.Set(request.MessageAttributes, nameof(sendContext.CorrelationId), sendContext.CorrelationId);

                    if (!string.IsNullOrEmpty(sendContext.DeduplicationId))
                    {
                        request.MessageDeduplicationId = sendContext.DeduplicationId;
                    }

                    if (!string.IsNullOrEmpty(sendContext.GroupId))
                    {
                        request.MessageGroupId = sendContext.GroupId;
                    }

                    await context.Publish(request, sendContext.CancellationToken).ConfigureAwait(false);

                    sendContext.LogSent();
                    activity.AddSendContextHeadersPostSend(sendContext);

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PostSend(sendContext).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    sendContext.LogFaulted(ex);

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.SendFault(sendContext, ex).ConfigureAwait(false);
                    }

                    throw;
                }
                finally
                {
                    activity?.Stop();
                }
            }
            public Task Send(SendContext <T> context)
            {
                context.Headers.Set(MessageHeaders.ClientId, _clientId.ToString("D"));

                return(_pipe.Send(context));
            }
示例#11
0
        /// <summary>
        /// When sending a command ensure the current correlationId is set in the message header and the message's context.
        /// Note, this is done because our product uses a string correlation-ID datatype and MassTransit uses a Guid correlation-ID datatype.
        /// In the event a non Guid string value was passed as a correlation-ID in our application this will log the association from one to the other.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task Send(SendContext <T> context, IPipe <SendContext <T> > next)
        {
            _logger.LogDebug("Start CorrelationSendContextFilter");

            // First try to find the CorrelationId in the CorrelationContextAccessor
            var headerCorrelationId = _correlationContextAccessor?.CorrelationContext?.CorrelationId;

            if (null == headerCorrelationId)
            {
                // Second try to find the CorrelationId already set in the outbound message header
                headerCorrelationId = context.Headers.Get <string>(Consts.CorrelationIdHeaderKey);

                if (null == headerCorrelationId)
                {
                    // Finally try to find the CorrelationId already set in the message context
                    if (null == context.CorrelationId)
                    {
                        context.CorrelationId = NewId.NextGuid();
                        headerCorrelationId   = context.CorrelationId.ToString();
                        context.Headers.Set(Consts.CorrelationIdHeaderKey, headerCorrelationId);

                        _logger.LogWarning("CorrelationSendContextFilter unable to find a Correlation-ID.  Using new ID: {Correlation-ID}", headerCorrelationId);
                    }
                    else
                    {
                        _logger.LogWarning("CorrelationSendContextFilter found Correlation-ID in context: {Correlation-ID}", headerCorrelationId);
                    }
                }
                else // found Correlation-ID already exists in message header
                {
                    var correlationGuid = Guid.Empty;

                    if (Guid.TryParse(headerCorrelationId, out correlationGuid))
                    {
                        _logger.LogInformation("CorrelationSendContextFilter found Guid Correlation-ID in header: {Correlation-ID}", headerCorrelationId);
                    }
                    else
                    {
                        // Use current Guid correlationId if it is already set in the message else generate a new one.
                        correlationGuid = context.CorrelationId ?? NewId.NextGuid();
                        _logger.LogInformation("CorrelationSendContextFilter found a Correlation-ID in header that was not a Guid. " +
                                               "Associating header correlationId={headerCorrelationId} to message correlationId={loggingCorrelationId}",
                                               headerCorrelationId, correlationGuid.ToString());
                    }
                    context.Headers.Set(Consts.CorrelationIdHeaderKey, correlationGuid.ToString());
                    context.CorrelationId = correlationGuid;
                }
            }
            else // found _correlationContextAccessor, confirm it is a guid and use it for message/context Correlation-ID also
            {
                context.Headers.Set(Consts.CorrelationIdHeaderKey, headerCorrelationId);

                var correlationGuid = Guid.Empty;

                if (Guid.TryParse(headerCorrelationId, out correlationGuid))
                {
                    _logger.LogInformation("CorrelationSendContextFilter found Guid Correlation-ID in CorrelationContextAccessor: {Correlation-ID}", headerCorrelationId);
                }
                else
                {
                    // Use current Guid correlationId if it is already set in the message else generate a new one.
                    correlationGuid = context.CorrelationId ?? NewId.NextGuid();
                    _logger.LogInformation("CorrelationSendContextFilter found a Correlation-ID in CorrelationContextAccessor that was not a Guid. " +
                                           "Associate header correlationId={headerCorrelationId} to message correlationId={loggingCorrelationId}",
                                           headerCorrelationId, correlationGuid.ToString());
                }
                context.CorrelationId = correlationGuid;
            }

            await next.Send(context);
        }
示例#12
0
        async void HandleMessage(IMessage message)
        {
            if (IsStopping)
            {
                await WaitAndAbandonMessage(message).ConfigureAwait(false);

                return;
            }

            using (var delivery = _tracker.BeginDelivery())
            {
                var context = new ActiveMqReceiveContext(_inputAddress, message, _receiveObserver, _context);

                context.GetOrAddPayload(() => _errorTransport);
                context.GetOrAddPayload(() => _deadLetterTransport);

                context.GetOrAddPayload(() => _receiveSettings);
                context.GetOrAddPayload(() => _session);
                context.GetOrAddPayload(() => _session.ConnectionContext);

                try
                {
                    if (!_pending.TryAdd(message.NMSMessageId, context))
                    {
                        if (_log.IsErrorEnabled)
                        {
                            _log.ErrorFormat("Duplicate BasicDeliver: {0}", message.NMSMessageId);
                        }
                    }

                    await _receiveObserver.PreReceive(context).ConfigureAwait(false);

                    await _receivePipe.Send(context).ConfigureAwait(false);

                    await context.CompleteTask.ConfigureAwait(false);

                    message.Acknowledge();

                    await _receiveObserver.PostReceive(context).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    await _receiveObserver.ReceiveFault(context, ex).ConfigureAwait(false);

                    try
                    {
//                        _session.BasicNack(deliveryTag, false, true);
                    }
                    catch (Exception ackEx)
                    {
                        if (_log.IsErrorEnabled)
                        {
                            _log.ErrorFormat("An error occurred trying to NACK a message with delivery tag {0}: {1}", message.NMSMessageId, ackEx.ToString());
                        }
                    }
                }
                finally
                {
                    _pending.TryRemove(message.NMSMessageId, out _);

                    context.Dispose();
                }
            }
        }
示例#13
0
            public Task Send(ConsumeContext <T> context, IPipe <ConsumeContext <T> > next)
            {
                _validator.Validate(context.Message);

                return(next.Send(context));
            }
示例#14
0
 public async Task Compensate(IParcelaEmitida message)
 {
     await _pipeCompensacao.Send(new CompensacaoContext <EventoEmissaoPremio>(message));
 }
示例#15
0
            public Task Send(SendContext <TMessage> context)
            {
                context.SetRoutingKey(_queueName);

                return(_pipe?.Send(context) ?? TaskUtil.Completed);
            }
示例#16
0
 public Task Send(ConsumeContext <T> context, IPipe <ConsumeContext <T> > next)
 {
     _taskCompletionSource.TrySetResult(_myId);
     return(next.Send(context));
 }
示例#17
0
        async Task SendUsingNewModel(IPipe<ModelContext> modelPipe, ModelScope scope, CancellationToken cancellationToken)
        {
            IPipe<ConnectionContext> connectionPipe = Pipe.ExecuteAsync<ConnectionContext>(async connectionContext =>
            {
                IModel model = await connectionContext.CreateModel().ConfigureAwait(false);

                EventHandler<ShutdownEventArgs> modelShutdown = null;
                modelShutdown = (obj, reason) =>
                {
                    model.ModelShutdown -= modelShutdown;

                    Interlocked.CompareExchange(ref _scope, null, scope);

                    scope.Close();
                };

                model.ModelShutdown += modelShutdown;

                var modelContext = new RabbitMqModelContext(connectionContext, model, connectionContext.CancellationToken);

                scope.Connected(modelContext);

                try
                {
                    using (SharedModelContext context = await scope.Attach(cancellationToken).ConfigureAwait(false))
                    {
                        await modelPipe.Send(context).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    if (_log.IsDebugEnabled)
                        _log.Debug("The existing model usage threw an exception", ex);

                    Interlocked.CompareExchange(ref _scope, null, scope);

                    scope.Close();

                    throw;
                }
            });

            try
            {
                await _connectionCache.Send(connectionPipe, new CancellationToken()).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The connection threw an exception", exception);

                Interlocked.CompareExchange(ref _scope, null, scope);

                throw;
            }
        }
示例#18
0
        public async Task <IProposta> Execute(IProposta contrato)
        {
            await _pipelineImplantacao.Send(new ImplantacaoContext(contrato));

            return(contrato);
        }
        async void Receiver(IPipe<ConnectionContext> connectionPipe, TaskSupervisor supervisor)
        {
            try
            {
                await _connectionRetryPolicy.RetryUntilCancelled(async () =>
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Connecting receive transport: {0}", _host.Settings.GetInputAddress(_settings.QueueDescription));

                    var context = new ServiceBusConnectionContext(_host, supervisor.StoppedToken);

                    try
                    {
                        await connectionPipe.Send(context).ConfigureAwait(false);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    catch (Exception ex)
                    {
                        if (_log.IsErrorEnabled)
                            _log.ErrorFormat("Azure Service Bus connection failed: {0}", ex.Message);

                        var inputAddress = context.GetQueueAddress(_settings.QueueDescription);

                        await _endpointObservers.Faulted(new Faulted(inputAddress, ex)).ConfigureAwait(false);
                    }
                }, supervisor.StoppingToken).ConfigureAwait(false);
            }
            catch (TaskCanceledException)
            {
            }
        }
示例#20
0
 public async Task Compensate(IProposta contrato)
 {
     await _pipeCompensacao.Send(new CompensacaoContext <EventoImplantacao>(contrato));
 }
        async Task Receiver(CancellationToken stopTokenSource, IPipe<ConnectionContext> connectionPipe)
        {
            await Repeat.UntilCancelled(stopTokenSource, async () =>
            {
                if (_log.IsDebugEnabled)
                    _log.DebugFormat("Connecting receive transport: {0}", _host.Settings.GetInputAddress(_settings.QueueDescription));

                var context = new ServiceBusConnectionContext(_host, stopTokenSource);

                try
                {
                    await connectionPipe.Send(context).ConfigureAwait(false);
                }
                catch (TaskCanceledException)
                {
                }
                catch (Exception ex)
                {
                    if (_log.IsErrorEnabled)
                        _log.ErrorFormat("Azure Service Bus connection failed: {0}", ex.Message);

                    Uri inputAddress = context.GetQueueAddress(_settings.QueueDescription);

                    await _endpointObservers.Faulted(new Faulted(inputAddress, ex));
                }
            }).ConfigureAwait(false);
        }
示例#22
0
        public async Task Send(SendEndpointContext context, IPipe <SendEndpointContext> next)
        {
            await ConfigureTopology(context).ConfigureAwait(false);

            await next.Send(context).ConfigureAwait(false);
        }
示例#23
0
            public async Task Send(BindContext <InputContext, Thing> context, IPipe <BindContext <InputContext, Thing> > next)
            {
                _completed.SetResult(context.SourceContext);

                await next.Send(context);
            }
示例#24
0
        public Task Send(SendContext <T> context, IPipe <SendContext <T> > next)
        {
            _setCorrelationId.SetCorrelationId(context);

            return(next.Send(context));
        }
示例#25
0
        public async Task Send(ConsumeContext <T> context, IPipe <ConsumeContext <T> > next)
        {
            await using IMessageScopeContext <T> scope = await _scopeProvider.GetScope(context).ConfigureAwait(false);

            await next.Send(scope.Context).ConfigureAwait(false);
        }
示例#26
0
 public async Task Compensate(IAporteApropriado message)
 {
     await _pipeCompensacao.Send(new CompensacaoContext <EventoAportePremio>(message));
 }
        public Task Send(IPipe <EventDataSendEndpointContext> pipe, CancellationToken cancellationToken = default)
        {
            var sharedContext = new SharedEventDataSendEndpointContext(_context, cancellationToken);

            return(pipe.Send(sharedContext));
        }
示例#28
0
 public async Task Send(PublishContext context, IPipe <PublishContext> next)
 {
     _taskCompletionSource.TrySetResult(context);
     await next.Send(context);
 }
示例#29
0
            public async Task Send(ModelContext modelContext)
            {
                LogContext.SetCurrentIfNull(_context.LogContext);

                await _context.ConfigureTopologyPipe.Send(modelContext).ConfigureAwait(false);

                var properties = modelContext.Model.CreateBasicProperties();

                var context = new BasicPublishRabbitMqSendContext <T>(properties, _context.Exchange, _message, _cancellationToken);

                await _pipe.Send(context).ConfigureAwait(false);

                var exchange = context.Exchange;

                if (exchange.Equals(RabbitMqExchangeNames.ReplyTo))
                {
                    if (string.IsNullOrWhiteSpace(context.RoutingKey))
                    {
                        throw new TransportException(context.DestinationAddress, "RoutingKey must be specified when sending to reply-to address");
                    }

                    exchange = "";
                }

                var activity = LogContext.IfEnabled(OperationName.Transport.Send)?.StartSendActivity(context);

                try
                {
                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PreSend(context).ConfigureAwait(false);
                    }

                    byte[] body = context.Body;

                    if (context.TryGetPayload(out PublishContext publishContext))
                    {
                        context.Mandatory = context.Mandatory || publishContext.Mandatory;
                    }

                    if (properties.Headers == null)
                    {
                        properties.Headers = new Dictionary <string, object>();
                    }

                    properties.ContentType = context.ContentType.MediaType;

                    properties.Headers["Content-Type"] = context.ContentType.MediaType;

                    SetHeaders(properties.Headers, context.Headers);

                    properties.Persistent = context.Durable;

                    if (context.MessageId.HasValue)
                    {
                        properties.MessageId = context.MessageId.ToString();
                    }

                    if (context.CorrelationId.HasValue)
                    {
                        properties.CorrelationId = context.CorrelationId.ToString();
                    }

                    if (context.TimeToLive.HasValue)
                    {
                        properties.Expiration = (context.TimeToLive > TimeSpan.Zero ? context.TimeToLive.Value : TimeSpan.FromSeconds(1)).TotalMilliseconds
                                                .ToString("F0", CultureInfo.InvariantCulture);
                    }

                    if (context.RequestId.HasValue && (context.ResponseAddress?.AbsolutePath?.EndsWith(RabbitMqExchangeNames.ReplyTo) ?? false))
                    {
                        context.BasicProperties.ReplyTo = RabbitMqExchangeNames.ReplyTo;
                    }

                    var publishTask = modelContext.BasicPublishAsync(exchange, context.RoutingKey ?? "", context.Mandatory, context.BasicProperties, body,
                                                                     context.AwaitAck);

                    await publishTask.OrCanceled(context.CancellationToken).ConfigureAwait(false);

                    context.LogSent();

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PostSend(context).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    context.LogFaulted(ex);

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.SendFault(context, ex).ConfigureAwait(false);
                    }

                    throw;
                }
                finally
                {
                    activity?.Stop();
                }
            }
示例#30
0
        async Task ISendTransport.Send <T>(T message, IPipe <SendContext <T> > pipe, CancellationToken cancellationToken)
        {
            if (IsStopped)
            {
                throw new TransportUnavailableException($"The RabbitMQ send transport is stopped: {_exchange}");
            }

            IPipe <ModelContext> modelPipe = Pipe.New <ModelContext>(p =>
            {
                p.UseFilter(_filter);

                p.UseExecuteAsync(async modelContext =>
                {
                    var properties = modelContext.Model.CreateBasicProperties();

                    var context = new BasicPublishRabbitMqSendContext <T>(properties, _exchange, message, cancellationToken);
                    try
                    {
                        await pipe.Send(context).ConfigureAwait(false);

                        byte[] body = context.Body;

                        if (context.TryGetPayload(out PublishContext publishContext))
                        {
                            context.Mandatory = context.Mandatory || publishContext.Mandatory;
                        }

                        if (properties.Headers == null)
                        {
                            properties.Headers = new Dictionary <string, object>();
                        }

                        properties.ContentType = context.ContentType.MediaType;

                        properties.Headers["Content-Type"] = context.ContentType.MediaType;

                        properties.Headers.SetTextHeaders(context.Headers, (_, text) => text);

                        properties.Persistent = context.Durable;

                        if (context.MessageId.HasValue)
                        {
                            properties.MessageId = context.MessageId.ToString();
                        }

                        if (context.CorrelationId.HasValue)
                        {
                            properties.CorrelationId = context.CorrelationId.ToString();
                        }

                        if (context.TimeToLive.HasValue)
                        {
                            properties.Expiration = context.TimeToLive.Value.TotalMilliseconds.ToString("F0", CultureInfo.InvariantCulture);
                        }

                        await _observers.PreSend(context).ConfigureAwait(false);

                        var publishTask = modelContext.BasicPublishAsync(context.Exchange, context.RoutingKey ?? "", context.Mandatory,
                                                                         context.BasicProperties, body, context.AwaitAck);

                        await publishTask.WithCancellation(context.CancellationToken).ConfigureAwait(false);

                        context.LogSent();

                        await _observers.PostSend(context).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        context.LogFaulted(ex);

                        await _observers.SendFault(context, ex).ConfigureAwait(false);

                        throw;
                    }
                });
            });

            await _modelContextSupervisor.Send(modelPipe, cancellationToken).ConfigureAwait(false);
        }
示例#31
0
        static async Task SendUsingExistingModel(IPipe<ModelContext> modelPipe, ModelScope existingScope, CancellationToken cancellationToken)
        {
            try
            {
                using (SharedModelContext context = await existingScope.Attach(cancellationToken))
                {
                    await modelPipe.Send(context);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The existing model usage threw an exception", ex);

                throw;
            }
        }
示例#32
0
            public async Task Send(ClientContext clientContext)
            {
                LogContext.SetCurrentIfNull(_context.LogContext);

                await _context.ConfigureTopologyPipe.Send(clientContext).ConfigureAwait(false);

                var context = new TransportAmazonSqsSendContext <T>(_message, _cancellationToken);

                await _pipe.Send(context).ConfigureAwait(false);

                var activity = LogContext.IfEnabled(OperationName.Transport.Send)?.StartSendActivity(context);

                try
                {
                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PreSend(context).ConfigureAwait(false);
                    }

                    var message = new SendMessageBatchRequestEntry("", Encoding.UTF8.GetString(context.Body));

                    _context.SqsSetHeaderAdapter.Set(message.MessageAttributes, context.Headers);

                    _context.SqsSetHeaderAdapter.Set(message.MessageAttributes, "Content-Type", context.ContentType.MediaType);
                    _context.SqsSetHeaderAdapter.Set(message.MessageAttributes, nameof(context.CorrelationId), context.CorrelationId);

                    if (!string.IsNullOrEmpty(context.DeduplicationId))
                    {
                        message.MessageDeduplicationId = context.DeduplicationId;
                    }

                    if (!string.IsNullOrEmpty(context.GroupId))
                    {
                        message.MessageGroupId = context.GroupId;
                    }

                    if (context.DelaySeconds.HasValue)
                    {
                        message.DelaySeconds = context.DelaySeconds.Value;
                    }

                    await clientContext.SendMessage(_context.EntityName, message, context.CancellationToken).ConfigureAwait(false);

                    context.LogSent();

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PostSend(context).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    context.LogFaulted(ex);

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.SendFault(context, ex).ConfigureAwait(false);
                    }

                    throw;
                }
                finally
                {
                    activity?.Stop();
                }
            }
示例#33
0
        async Task SendUsingExistingModel(IPipe<ModelContext> modelPipe, ModelScope existingScope, CancellationToken cancellationToken)
        {
            try
            {
                using (SharedModelContext context = await existingScope.Attach(cancellationToken).ConfigureAwait(false))
                {
                    await modelPipe.Send(context).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The existing model usage threw an exception", ex);

                Interlocked.CompareExchange(ref _scope, null, existingScope);

                existingScope.Close();

                throw;
            }
        }
示例#34
0
        async Task ISendTransport.Move(ReceiveContext context, IPipe <SendContext> pipe)
        {
            IPipe <ModelContext> modelPipe = Pipe.New <ModelContext>(p =>
            {
                p.UseFilter(_filter);

                p.UseExecuteAsync(async modelContext =>
                {
                    Guid?messageId = context.TransportHeaders.Get("MessageId", default(Guid?));

                    try
                    {
                        IBasicProperties properties;

                        RabbitMqBasicConsumeContext basicConsumeContext;
                        if (context.TryGetPayload(out basicConsumeContext))
                        {
                            properties = basicConsumeContext.Properties;
                        }
                        else
                        {
                            properties         = modelContext.Model.CreateBasicProperties();
                            properties.Headers = new Dictionary <string, object>();
                        }

                        var moveContext = new RabbitMqMoveContext(context, properties);

                        await pipe.Send(moveContext);

//                        properties.Headers["Content-Type"] = context.ContentType.MediaType;

//                        if (messageId.HasValue)
//                            properties.MessageId = messageId.ToString();

                        byte[] body;
                        using (var memoryStream = new MemoryStream())
                        {
                            using (Stream bodyStream = context.GetBody())
                            {
                                bodyStream.CopyTo(memoryStream);
                            }

                            body = memoryStream.ToArray();
                        }

                        Task task = modelContext.BasicPublishAsync(_sendSettings.ExchangeName, "", true, false, properties, body);
                        context.AddPendingTask(task);

                        if (_log.IsDebugEnabled)
                        {
                            context.InputAddress.LogMoved(modelContext.ConnectionContext.HostSettings.GetSendAddress(_sendSettings),
                                                          messageId?.ToString() ?? "N/A", "Moved");
                        }
                    }
                    catch (Exception ex)
                    {
                        if (_log.IsErrorEnabled)
                        {
                            _log.Error("Move To Error Queue Fault: " + _sendSettings.ExchangeName, ex);
                        }

                        throw;
                    }
                });
            });

            await _modelCache.Send(modelPipe, context.CancellationToken);
        }
示例#35
0
 public Task Send(SendContext <TMessage> context)
 {
     return(_pipe?.Send(context) ?? TaskUtil.Completed);
 }
示例#36
0
        async Task ISendTransport.Send <T>(T message, IPipe <SendContext <T> > pipe, CancellationToken cancelSend)
        {
            IPipe <ModelContext> modelPipe = Pipe.New <ModelContext>(p =>
            {
                p.UseFilter(_filter);

                p.UseExecuteAsync(async modelContext =>
                {
                    IBasicProperties properties = modelContext.Model.CreateBasicProperties();

                    var context = new RabbitMqSendContextImpl <T>(properties, message, _sendSettings, cancelSend);

                    try
                    {
                        await pipe.Send(context);

                        properties.ContentType = context.ContentType.MediaType;

                        properties.Headers = (properties.Headers ?? Enumerable.Empty <KeyValuePair <string, object> >())
                                             .Concat(context.Headers.GetAll())
                                             .Where(x => x.Value != null && (x.Value is string || x.Value.GetType().IsValueType))
                                             .Distinct()
                                             .ToDictionary(entry => entry.Key, entry => entry.Value);
                        properties.Headers["Content-Type"] = context.ContentType.MediaType;

                        properties.Persistent = context.Durable;

                        if (context.MessageId.HasValue)
                        {
                            properties.MessageId = context.MessageId.ToString();
                        }

                        if (context.CorrelationId.HasValue)
                        {
                            properties.CorrelationId = context.CorrelationId.ToString();
                        }

                        if (context.TimeToLive.HasValue)
                        {
                            properties.Expiration = context.TimeToLive.Value.TotalMilliseconds.ToString("F0", CultureInfo.InvariantCulture);
                        }

                        await _observers.PreSend(context);

                        await modelContext.BasicPublishAsync(context.Exchange, context.RoutingKey, context.Mandatory,
                                                             context.Immediate, context.BasicProperties, context.Body);

                        context.DestinationAddress.LogSent(context.MessageId?.ToString("N") ?? "", TypeMetadataCache <T> .ShortName);

                        await _observers.PostSend(context);
                    }
                    catch (Exception ex)
                    {
                        _observers.SendFault(context, ex).Wait(cancelSend);

                        if (_log.IsErrorEnabled)
                        {
                            _log.Error("Send Fault: " + context.DestinationAddress, ex);
                        }

                        throw;
                    }
                });
            });

            await _modelCache.Send(modelPipe, cancelSend);
        }
示例#37
0
        async Task SendUsingExistingModel(IPipe<ModelContext> modelPipe, ModelScope scope, CancellationToken cancellationToken)
        {
            try
            {
                using (var context = await scope.Attach(cancellationToken).ConfigureAwait(false))
                {
//                    if (_log.IsDebugEnabled)
//                        _log.DebugFormat("Using model: {0}", ((ModelContext)context).ConnectionContext.HostSettings.ToDebugString());

                    await modelPipe.Send(context).ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The model usage threw an exception", exception);

                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.CreateFaulted(exception);

                throw;
            }
        }
            public async Task Send(SessionContext sessionContext)
            {
                LogContext.SetCurrentIfNull(_context.LogContext);

                await _context.ConfigureTopologyPipe.Send(sessionContext).ConfigureAwait(false);

                var destination = await sessionContext.GetDestination(_context.EntityName, _context.DestinationType).ConfigureAwait(false);

                var producer = await sessionContext.CreateMessageProducer(destination).ConfigureAwait(false);

                var context = new TransportActiveMqSendContext <T>(_message, _cancellationToken);

                await _pipe.Send(context).ConfigureAwait(false);

                StartedActivity?activity = LogContext.IfEnabled(OperationName.Transport.Send)?.StartSendActivity(context);

                try
                {
                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PreSend(context).ConfigureAwait(false);
                    }

                    var transportMessage = sessionContext.Session.CreateBytesMessage();

                    transportMessage.Properties.SetHeaders(context.Headers);

                    transportMessage.Properties["Content-Type"] = context.ContentType.MediaType;

                    transportMessage.NMSDeliveryMode = context.Durable ? MsgDeliveryMode.Persistent : MsgDeliveryMode.NonPersistent;

                    if (context.MessageId.HasValue)
                    {
                        transportMessage.NMSMessageId = context.MessageId.ToString();
                    }

                    if (context.CorrelationId.HasValue)
                    {
                        transportMessage.NMSCorrelationID = context.CorrelationId.ToString();
                    }

                    if (context.TimeToLive.HasValue)
                    {
                        transportMessage.NMSTimeToLive = context.TimeToLive > TimeSpan.Zero ? context.TimeToLive.Value : TimeSpan.FromSeconds(1);
                    }

                    if (context.Priority.HasValue)
                    {
                        transportMessage.NMSPriority = context.Priority.Value;
                    }

                    transportMessage.Content = context.Body;

                    var publishTask = Task.Run(() => producer.Send(transportMessage), context.CancellationToken);

                    await publishTask.OrCanceled(context.CancellationToken).ConfigureAwait(false);

                    context.LogSent();
                    activity.AddSendContextHeadersPostSend(context);

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PostSend(context).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    context.LogFaulted(ex);

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.SendFault(context, ex).ConfigureAwait(false);
                    }

                    throw;
                }
                finally
                {
                    activity?.Stop();
                }
            }
        static async Task SendUsingExistingConnection(IPipe<ConnectionContext> connectionPipe, CancellationToken cancellationToken, ConnectionScope scope)
        {
            try
            {
                using (SharedConnectionContext context = await scope.Attach(cancellationToken))
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Using existing connection: {0}", ((ConnectionContext)context).HostSettings.ToDebugString());

                    await connectionPipe.Send(context);
                }
            }
            catch (Exception ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The existing connection usage threw an exception", ex);

                throw;
            }
        }
            public async Task Send(SendEndpointContext clientContext)
            {
                LogContext.SetCurrentIfNull(_context.LogContext);

                var context = new AzureServiceBusSendContext <T>(_message, _cancellationToken);

                await _pipe.Send(context).ConfigureAwait(false);

                CopyIncomingIdentifiersIfPresent(context);

                StartedActivity?activity = LogContext.IfEnabled(OperationName.Transport.Send)?.StartSendActivity(context,
                                                                                                                 (nameof(context.PartitionKey), context.PartitionKey),
                                                                                                                 (nameof(context.SessionId), context.SessionId));

                try
                {
                    if (IsCancelScheduledSend(context, out var sequenceNumber))
                    {
                        await CancelScheduledSend(clientContext, sequenceNumber).ConfigureAwait(false);

                        return;
                    }

                    if (context.ScheduledEnqueueTimeUtc.HasValue)
                    {
                        var scheduled = await ScheduleSend(clientContext, context).ConfigureAwait(false);

                        if (scheduled)
                        {
                            return;
                        }
                    }

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PreSend(context).ConfigureAwait(false);
                    }

                    var message = CreateMessage(context);

                    await clientContext.Send(message).ConfigureAwait(false);

                    context.LogSent();
                    activity.AddSendContextHeadersPostSend(context);

                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.PostSend(context).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    if (_context.SendObservers.Count > 0)
                    {
                        await _context.SendObservers.SendFault(context, ex).ConfigureAwait(false);
                    }

                    throw;
                }
                finally
                {
                    activity?.Stop();
                }
            }
示例#41
0
        async Task SendUsingExistingClient(IPipe<ClientContext> clientPipe, ClientScope scope, CancellationToken cancellationToken)
        {
            try
            {
                using (var context = await scope.Attach(cancellationToken).ConfigureAwait(false))
                {
                    await clientPipe.Send(context).ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The client usage threw an exception", exception);

                Interlocked.CompareExchange(ref _scope, null, scope);

                scope.CreateFaulted(exception);

                throw;
            }
        }
        Task IPipe <SendContext <TMessage> > .Send(SendContext <TMessage> context)
        {
            Send(context);

            return(_pipe.IsNotEmpty() ? _pipe.Send(context) : Task.CompletedTask);
        }
示例#43
0
 public void HandleMessage(object message, IPipe pipe)
 {
     Console.WriteLine("[SERVER] Message from client: {0}", message);
     pipe.Send("Thanks for sending '" + message + "'");
 }
        async Task SendUsingExistingConnection(IPipe<ConnectionContext> connectionPipe, CancellationToken cancellationToken, ConnectionScope scope)
        {
            try
            {
                using (SharedConnectionContext context = await scope.Attach(cancellationToken).ConfigureAwait(false))
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Using existing connection: {0}", ((ConnectionContext)context).HostSettings.ToDebugString());

                    await connectionPipe.Send(context).ConfigureAwait(false);
                }
            }
            catch (BrokerUnreachableException ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The connection usage threw an exception", ex);

                throw new RabbitMqConnectionException("Connect failed: " + _connectionFactory.ToDebugString(), ex);
            }
            catch (Exception ex)
            {
                if (_log.IsDebugEnabled)
                    _log.Debug("The existing connection usage threw an exception", ex);

                throw;
            }
        }