Пример #1
0
        public async Task IncludesFullErrorDetailsWhenSecondLevelRetriesFailToo()
        {
            var counter = new SharedCounter(1);

            Using(counter);

            _activator.Handle <string>(async str =>
            {
                throw new ApplicationException("1st level!!");
            });

            _activator.Handle <IFailed <string> >(async failed =>
            {
                throw new ApplicationException("2nd level!!");
            });

            await _bus.SendLocal("hej med dig!");

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

            var errorDetails = transportMessage.Headers[Headers.ErrorDetails];

            Console.WriteLine(errorDetails);

            Assert.That(errorDetails, Does.Contain("1st level!!"));
            Assert.That(errorDetails, Does.Contain("2nd level!!"));
        }
        public async Task CanForwardToMultipleRecipients()
        {
            var network   = new InMemNetwork();
            var activator = new BuiltinHandlerActivator();

            Using(activator);

            var recipients = new[] { "recipient-A", "recipient-B" }.ToList();

            recipients.ForEach(network.CreateQueue);

            Configure.With(activator)
            .Transport(t => t.UseInMemoryTransport(network, "forwarder"))
            .Routing(t =>
            {
                t.AddTransportMessageForwarder(async transportMessage => ForwardAction.ForwardTo(recipients));
            })
            .Start();

            await activator.Bus.SendLocal("HEJ MED DIG!!!");

            var transportMessages = await Task.WhenAll(recipients.Select(async queue =>
            {
                var message = await network.WaitForNextMessageFrom(queue);

                return(message);
            }));

            Assert.That(transportMessages.Length, Is.EqualTo(2));
        }
