<|start_filename|>Rebus.Async.Tests/DoesNotUseTheseCharactersInMessageIdHeaderValue.cs<|end_filename|>
﻿using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using Rebus.Activation;
using Rebus.Config;
using Rebus.Extensions;
using Rebus.Messages;
using Rebus.Routing.TypeBased;
using Rebus.Tests.Contracts;
using Rebus.Transport;
using Rebus.Transport.InMem;

namespace Rebus.Async.Tests
{
    [TestFixture]
    public class DoesNotUseTheseCharactersInMessageIdHeaderValue : FixtureBase
    {
        [Test]
        [Description("Solves the special case where Amazon SQS refuses to send messages, because the rbs2-msg-id header is transferred as a native SQS message ID, and those are only allowed to contain alphanumeric characters and _ and -")]
        public async Task ItsTrueItDoesnt()
        {
            var activator = new BuiltinHandlerActivator();

            Using(activator);

            activator.Handle<TestRequest>(async (bus, request) => await bus.Reply(new TestReply()));

            var network = new InMemNetwork();

            var client = Configure.With(activator)
                .Transport(t =>
                {
                    t.UseInMemoryTransport(network, "test-queue");
                    t.Decorate(c => new ThrowOnInvalidCharactersTransportDecorator(c.Get<ITransport>()));
                })
                .Routing(t => t.TypeBased().Map<TestRequest>("test-queue"))
                .Options(o => o.EnableSynchronousRequestReply())
                .Start();

            var reply = await client.SendRequest<TestReply>(new TestRequest());

            Assert.That(reply, Is.TypeOf<TestReply>());
        }

        class TestRequest { }
        class TestReply { }

        class ThrowOnInvalidCharactersTransportDecorator : ITransport
        {
            readonly ITransport _transport;
            readonly Regex _validMessageIdRegex = new Regex("^[a-zA-Z0-9\\-_]+$");

            public ThrowOnInvalidCharactersTransportDecorator(ITransport transport)
            {
                _transport = transport;
            }

            public void CreateQueue(string address) => _transport.CreateQueue(address);

            public string Address => _transport.Address;

            public Task<TransportMessage> Receive(ITransactionContext context, CancellationToken cancellationToken) => _transport.Receive(context, cancellationToken);

            public Task Send(string destinationAddress, TransportMessage message, ITransactionContext context)
            {
                var headers = message.Headers;
                var messageId = headers.GetValue(Headers.MessageId);

                if (!_validMessageIdRegex.IsMatch(messageId))
                {
                    throw new ArgumentException($@"Sorry, but the message ID

    {messageId}

contains one or more invalid characters.");
                }

                return _transport.Send(destinationAddress, message, context);
            }
        }
    }
}

<|start_filename|>Rebus.Async.Tests/VerifyThatCleanupHappensAutomatically.cs<|end_filename|>
﻿using System;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using Rebus.Activation;
using Rebus.Config;
using Rebus.Exceptions;
using Rebus.Logging;
using Rebus.Routing.TypeBased;
using Rebus.Tests.Contracts;
using Rebus.Transport.InMem;
// ReSharper disable RedundantArgumentDefaultValue
// ReSharper disable ArgumentsStyleLiteral
// ReSharper disable UnusedVariable

namespace Rebus.Async.Tests
{
    [TestFixture]
    public class VerifyThatCleanupHappensAutomatically : FixtureBase
    {
        [TestCase(100)]
        [TestCase(1000)]
        [TestCase(10000)]
        public async Task ItSureDoes(int count)
        {
            var network = new InMemNetwork(outputEventsToConsole: false);
            var server = Using(new BuiltinHandlerActivator());

            server.Handle<SimpleRequest>((bus, request) =>
            {
                if (request.Number % 97 == 0)
                {
                    throw new TripUpTheHandlerException();
                }
                return bus.Reply(new SimpleReply());
            });

            Configure.With(server)
                .Logging(l => l.None())
                .Transport(t => t.UseInMemoryTransport(network, "server"))
                .Options(o => o.EnableSynchronousRequestReply())
                .Start();

            var client = Using(new BuiltinHandlerActivator());

            Configure.With(client)
                .Logging(l => l.None())
                .Transport(t => t.UseInMemoryTransport(network, "client"))
                .Routing(r => r.TypeBased().Map<SimpleRequest>("server"))
                .Options(o => o.EnableSynchronousRequestReply())
                .Start();

            var operations = Enumerable.Range(0, count)
                .Select(async n =>
                {
                    try
                    {
                        var reply = await client.Bus.SendRequest<SimpleReply>(new SimpleRequest(n));

                        // some will complete,
                    }
                    catch (TimeoutException)
                    {
                        // others will time out
                    }
                })
                .ToList();

            await Task.WhenAll(operations);

            Assert.That(AsyncBusExtensions.Messages.Count, Is.EqualTo(0), 
                "There should be exactly zero task completion sources in the dictionary by now");
        }

        class SimpleRequest
        {
            public int Number { get; }

            public SimpleRequest(int number)
            {
                Number = number;
            }
        }
        class SimpleReply { }

