public async Task Invoke(IncomingTransportContext context, IBusForHandler bus, Func<Task> next)
        {
            ExceptionDispatchInfo serializationException = null;
            try
            {
                await next()
                    .ConfigureAwait(false);
            }
            catch (SerializationException exception)
            {
                // We can't do async in a catch block, therefore we have to capture the exception!
                serializationException = ExceptionDispatchInfo.Capture(exception);
            }

            if (SerializationExceptionHasBeenCaught(serializationException))
            {
                var message = context.TransportMessage;

// ReSharper disable PossibleNullReferenceException
                message.SetFailureHeaders(serializationException.SourceException, "Messages which can't be deserialized are deadlettered immediately");
// ReSharper restore PossibleNullReferenceException
                await message.DeadLetterAsync()
                    .ConfigureAwait(false);

                // Because we instructed the message to deadletter it is safe to rethrow. The broker will not redeliver.
                serializationException.Throw();
            }
        }
        public async Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func <Task> next)
        {
            ExceptionDispatchInfo exceptionDispatchInfo = null;

            try
            {
                await next()
                .ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                if (ShouldMessageBeDelayed(context))
                {
                    // We can't do async in a catch block, therefore we have to capture the exception!
                    exceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception);
                }
                else
                {
                    throw;
                }
            }

            if (exceptionDispatchInfo != null)
            {
                var message = context.TransportMessage;
                var scheduledEnqueueTimeUtc = DateTime.UtcNow
                                              + TimeSpan.FromSeconds(DelayTimeSpanInSeconds(context));

                message.DelayedDeliveryCount++;
                await bus.Postpone(context.LogicalMessage.Instance, scheduledEnqueueTimeUtc);

                // Don't rethrow, the current message is consumed and a new message is postponed.
            }
        }
        public async Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func <Task> next)
        {
            var messageType = context.LogicalMessage.Instance.GetType();

            var handlers = registry.GetHandlers(messageType);

            foreach (var handler in handlers)
            {
                var messageHandler = new MessageHandler
                {
                    Instance   = handler,
                    Invocation = (handlerInstance, message) => registry.InvokeHandle(handlerInstance, message, bus)
                };

                context.Handler = messageHandler;

                await next()
                .ConfigureAwait(false);

                if (context.HandlerInvocationAbortPending)
                {
                    break;
                }
            }
        }