Пример #3
0
    public async Task CanRevealNumberOfRetries()
    {
        var retryCounts = new ConcurrentQueue <int>();
        var activator   = Using(new BuiltinHandlerActivator());

        // create random header key every time to verify that it is actually used
        var headerKey = $"retry-count/{Guid.NewGuid()}";

        activator.Handle <Fail>(async(_, context, _) =>
        {
            Console.WriteLine($@"Got message {context.TransportMessage.GetMessageId()}:
{string.Join(Environment.NewLine, context.Headers.Select(kvp => $"    {kvp.Key}: {kvp.Value}"))}");

            retryCounts.Enqueue(int.Parse(context.Headers.GetValue(headerKey)));

            throw new Exception("oh no!");
        });

        var network = new InMemNetwork();

        var bus = Configure.With(activator)
                  .Transport(t => t.UseInMemoryTransport(network, "who-cares"))
                  .Options(o => o.AddRetryCountHeader(key: headerKey))
                  .Options(o => o.LogPipeline(verbose: true))
                  .Start();

        // send message that will fail
        await bus.SendLocal(new Fail());

        // wait until the message is dead-lettered
        _ = await network.WaitForNextMessageFrom("error");

        Assert.That(retryCounts.Count, Is.EqualTo(5));
        Assert.That(retryCounts.ToArray(), Is.EqualTo(new[] { 0, 1, 2, 3, 4 }));
    }
Пример #4
0
    public async Task CanMoveMessageToErrorQueueEvenThoughExceptionIsNotSerializable()
    {
        using (var activator = new BuiltinHandlerActivator())
        {
            activator.Handle <string>(async str =>
            {
                throw new ThisOneCannotBeSerialized("BAM!!!!!!!!!!!11111111111111111");
            });

            var network = new InMemNetwork();

            var bus = Configure.With(activator)
                      .Transport(t => t.UseInMemoryTransport(network, "unserializable exceptions"))
                      .Options(o => o.SimpleRetryStrategy(maxDeliveryAttempts: 1))
                      .Start();

            const string knownString = "JUST SOME LISP!!!!11((((((((((((((((((()))))))))))))))))))))))";

            await bus.SendLocal(knownString);

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

            Assert.That(Encoding.UTF8.GetString(failedMessage.Body), Is.EqualTo(JsonConvert.SerializeObject(knownString)));
        }
    }
    public async Task ItWorks()
    {
        var network = new InMemNetwork();
        var builder = new ContainerBuilder();
        var stuff   = new ConcurrentQueue <string>();

        builder.RegisterInstance(stuff);

        builder.RegisterRebus(configure =>
                              configure
                              .Logging(l => l.None())
                              .Transport(t => t.UseInMemoryTransport(network, "test"))
                              .Options(o => o.SimpleRetryStrategy(secondLevelRetriesEnabled: true, maxDeliveryAttempts: 1))
                              );

        builder.RegisterHandler <MyTestHandler>();

        await using var container = builder.Build();

        var bus = container.Resolve <IBus>();

        Console.WriteLine("Sending message");
        await bus.SendLocal("hej søtte!");

        Console.WriteLine("Waiting for message to arrive in queue 'done'...");
        await network.WaitForNextMessageFrom("done");

        Console.WriteLine("Got the message!");

        Assert.That(stuff.Count, Is.EqualTo(1),
                    "Expected second level handler to have been called only once!!");
    }
Пример #6
0
        public async Task CopiesProperlyHandledMessageToAuditQueue()
        {
            var gotTheMessage = new ManualResetEvent(false);

            _adapter.Handle <string>(async _ =>
            {
                gotTheMessage.Set();
            });

            await _bus.SendLocal("woohooo!!!!");

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

            var message = await _network.WaitForNextMessageFrom("audit");

            PrintHeaders(message);

            Assert.That(message.Headers.ContainsKey(AuditHeaders.AuditTime));
            Assert.That(message.Headers.ContainsKey(AuditHeaders.HandleTime));
            Assert.That(message.Headers.ContainsKey(Headers.Intent));
            Assert.That(message.Headers[Headers.Intent], Is.EqualTo(Headers.IntentOptions.PointToPoint));
        }
Пример #7
0
        public async Task ItWorks()
        {
            const int numberOfRetries = 5;

            InitializeBus(numberOfRetries);

            var attemptedDeliveries = 0;

            _handlerActivator.AddHandlerWithBusTemporarilyStopped <string>(async _ =>
            {
                Interlocked.Increment(ref attemptedDeliveries);
                throw new RebusApplicationException("omgwtf!");
            });

            await _bus.Send("hej");

            var failedMessage = await _network.WaitForNextMessageFrom(ErrorQueueName);

            Assert.That(attemptedDeliveries, Is.EqualTo(numberOfRetries));
            Assert.That(failedMessage.Headers.GetValue(Headers.ErrorDetails), Contains.Substring("5 unhandled exceptions"));
            Assert.That(failedMessage.Headers.GetValue(Headers.SourceQueue), Is.EqualTo(InputQueueName));
        }
Пример #8
0
        public async Task DeferredMessageHasDeferCountOf1()
        {
            var bus = _starter.Start();

            await bus.Defer(TimeSpan.FromSeconds(0.001), "HEJ MED DIG MIN VEN");

            var message = await _network.WaitForNextMessageFrom(DestinationAddress);

            var headers = message.Headers;

            Assert.That(headers.Keys, Contains.Item("rbs2-defer-count"));
            Assert.That(int.Parse(headers["rbs2-defer-count"]), Is.EqualTo(1));
        }
        public async Task CanRetryForever()
        {
            const string recipientQueueName = "recipient";
            var          network            = new InMemNetwork();
            var          activator          = new BuiltinHandlerActivator();

            Using(activator);

            network.CreateQueue(recipientQueueName);

            var bus = GetFailingBus(activator, network, recipientQueueName, ErrorBehavior.RetryForever);

            await bus.SendLocal("HEJ MED DIG!!!");

            var message = await network.WaitForNextMessageFrom(recipientQueueName);

            Assert.That(Encoding.UTF8.GetString(message.Body), Is.EqualTo(@"""HEJ MED DIG!!!"""));
        }
        public async Task ContinuationsCanStillUseTheBus()
        {
            const string queueName = "another-queue";

            _network.CreateQueue(queueName);

            _activator.Bus.Advanced.Workers.SetNumberOfWorkers(1);

            var gotMessage          = new ManualResetEvent(false);
            var doneHandlingMessage = new ManualResetEvent(false);

            _activator.Handle <string>(async(bus, message) =>
            {
                gotMessage.Set();

                Printt("Got message - waiting 3 s...");

                await Task.Delay(3000);

                Printt("Done waiting :)");

                await bus.Advanced.Routing.Send(queueName, "JAJA DET VIRKER!");

                doneHandlingMessage.Set();
            });

            // send message
            await _activator.Bus.SendLocal("hej med dig");

            // wait for message to be received and then immediately shutdown the bus
            gotMessage.WaitOrDie(TimeSpan.FromSeconds(3), "Did not receive message within timeout");

            CleanUpDisposables();

            // wait for message to have been handled to end
            doneHandlingMessage.WaitOrDie(TimeSpan.FromSeconds(6), "Did not finish handling the message within expected timeframe");

            // wait for message to pop up in the expected queue
            var transportMessage = await _network.WaitForNextMessageFrom(queueName);

            Assert.That(Encoding.UTF8.GetString(transportMessage.Body), Is.EqualTo(@"""JAJA DET VIRKER!"""));
        }
        public async Task CanFailFastAndForwardToErrorQueue()
        {
            const string recipientQueueName = "recipient";
            var          network            = new InMemNetwork();
            var          activator          = new BuiltinHandlerActivator();

            Using(activator);

            network.CreateQueue(recipientQueueName);

            var bus = GetFailingBus(activator, network, recipientQueueName, ErrorBehavior.ForwardToErrorQueue);

            await bus.SendLocal("HEJ MED DIG!!!");

            var message = await network.WaitForNextMessageFrom("error");

            Assert.That(Encoding.UTF8.GetString(message.Body), Is.EqualTo(@"""HEJ MED DIG!!!"""));
            Assert.That(message.Headers.GetValueOrNull(Headers.SourceQueue), Is.EqualTo("forwarder"));
            Assert.That(message.Headers.GetValueOrNull(Headers.ErrorDetails), Does.Contain("fake an error"));
        }
Пример #12
0
        public async Task ComeOn_InMemory()
        {
            using var activator = new BuiltinHandlerActivator();

            activator.Register((bús, context) => new TestMessageHandler(context, bús.Advanced.TransportMessage));

            var network = new InMemNetwork();

            var bus = Configure.With(activator)
                      .Logging(l => l.None())
                      .Transport(t => t.UseInMemoryTransport(network, "whatever-man"))
                      .Options(o => o.SimpleRetryStrategy(secondLevelRetriesEnabled: true))
                      .Timeouts(t => t.StoreInMemory())
                      .Start();

            await bus.SendLocal(new TestMessage("yo!"));

            var message = await network.WaitForNextMessageFrom("error", timeoutSeconds : 25);

            Assert.That(message.DeserializeTo <TestMessage>().Text, Is.EqualTo("yo!"));
        }
        public async Task ErrorInErrorQueue()
        {
            var network   = new InMemNetwork();
            var activator = Using(new BuiltinHandlerActivator());

            // count send operations to error queue with this one
            var sendToErrorQueueAttempts = 0;

            // hook into send operations
            void SendCallback(string queue)
            {
                if (queue != "error")
                {
                    return;                   //< don't care about other queues
                }
                sendToErrorQueueAttempts++;

                // fail on the very first attempt
                if (sendToErrorQueueAttempts == 1)
                {
                    throw new ApplicationException("FAILURE ON FIRST ATTEMPT!");
                }
            }

            Configure.With(activator)
            .Transport(t => t.UseInMemoryTransport(network, "whatever"))
            .Routing(r => r.AddTransportMessageForwarder(async msg => throw new AbandonedMutexException("oh no it's been abandoned")))
            .Options(o => o.Decorate <ITransport>(c => new FailureTransportDecorator(SendCallback, c.Get <ITransport>())))
            .Start();

            await activator.Bus.SendLocal("HEJ MED DIG MIN VEN");

            var failedMessage = await network.WaitForNextMessageFrom("error", timeoutSeconds : 10);

            var receivedString = Encoding.UTF8.GetString(failedMessage.Body);

            Assert.That(receivedString, Is.EqualTo("\"HEJ MED DIG MIN VEN\""));
        }