Exemplo n.º 1
0
        public async Task IncomingMessageHasNoHeaders()
        {
            var gotMessage = false;

            _adapter.Handle <string>(async str => gotMessage = true);

            var body = BodyWith("hej med dig min ven");
            var headersWithoutMessageId = new Dictionary <string, string>();

            _network.Deliver("test", new TransportMessage(headersWithoutMessageId, body).ToInMemTransportMessage());

            await Task.Delay(1000);

            PrintLogs();

            Assert.That(gotMessage, Is.False, "Did not expect to receive the message");

            var loggedErrors = _listLoggerFactory
                               .Where(l => l.Level == LogLevel.Error)
                               .ToList();

            Assert.That(loggedErrors.Count, Is.EqualTo(1));

            var errorLogLine = loggedErrors.Single(e => e.Level == LogLevel.Error);

            Assert.That(errorLogLine.Text, Contains.Substring(
                            $"Received message with empty or absent '{Headers.MessageId}' header"));
        }
Exemplo n.º 2
0
    /// <summary>
    /// Receives the next message from the queue identified by the configured <see cref="AbstractRebusTransport.Address"/>, returning null if none was available
    /// </summary>
    public override async Task <TransportMessage> Receive(ITransactionContext context, CancellationToken cancellationToken)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }
        if (_inputQueueAddress == null)
        {
            throw new InvalidOperationException("This in-mem transport is initialized without an input queue, hence it is not possible to receive anything!");
        }

        var nextMessage = _network.GetNextOrNull(_inputQueueAddress);

        if (nextMessage == null)
        {
            return(null);
        }

        context.OnAborted(_ =>
        {
            _network.Deliver(_inputQueueAddress, nextMessage, alwaysQuiet: true);
        });

        return(nextMessage.ToTransportMessage());
    }
Exemplo n.º 3
0
    public void GetMessages_QueueWithMessages_ReturnsMessages()
    {
        _inMemNetwork.Deliver("input", CreateMessage("Hello"));
        _inMemNetwork.Deliver("input", CreateMessage("World"));

        var messages = _inMemNetwork.GetMessages("input");

        Assert.That(messages.Count, Is.EqualTo(2));
        AssertMessage(messages[0], "Hello");
        AssertMessage(messages[1], "World");
    }
Exemplo n.º 4
0
    public void CanSendAndReceive()
    {
        var messageId = Guid.NewGuid().ToString();
        var transportMessageToSend = GetTransportMessage(messageId);

        _network.Deliver("bimse", transportMessageToSend.ToInMemTransportMessage());

        var receivedTransportMessage = _network.GetNextOrNull("bimse");

        Assert.That(receivedTransportMessage, Is.Not.Null);
        Assert.That(receivedTransportMessage.Headers.GetValue(Headers.MessageId), Is.EqualTo(messageId));
    }
Exemplo n.º 5
0
        public void DispatchesDynamicMessageWhenDotNetTypeCannotBeFound()
        {
            var gotTheMessage = new ManualResetEvent(false);

            string messageText = null;

            _builtinHandlerActivator.Handle <dynamic>(async message =>
            {
                Console.WriteLine("Received dynamic message: {0}", message);

                messageText = message.something.text;

                gotTheMessage.Set();
            });

            var headers = new Dictionary <string, string>
            {
                { Headers.MessageId, Guid.NewGuid().ToString() },
                { Headers.ContentType, "application/json;charset=utf-8" },
            };

            var transportMessage = new TransportMessage(headers, Encoding.UTF8.GetBytes(@"{
    ""something"": {
        ""text"": ""OMG dynamic JSON BABY!!""
    }
}"));

            _network.Deliver(InputQueueName, new InMemTransportMessage(transportMessage));

            gotTheMessage.WaitOrDie(TimeSpan.FromSeconds(2));

            Assert.That(messageText, Is.EqualTo("OMG dynamic JSON BABY!!"));
        }
Exemplo n.º 6
0
        static TimeSpan RunTest(int numberOfMessages, PipelineStepProfilerStats profilerStats)
        {
            using (var adapter = new BuiltinHandlerActivator())
            {
                var network = new InMemNetwork();

                Configure.With(adapter)
                .Logging(l => l.Console(LogLevel.Warn))
                .Transport(t => t.UseInMemoryTransport(network, "perftest"))
                .Options(o =>
                {
                    o.SetNumberOfWorkers(0);
                    o.SetMaxParallelism(1);

                    o.Decorate <IPipeline>(c => new PipelineStepProfiler(c.Get <IPipeline>(), profilerStats));
                    o.Register <IPipelineInvoker>(c => new DefaultPipelineInvoker(c.Get <IPipeline>()));
                })
                .Start();

                var serializer = new SystemTextJsonSerializer(new SimpleAssemblyQualifiedMessageTypeNameConvention());
                var boy        = new SomeMessage("hello there!");

                for (var counter = 0; counter < numberOfMessages; counter++)
                {
                    var headers = new Dictionary <string, string> {
                        { Headers.MessageId, Guid.NewGuid().ToString() }
                    };
                    var message               = new Message(headers, boy);
                    var transportMessage      = serializer.Serialize(message).Result;
                    var inMemTransportMessage = transportMessage.ToInMemTransportMessage();

                    network.Deliver("perftest", inMemTransportMessage);
                }
                ;

                var numberOfReceivedMessages = 0;
                var gotAllMessages           = new ManualResetEvent(false);

                adapter.Handle <SomeMessage>(async m =>
                {
                    Interlocked.Increment(ref numberOfReceivedMessages);

                    if (Volatile.Read(ref numberOfReceivedMessages) == numberOfMessages)
                    {
                        gotAllMessages.Set();
                    }
                });

                var stopwatch = Stopwatch.StartNew();

                adapter.Bus.Advanced.Workers.SetNumberOfWorkers(1);
                gotAllMessages.WaitOrDie(TimeSpan.FromSeconds(30));

                return(stopwatch.Elapsed);
            }
        }
Exemplo n.º 7
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));
        }