Example #4
0
        public async Task Invoke(IncomingTransportContext context, IBusForHandler bus, Func <Task> next)
        {
            ExceptionDispatchInfo serializationException = null;

            try
            {
                await next()
                .ConfigureAwait(false);
            }
            catch (SerializationException exception)
            {
                // We can't do async in a catch block, therefore we have to capture the exception!
                serializationException = ExceptionDispatchInfo.Capture(exception);
            }

            if (SerializationExceptionHasBeenCaught(serializationException))
            {
                var message = context.TransportMessage;

// ReSharper disable PossibleNullReferenceException
                message.SetFailureHeaders(serializationException.SourceException, "Messages which can't be deserialized are deadlettered immediately");
// ReSharper restore PossibleNullReferenceException
                await message.DeadLetterAsync()
                .ConfigureAwait(false);

                // Because we instructed the message to deadletter it is safe to rethrow. The broker will not redeliver.
                serializationException.Throw();
            }
        }
        public async Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func <Task> next)
        {
            ExceptionDispatchInfo exceptionDispatchInfo = null;

            try
            {
                await next()
                .ConfigureAwait(false);
            }
            catch (DeadletterMessageImmediatelyException exception)
            {
                // We can't do async in a catch block, therefore we have to capture the exception!
                exceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception);
            }

            if (HandleMessageCriticalExceptionHasBeenCaught(exceptionDispatchInfo))
            {
                var message = context.TransportMessage;

                // ReSharper disable PossibleNullReferenceException
                var exceptionToHeader = exceptionDispatchInfo.SourceException.InnerException ?? exceptionDispatchInfo.SourceException;
                message.SetFailureHeaders(exceptionToHeader, "Message is deadlettered immediately on DeadletterMessageImmediatelyException");
                // ReSharper restore PossibleNullReferenceException
                await message.DeadLetterAsync()
                .ConfigureAwait(false);

                // Because we instructed the message to deadletter it is safe to rethrow. The broker will not redeliver.
                // Already deadlettered message should not be unlocked - throw for it
                exceptionDispatchInfo.Throw();
            }
        }
        public async Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func<Task> next)
        {
            var messageType = context.LogicalMessage.Instance.GetType();

            var handlers = registry.GetHandlers(messageType);

            foreach (var handler in handlers)
            {
                using (context.CreateSnapshot())
                {
                    var messageHandler = new MessageHandler
                    {
                        Instance = handler,
                        Invocation = (handlerInstance, message) => registry.InvokeHandle(handlerInstance, message, bus)
                    };

                    context.Handler = messageHandler;

                    await next()
                        .ConfigureAwait(false);

                    if (context.HandlerInvocationAbortPending)
                    {
                        break;
                    }
                }
            }
        }
        public virtual Task InvokeHandle(object handler, object message, IBusForHandler bus)
        {
            dynamic h = handler;
            dynamic m = message;

            return(h.Handle(m, bus));
        }
        public async Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func <Task> next)
        {
            ExceptionDispatchInfo serializationException = null;

            try
            {
                await next()
                .ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                if (IsRetryCountReached(context))
                {
                    // We can't do async in a catch block, therefore we have to capture the exception!
                    serializationException = ExceptionDispatchInfo.Capture(exception);
                }
                else
                {
                    throw;
                }
            }

            if (serializationException != null)
            {
                var message = context.TransportMessage;

                message.SetFailureHeaders(serializationException.SourceException, "Max number of retries has been reached!");
                await message.DeadLetterAsync()
                .ConfigureAwait(false);

                // Because we instructed the message to deadletter it is safe to rethrow. The broker will not redeliver.
                serializationException.Throw();
            }
        }
        public async Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func<Task> next)
        {
            ExceptionDispatchInfo serializationException = null;
            try
            {
                await next()
                    .ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                if (IsRetryCountReached(context))
                {
                    // We can't do async in a catch block, therefore we have to capture the exception!
                    serializationException = ExceptionDispatchInfo.Capture(exception);
                }
                else
                {
                    throw;
                }
            }

            if (serializationException != null)
            {
                var message = context.TransportMessage;

                message.SetFailureHeaders(serializationException.SourceException, "Max number of retries has been reached!");
                await message.DeadLetterAsync()
                    .ConfigureAwait(false);

                // Because we instructed the message to deadletter it is safe to rethrow. The broker will not redeliver.
                serializationException.Throw();
            }
        }
Example #10
0
 public void Handle(Message message, IBusForHandler bus)
 {
     this.context.HandlerCalled();
     bus.Reply(new ReplyMessage {
         Answer = "MessageHandler"
     }).Wait();
 }
        public Task Handle(object message, IBusForHandler bus)
        {
            IDictionary <string, string> headers = bus.Headers(message);

            var exceptionMessage = string.Format(CultureInfo.InvariantCulture, "The message with id {0} of type {1} has been rejected.", headers[HeaderKeys.MessageId], message.GetType());

            throw new InvalidOperationException(exceptionMessage);
        }
