Exemple #1
0
    private void AssertMessage(InMemTransportMessage message, string expectedBody)
    {
        var body = Encoding.UTF8.GetString(message.Body);

        Assert.That(message.Headers, Is.Empty);
        Assert.That(body, Is.EqualTo(expectedBody));
    }
Exemple #2
0
        public void Send(string topic, TransportMessage message)
        {
            var queue = GetQueueForTopic(topic);
            var inMemTransportMessage = new InMemTransportMessage(message, 1);

            queue.Enqueue(inMemTransportMessage);
        }
Exemple #3
0
    public void Send(string topic, TransportMessage message)
    {
        var inMemTransportMessage = new InMemTransportMessage(
            transportMessage: message,
            offset: Interlocked.Increment(ref _offsetCounter)
            );

        GetQueueForTopic(topic).Enqueue(inMemTransportMessage);
    }
Exemple #4
0
    static bool MessageIsExpired(InMemTransportMessage message)
    {
        var headers = message.Headers;

        if (!headers.ContainsKey(Headers.TimeToBeReceived))
        {
            return(false);
        }

        var timeToBeReceived = headers[Headers.TimeToBeReceived];
        var maximumAge       = TimeSpan.Parse(timeToBeReceived);

        return(message.Age > maximumAge);
    }
Exemple #5
0
        public async Task StillWorksWhenIncomingMessageCannotBeDeserialized()
        {
            const string brokenJsonString = @"{'broken': 'json', // DIE!!1}";

            var headers = new Dictionary <string, string>
            {
                { Headers.MessageId, Guid.NewGuid().ToString() },
                { Headers.ContentType, "application/json;charset=utf-8" },
            };
            var body                  = Encoding.UTF8.GetBytes(brokenJsonString);
            var transportMessage      = new TransportMessage(headers, body);
            var inMemTransportMessage = new InMemTransportMessage(transportMessage);

            _network.Deliver(InputQueueName, inMemTransportMessage);

            var failedMessage = await _network.WaitForNextMessageFrom("error");

            Assert.That(failedMessage, Is.Not.Null);
            var bodyString = Encoding.UTF8.GetString(failedMessage.Body);

            Assert.That(bodyString, Is.EqualTo(brokenJsonString));
        }
Exemple #6
0
    /// <summary>
    /// Delivers the specified <see cref="InMemTransportMessage"/> to the address specified by <paramref name="destinationAddress"/>.
    /// If <paramref name="alwaysQuiet"/> is set to true, no events will ever be printed to <see cref="Console.Out"/>
    /// (can be used by an in-mem transport to return a message to a queue, as if there was a queue transaction that was rolled back)
    /// </summary>
    public void Deliver(string destinationAddress, InMemTransportMessage msg, bool alwaysQuiet = false)
    {
        if (destinationAddress == null)
        {
            throw new ArgumentNullException(nameof(destinationAddress));
        }
        if (msg == null)
        {
            throw new ArgumentNullException(nameof(msg));
        }

        if (!alwaysQuiet)
        {
            var messageId = msg.Headers.GetValueOrNull(Headers.MessageId) ?? "<no message ID>";

            _log.Info($"{messageId} ---> {destinationAddress} ({_networkId})");
        }

        var messageQueue = _queues
                           .GetOrAdd(destinationAddress, address => new ConcurrentQueue <InMemTransportMessage>());

        messageQueue.Enqueue(msg);
    }
        public async Task Given_deadLetter_is_configured_when_receiving_invalid_message_it_should_be_moved_to_error_queue()
        {
            string      messageId       = null;
            TestMessage receivedMessage = null;
            var         sync            = new ManualResetEvent(false);

            var inMemNetwork = new InMemNetwork();
            var activator    = new BuiltinHandlerActivator();

            activator
            .Handle <TestMessage>(message =>
            {
                // This should not happen, but signal completion.
                receivedMessage = message;
                sync.Set();
                return(Task.CompletedTask);
            });

            using (IBus bus = CreateBus(activator,
                                        o =>
            {
                o.ValidateIncomingMessages(_validatorFactoryMock.Object,
                                           v => v.DeadLetter <TestMessage>()
                                           );
                o.OnPipelineCompletion <TestMessage>(failed =>
                {
                    messageId = MessageContext.Current.Message.GetMessageId();
                    sync.Set();
                });
            },
                                        inMemNetwork))
            {
                // Act
                var testMessage = new TestMessage
                {
                    ShouldPassValidation = false
                };

                await bus.Send(testMessage);

                // Assert
                sync.WaitOne(Debugger.IsAttached ? -1 : 5000);

                receivedMessage.Should().BeNull();

                var errorQueueMessages        = inMemNetwork.GetMessages(ErrorQueueName).ToList();
                InMemTransportMessage message = errorQueueMessages.Should()
                                                .HaveCount(1)
                                                .And.Subject.Single();
                message.Headers.Should()
                .ContainKey(Headers.ErrorDetails)
                .WhichValue.Should()
                .Match($"*{nameof(TestMessage.ShouldPassValidation)}: The specified condition was not met*");
                message.Headers.Should()
                .ContainKey(Headers.Type)
                .WhichValue.Should()
                .StartWith(typeof(TestMessage).FullName);
            }

            _loggerFactory.LogEvents
            .Select(le => le.Exception)
            .Should()
            .NotContain(ex => ex is MessageCouldNotBeDispatchedToAnyHandlersException);
            _loggerFactory.LogEvents
            .Select(le => le.ToString())
            .Should()
            .ContainMatch($"Debug: Message \"{messageId}\" failed to validate.*The specified condition was not met for 'Should Pass Validation'.*");
            _loggerFactory.LogEvents
            .Select(le => le.Message)
            .Should()
            .ContainMatch("*is configured to be moved to error queue.")
            .And
            .ContainMatch("Moving message with ID *");
        }
Exemple #8
0
        static void PrintHeaders(InMemTransportMessage message)
        {
            Console.WriteLine(@"Headers:
{0}", string.Join(Environment.NewLine, message.Headers.Select(kvp => string.Format("    {0}: {1}", kvp.Key, kvp.Value))));
        }