Exemplo n.º 8
0
        static TimeSpan RunTest(int numberOfMessages, PipelineStepProfilerStats profilerStats, PipelineInvokerMode pipelineInvokerMode)
        {
            using (var adapter = new BuiltinHandlerActivator())
            {
                var network = new InMemNetwork();

                Configure.With(adapter)
                .Logging(l => l.Console(LogLevel.Warn))
                .Transport(t => t.UseInMemoryTransport(network, "perftest"))
                .Options(o =>
                {
                    o.SetNumberOfWorkers(0);
                    o.SetMaxParallelism(1);

                    o.Decorate <IPipeline>(c => new PipelineStepProfiler(c.Get <IPipeline>(), profilerStats));

                    switch (pipelineInvokerMode)
                    {
                    case PipelineInvokerMode.Default:
                        o.Register <IPipelineInvoker>(c => new DefaultPipelineInvoker(c.Get <IPipeline>()));
                        break;

                    case PipelineInvokerMode.DefaultNew:
                        o.Register <IPipelineInvoker>(c => new DefaultPipelineInvokerNew(c.Get <IPipeline>()));
                        break;

                    case PipelineInvokerMode.Compiled:
                        o.Register <IPipelineInvoker>(c => new CompiledPipelineInvoker(c.Get <IPipeline>()));
                        break;

                    case PipelineInvokerMode.Action:
                        o.Register <IPipelineInvoker>(c => new ActionPipelineInvoker(c.Get <IPipeline>()));
                        break;

                    default:
                        throw new ArgumentOutOfRangeException($"Unknown pipeline invoker: {pipelineInvokerMode}");
                    }
                })
                .Start();

                var serializer = new JsonSerializer();
                var boy        = new SomeMessage("hello there!");

                numberOfMessages.Times(() =>
                {
                    var headers = new Dictionary <string, string> {
                        { Headers.MessageId, Guid.NewGuid().ToString() }
                    };
                    var message               = new Message(headers, boy);
                    var transportMessage      = serializer.Serialize(message).Result;
                    var inMemTransportMessage = transportMessage.ToInMemTransportMessage();

                    network.Deliver("perftest", inMemTransportMessage);
                });

                var numberOfReceivedMessages = 0;
                var gotAllMessages           = new ManualResetEvent(false);

                adapter.Handle <SomeMessage>(async m =>
                {
                    Interlocked.Increment(ref numberOfReceivedMessages);

                    if (Volatile.Read(ref numberOfReceivedMessages) == numberOfMessages)
                    {
                        gotAllMessages.Set();
                    }
                });

                var stopwatch = Stopwatch.StartNew();

                adapter.Bus.Advanced.Workers.SetNumberOfWorkers(1);
                gotAllMessages.WaitOrDie(TimeSpan.FromSeconds(30));

                return(stopwatch.Elapsed);
            }
        }