        class TripUpTheHandlerException : Exception, IFailFastException
        {
        }
    }
}

<|start_filename|>Rebus.Async/Config/AsyncConfigurationExtensions.cs<|end_filename|>
﻿using System;
using Rebus.Internals;
using Rebus.Logging;
using Rebus.Pipeline;
using Rebus.Pipeline.Receive;

namespace Rebus.Config
{
    /// <summary>
    /// Configuration extensions for Async
    /// </summary>
    public static class AsyncConfigurationExtensions
    {
        /// <summary>
        /// Enables async/await-based request/reply whereby a request can be sent using the <see cref="AsyncBusExtensions.SendRequest{TReply}"/> method
        /// which can be awaited for a corresponding reply.
        /// </summary>
        public static void EnableSynchronousRequestReply(this OptionsConfigurer configurer)
        {
            if (configurer == null) throw new ArgumentNullException(nameof(configurer));

            configurer.Register(c =>
            {
                var rebusLoggerFactory = c.Get<IRebusLoggerFactory>();
                var step = new ReplyHandlerStep(AsyncBusExtensions.Messages, rebusLoggerFactory);
                return step;
            });

            configurer.Decorate<IPipeline>(c =>
            {
                var pipeline = c.Get<IPipeline>();
                var step = c.Get<ReplyHandlerStep>();
                return new PipelineStepInjector(pipeline)
                    .OnReceive(step, PipelineRelativePosition.Before, typeof(ActivateHandlersStep));
            });
        }

    }
}

<|start_filename|>Rebus.Async/Internals/ReplyHandlerStep.cs<|end_filename|>
﻿using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Rebus.Logging;
using Rebus.Messages;
using Rebus.Pipeline;

#pragma warning disable 1998

namespace Rebus.Internals
{
    [StepDocumentation("Handles replies to requests sent with bus.SendRequest")]
    class ReplyHandlerStep : IIncomingStep
    {
        readonly ConcurrentDictionary<string, TaskCompletionSource<Message>> _messages;
        readonly ILog _log;

        public ReplyHandlerStep(ConcurrentDictionary<string, TaskCompletionSource<Message>> messages, IRebusLoggerFactory rebusLoggerFactory)
        {
            _messages = messages ?? throw new ArgumentNullException(nameof(messages));
            _log = rebusLoggerFactory?.GetLogger<ReplyHandlerStep>() ?? throw new ArgumentNullException(nameof(rebusLoggerFactory));
        }

        public const string SpecialMessageIdPrefix = "request-reply";

        public async Task Process(IncomingStepContext context, Func<Task> next)
        {
            var message = context.Load<Message>();

            var hasInReplyToHeader = message.Headers.TryGetValue(Headers.InReplyTo, out var inReplyToMessageId);

            if (hasInReplyToHeader)
            {
                var isRequestReplyCorrelationId = inReplyToMessageId.StartsWith(SpecialMessageIdPrefix);

                if (isRequestReplyCorrelationId)
                {
                    // if we could successfully remove the task completion source for the request message ID,
                    // we can complete it here
                    if (_messages.TryRemove(inReplyToMessageId, out var taskCompletionSource))
                    {
                        taskCompletionSource.SetResult(message);

                        // abort anything else in the pipeline
                        return;
                    }

                    _log.Warn("Received message with message ID {messageId}, which was determined to be a reply to be handled as an inline request-reply reply (because of the {prefix} prefix), BUT the dictionary of task completion sources did NOT contain an entry for that ID",
                        inReplyToMessageId, SpecialMessageIdPrefix);
                }
            }

            await next();
        }
    }
}

<|start_filename|>Rebus.Async.Tests/DoesNotDeadlock.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using Rebus.Activation;
using Rebus.Config;
using Rebus.Routing.TypeBased;
using Rebus.Tests.Contracts;
using Rebus.Transport.InMem;
#pragma warning disable 1998

namespace Rebus.Async.Tests
{
    [TestFixture]
    public class DoesNotDeadlock : FixtureBase
    {
        readonly InMemNetwork _network = new InMemNetwork(true);

        protected override void SetUp()
        {
            _network.Reset();
        }

        [Test]
        public async Task CanDoItInHandler()
        {
            var replier = CreateBus("server");
            replier.Activator.Handle<string>(async (bus, context, text) =>
            {
                await bus.Reply($"Got text: {text}");
            });
            replier.BusStarter.Start();

            var requestor = CreateBus("requestor");

            requestor.Activator.Handle<Request>(async (bus, context, request) =>
            {
                var texts = new List<string>();

                for (var index = 0; index < request.Count; index++)
                {
                    Console.WriteLine("SENDING REQUEST");
                    var result = await bus.SendRequest<string>($"Text {index}");
                    Console.WriteLine("GOT REPLY REQUEST");

                    texts.Add(result);
                }

                await bus.Reply(new Response(texts));
            });
            requestor.BusStarter.Start();

            var client = CreateBus("client");

            var theBus = client.BusStarter.Start();
            var response = await theBus.SendRequest<Response>(new Request(4));

            Assert.That(response.Texts.Count, Is.EqualTo(4));
        }

        class Request
        {
            public int Count { get; }

            public Request(int count)
            {
                Count = count;
            }
        }

        class Response
        {
            public IReadOnlyCollection<string> Texts { get; }

            public Response(IEnumerable<string> texts)
            {
                Texts = texts.ToList();
            }
        }

        class BusWrapper
        {
            public IBusStarter BusStarter;
            public BuiltinHandlerActivator Activator;
        }

        BusWrapper CreateBus(string queueName)
        {
            var activator = new BuiltinHandlerActivator();

            Using(activator);

            var busStarter = Configure.With(activator)
                .Transport(t => t.UseInMemoryTransport(_network, queueName))
                .Routing(r => r.TypeBased()
                    .Map<Request>("requestor")
                    .Map<string>("server"))
                .Options(o => o.EnableSynchronousRequestReply())
                .Create();

            return new BusWrapper
            {
                BusStarter = busStarter,
                Activator = activator,
            };
        }
    }
}

<|start_filename|>Rebus.Async/Internals/InternalsVisibleTo.cs<|end_filename|>
﻿using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Rebus.Async.Tests")]