Example #12
0
 public Task Handle(Message message, IBusForHandler bus)
 {
     context.SecondHandlerCalls += 1;
     return(bus.Reply(new ReplyMessage
     {
         Answer = "SecondHandler"
     }));
 }
            public void Handle(Message message, IBusForHandler bus)
            {
                this.context.HandlerCalled();

                if (message.AbortSync)
                {
                    bus.DoNotContinueDispatchingCurrentMessageToHandlers();
                }
            }
            public void Handle(Message message, IBusForHandler bus)
            {
                Debug.WriteLine("Sync {0}", message.Bar);
                if (message.Bar % 2 == 0)
                {
                    throw new InvalidOperationException();
                }

                this.context.HandlerCalled();
            }
            public async Task Handle(Message message, IBusForHandler bus)
            {
                this.context.AsyncHandlerCalls += 1;
                await bus.Reply(new ReplyMessage { Answer = "AsyncMessageHandler" });

                var options = new ReplyOptions();

                options.Headers.Add("Key", "Value");
                await bus.Reply(new ReplyMessage { Answer = "AsyncMessageHandlerWithHeaders" }, options);
            }
            public Task Handle(ReplyMessage message, IBusForHandler bus)
            {
                this.context.ReplyHandlerCalls += 1;
                if (bus.Headers(message).ContainsKey("Key"))
                {
                    this.context.HeaderValue = bus.Headers(message)["Key"];
                }

                return(Task.FromResult(0));
            }
            public void Handle(Message message, IBusForHandler bus)
            {
                Debug.WriteLine("{0}s: Sync {1}, delayed {2}", DateTime.Now.Subtract(startTime).Seconds, message.Bar, bus.Headers(message)[HeaderKeys.DelayedDeliveryCount]);
                if (message.Bar % 2 == 0)
                {
                    throw new InvalidOperationException();
                }

                this.context.HandlerCalled();
            }
        public async Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func <Task> next)
        {
            var messageHandler = context.Handler;

            await messageHandler.Invocation(messageHandler.Instance, context.LogicalMessage.Instance)
            .ConfigureAwait(false);

            await next()
            .ConfigureAwait(false);
        }
Example #19
0
            public Task Handle(ReplyMessage message, IBusForHandler bus)
            {
                context.ReplyHandlerCalls += 1;
                if (bus.Headers(message).ContainsKey("Key"))
                {
                    context.HeaderValue = bus.Headers(message)["Key"];
                }

                return(Task.CompletedTask);
            }
Example #20
0
        public async Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func<Task> next)
        {
            var messageHandler = context.Handler;

            await messageHandler.Invocation(messageHandler.Instance, context.LogicalMessage.Instance)
                .ConfigureAwait(false);

            await next()
                .ConfigureAwait(false);
        }
        private Task InvokeTransport(IncomingTransportContext context, IBusForHandler bus)
        {
            if (this.executingTransportPipeline.Count == 0)
            {
                return(Task.FromResult(0));
            }

            IIncomingTransportStep step = this.executingTransportPipeline.Dequeue();

            return(step.Invoke(context, bus, () => this.InvokeTransport(context, bus)));
        }
Example #22
0
            public Task Handle(Message message, IBusForHandler bus)
            {
                context.FirstHandlerCalls += 1;

                if (message.AbortFirstHandler)
                {
                    bus.DoNotContinueDispatchingCurrentMessageToHandlers();
                }

                return(Task.CompletedTask);
            }
            public Task Handle(AsyncMessage message, IBusForHandler bus)
            {
                Debug.WriteLine("ASync {0}, delayed {1}", message.Bar, bus.Headers(message)[HeaderKeys.DelayedDeliveryCount]);
                if (message.Bar % 2 == 0)
                {
                    throw new InvalidOperationException();
                }

                this.context.HandlerCalled();
                return(Task.FromResult(0));
            }
Example #24
0
        Task InvokeLogical(IncomingLogicalContext context, IBusForHandler bus)
        {
            if (executingLogicalPipeline.Count == 0)
            {
                return(Task.FromResult(0));
            }

            IIncomingLogicalStep step = executingLogicalPipeline.Dequeue();

            return(step.Invoke(context, bus, () => InvokeLogical(context, bus)));
        }
            public Task Handle(AsyncMessage message, IBusForHandler bus)
            {
                Debug.WriteLine("Async {0}", message.Bar);
                if (message.Bar % 2 == 0)
                {
                    throw new InvalidOperationException();
                }

                this.context.HandlerCalled();
                return(Task.FromResult(0));
            }
Example #26
0
        Task InvokeLogical(IncomingLogicalContext context, IBusForHandler bus, int currentIndex = 0)
        {
            if (currentIndex == registeredLogicalPipeline.Count)
            {
                return(Task.CompletedTask);
            }

            IIncomingLogicalStep step = registeredLogicalPipeline[currentIndex];

            return(step.Invoke(context, bus, () => InvokeLogical(context, bus, currentIndex + 1)));
        }
            public Task Handle(Message message, IBusForHandler bus)
            {
                this.context.AsyncHandlerCalled();

                if (message.AbortAsync)
                {
                    bus.DoNotContinueDispatchingCurrentMessageToHandlers();
                }

                return(Task.FromResult(0));
            }
Example #28
0
            public async Task Handle(Message message, IBusForHandler bus)
            {
                this.context.AsyncHandlerCalled();

                await bus.Reply(new ReplyMessage { Bar = message.Bar });

                if (message.Throw)
                {
                    throw new InvalidOperationException();
                }
            }
        Task InvokeLogical(IncomingLogicalContext context, IBusForHandler bus, int currentIndex = 0)
        {
            if (currentIndex == registeredLogicalPipeline.Count)
            {
                return Task.CompletedTask;
            }

            IIncomingLogicalStep step = registeredLogicalPipeline[currentIndex];

            return step.Invoke(context, bus, () => InvokeLogical(context, bus, currentIndex + 1));
        }
Example #30
0
        Task InvokeTransport(IncomingTransportContext context, IBusForHandler bus, int currentIndex = 0)
        {
            if (currentIndex == registeredTransportPipeline.Count)
            {
                return(Task.CompletedTask);
            }

            IIncomingTransportStep step = registeredTransportPipeline[currentIndex];

            return(step.Invoke(context, bus, () => InvokeTransport(context, bus, currentIndex + 1)));
        }
            public Task Handle(Message message, IBusForHandler bus)
            {
                context.SecondHandlerCalls += 1;

                if (message.AbortSecondHandler)
                {
                    bus.DoNotContinueDispatchingCurrentMessageToHandlers();
                }

                return(Task.FromResult(0));
            }
            public async Task Handle(Message message, IBusForHandler bus)
            {
                var        time      = TimeSpan.FromSeconds(6);
                IRenewLock renewLock = bus as IRenewLock;

                context.Start();
                await Task.Delay(time);

                renewLock?.RenewLock();
                await Task.Delay(time);

                this.context.Done();
            }
Example #33
0
            public Task Handle(Message message, IBusForHandler bus)
            {
                int    delayedDeliveryCount;
                string delayedDeliveryCountString;

                bus.Headers(message).TryGetValue(HeaderKeys.DelayedDeliveryCount, out delayedDeliveryCountString);
                int.TryParse(delayedDeliveryCountString, out delayedDeliveryCount);
                if (delayedDeliveryCount == actualDelayedRetryCount)
                {
                    throw new InvalidOperationException();
                }

                return(Task.FromResult(0));
            }
        public async Task Invoke(IBusForHandler bus, TransportMessage message, EndpointConfiguration.ReadOnly configuration)
        {
            var transportContext = new IncomingTransportContext(message, configuration);
            await InvokeTransport(transportContext, bus)
                .ConfigureAwait(false);

            // We assume that someone in the pipeline made logical message
            var logicalMessage = transportContext.Get<LogicalMessage>();

            var logicalContext = new IncomingLogicalContext(logicalMessage, message, configuration);
            currentContext = logicalContext;
            await InvokeLogical(logicalContext, bus)
                .ConfigureAwait(false);
        }
Example #35
0
        public Task Invoke(IncomingTransportContext context, IBusForHandler bus, Func <Task> next)
        {
            var transportMessage = context.TransportMessage;

            try
            {
                context.Set(Extract(transportMessage));
            }
            catch (Exception exception)
            {
                throw new SerializationException(string.Format("An error occurred while attempting to extract logical messages from transport message {0}", transportMessage), exception);
            }

            return(next());
        }
        public Task Invoke(IncomingTransportContext context, IBusForHandler bus, Func<Task> next)
        {
            var transportMessage = context.TransportMessage;

            try
            {
                context.Set(this.Extract(transportMessage));
            }
            catch (Exception exception)
            {
                throw new SerializationException(string.Format("An error occurred while attempting to extract logical messages from transport message {0}", transportMessage), exception);
            }

            return next();
        }
Example #37
0
        public async Task Invoke(IBusForHandler bus, TransportMessage message, EndpointConfiguration.ReadOnly configuration)
        {
            var transportContext = new IncomingTransportContext(message, configuration);

            await InvokeTransport(transportContext, bus)
            .ConfigureAwait(false);

            // We assume that someone in the pipeline made logical message
            var logicalMessage = transportContext.Get <LogicalMessage>();

            var logicalContext = new IncomingLogicalContext(logicalMessage, message, configuration);

            currentContext = logicalContext;
            await InvokeLogical(logicalContext, bus)
            .ConfigureAwait(false);
        }
Example #38
0
        public async Task Invoke(IBusForHandler bus, TransportMessage message, EndpointConfiguration.ReadOnly configuration)
        {
            executingTransportPipeline = new Queue<IIncomingTransportStep>(registeredTransportPipeline);
            var transportContext = new IncomingTransportContext(message, configuration);
            transportContext.SetChain(this);
            await InvokeTransport(transportContext, bus)
                .ConfigureAwait(false);

            // We assume that someone in the pipeline made logical message
            var logicalMessage = transportContext.Get<LogicalMessage>();

            executingLogicalPipeline = new Queue<IIncomingLogicalStep>(registeredLogicalPipeline);
            var logicalContext = new IncomingLogicalContext(logicalMessage, message, configuration);
            logicalContext.SetChain(this);
            currentContext = logicalContext;
            await InvokeLogical(logicalContext, bus)
                .ConfigureAwait(false);
        }
        public async Task Invoke(IncomingTransportContext context, IBusForHandler bus, Func<Task> next)
        {
            try
            {
                await next()
                    .ConfigureAwait(false);
            }
            catch (SerializationException exception)
            {
                var message = context.TransportMessage;

                message.SetFailureHeaders(exception, "Messages which can't be deserialized are deadlettered immediately");
                await deadLetter.DeadLetterAsync(message)
                    .ConfigureAwait(false);

                // Because we instructed the message to deadletter it is safe to rethrow. The broker will not redeliver.
                throw;
            }
        }
        public async Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func<Task> next)
        {
            try
            {
                await next()
                    .ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                var message = context.TransportMessage;
                if (IsRetryCountReached(context))
                {
                    message.SetFailureHeaders(exception, "Max number of retries has been reached!");

                    // C# 6 can do this!
                    await deadLetter.DeadLetterAsync(message).ConfigureAwait(false);
                }
                else
                {
                    message.DeliveryCount++;
                    throw;
                }
            }
        }
            public Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func<Task> next)
            {
                var step = this.factory();

                return step.Invoke(context, bus, next);
            }
        Task InvokeTransport(IncomingTransportContext context, IBusForHandler bus, int currentIndex = 0)
        {
            if (currentIndex == registeredTransportPipeline.Count)
            {
                return Task.CompletedTask;
            }

            IIncomingTransportStep step = registeredTransportPipeline[currentIndex];

            return step.Invoke(context, bus, () => InvokeTransport(context, bus, currentIndex + 1));
        }
Example #43
0
        Task InvokeLogical(IncomingLogicalContext context, IBusForHandler bus)
        {
            if (executingLogicalPipeline.Count == 0)
            {
                return Task.FromResult(0);
            }

            IIncomingLogicalStep step = executingLogicalPipeline.Dequeue();

            return step.Invoke(context, bus, () => InvokeLogical(context, bus));
        }
Example #44
0
            public Task Invoke(IncomingTransportContext context, IBusForHandler bus, Func<Task> next)
            {
                var step = factory();

                return step.Invoke(context, bus, next);
            }
Example #45
0
        Task InvokeTransport(IncomingTransportContext context, IBusForHandler bus)
        {
            if (executingTransportPipeline.Count == 0)
            {
                return Task.FromResult(0);
            }

            IIncomingTransportStep step = executingTransportPipeline.Dequeue();

            return step.Invoke(context, bus, () => InvokeTransport(context, bus));
        }
Example #46
0
 public Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func<Task> next)
 {
     this.collector.Add(context.LogicalMessage);
     return next();
 }
 public Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func<Task> next)
 {
     var delay = 100;
     return InvokeWithDelay(context, next, delay);
 }
Example #48
0
 public virtual Task InvokeHandle(object handler, object message, IBusForHandler bus)
 {
     dynamic h = handler;
     dynamic m = message;
     return h.Handle(m, bus);
 }