public void When_RequestExpired_Then_OnMessageExpiredIsCalled()
        {
            // arrange
            var onMessageExpiredMock = new Mock <Action <IMessageBus, AbstractConsumerSettings, object> >();
            var consumerSettings     = new HandlerBuilder <SomeRequest, SomeResponse>(new MessageBusSettings()).Topic(null).WithHandler <IRequestHandler <SomeRequest, SomeResponse> >().Instances(1).ConsumerSettings;

            consumerSettings.OnMessageExpired = onMessageExpiredMock.Object;

            var p = new ConsumerInstancePoolMessageProcessor <SomeRequest>(consumerSettings, _busMock.Bus, x => Array.Empty <byte>());

            var request        = new SomeRequest();
            var requestMessage = new MessageWithHeaders();

            requestMessage.SetHeader(ReqRespMessageHeaders.Expires, _busMock.CurrentTime.AddSeconds(-10));

            _busMock.BusMock.Setup(x => x.DeserializeRequest(typeof(SomeRequest), It.IsAny <byte[]>(), out requestMessage))
            .Returns(request);

            // act
            p.ProcessMessage(request).Wait();

            // assert
            _busMock.HandlerMock.Verify(x => x.OnHandle(It.IsAny <SomeRequest>(), It.IsAny <string>()), Times.Never); // the handler should not be called

            onMessageExpiredMock.Verify(x => x(_busMock.Bus, consumerSettings, request), Times.Once);                 // callback called once
        }
Beispiel #2
0
        public void WhenRequestExpired_OnMessageExpired_IsCalled()
        {
            // arrange

            var onMessageExpiredMock = new Mock <Action <ConsumerSettings, object> >();
            var consumerSettings     = new ConsumerSettings
            {
                Instances        = 1,
                Topic            = "topic1",
                ConsumerMode     = ConsumerMode.RequestResponse,
                ConsumerType     = typeof(IRequestHandler <SomeRequest, SomeResponse>),
                MessageType      = typeof(SomeRequest),
                OnMessageExpired = onMessageExpiredMock.Object
            };

            var p = new ConsumerInstancePool <SomeRequest>(consumerSettings, _busMock.Object, x => new byte[0]);

            var            request = new SomeRequest();
            string         requestId;
            string         replyTo;
            DateTimeOffset?expires = _currentTime.AddSeconds(-10);

            _busMock.Setup(x => x.DeserializeRequest(typeof(SomeRequest), It.IsAny <byte[]>(), out requestId, out replyTo, out expires)).Returns(request);

            // act
            p.Submit(request);
            var commitedMsg = p.Commit(request);

            // assert
            commitedMsg.Should().BeSameAs(request);                                                           // it should commit the request message
            _handlerMock.Verify(x => x.OnHandle(It.IsAny <SomeRequest>(), It.IsAny <string>()), Times.Never); // the handler should not be called

            onMessageExpiredMock.Verify(x => x(consumerSettings, request), Times.Once);                       // callback called once
        }
Beispiel #3
0
        public void WhenRequestExpiredThenOnMessageExpiredIsCalled()
        {
            // arrange

            var onMessageExpiredMock = new Mock <Action <AbstractConsumerSettings, object> >();
            var consumerSettings     = new ConsumerSettings
            {
                Instances        = 1,
                Topic            = "topic1",
                ConsumerMode     = ConsumerMode.RequestResponse,
                ConsumerType     = typeof(IRequestHandler <SomeRequest, SomeResponse>),
                MessageType      = typeof(SomeRequest),
                OnMessageExpired = onMessageExpiredMock.Object
            };

            var p = new ConsumerInstancePool <SomeRequest>(consumerSettings, _busMock.Bus, x => Array.Empty <byte>());

            var request        = new SomeRequest();
            var requestMessage = new MessageWithHeaders();

            requestMessage.SetHeader(ReqRespMessageHeaders.Expires, _busMock.CurrentTime.AddSeconds(-10));

            _busMock.BusMock.Setup(x => x.DeserializeRequest(typeof(SomeRequest), It.IsAny <byte[]>(), out requestMessage))
            .Returns(request);

            // act
            p.ProcessMessage(request).Wait();

            // assert
            _busMock.HandlerMock.Verify(x => x.OnHandle(It.IsAny <SomeRequest>(), It.IsAny <string>()), Times.Never); // the handler should not be called

            onMessageExpiredMock.Verify(x => x(consumerSettings, request), Times.Once);                               // callback called once
        }
Beispiel #4
0
        public void IncludedCorrelationIdIsAutomaticallyTransferredToReplies()
        {
            // arrange
            var resetEvent = new ManualResetEvent(false);
            adapter.Handle<SomeRequest>(req => bus.Reply(new SomeReply()));

            string receivedCorrelationId = null;
            adapter.Handle<SomeReply>(rep =>
                {
                    var currentHeaders = MessageContext
                        .GetCurrent()
                        .Headers;

                    receivedCorrelationId = currentHeaders.ContainsKey(Headers.CorrelationId)
                                                ? currentHeaders[Headers.CorrelationId].ToString()
                                                : "could not find correlation ID in headers";

                    resetEvent.Set();
                });

            var someRequest = new SomeRequest();
            bus.AttachHeader(someRequest, Headers.CorrelationId, "wootadafook!");

            // act
            bus.SendLocal(someRequest);

            if (!resetEvent.WaitOne(2.Seconds()))
            {
                Assert.Fail("Did not receive any reply withing 2 seconds of waiting");
            }

            // assert
            receivedCorrelationId.ShouldBe("wootadafook!");
        }
        public void ValidRoutesShouldResolve(SomeRequest command, string expected)
        {
            var httpRouteExtractor = new HttpRouteExtractor(AppDomainScanner.ScanForAllTypes);

            var httpRoute = httpRouteExtractor.ExtractHttpRoute(command);

            httpRoute.Should().Be(expected);
        }
 public void SetUp()
 {
     request = new SomeRequest();
     serverAddress = Mock.Of<IServerAddress>();
     packetReceiver = Mock.Of<IPacketReceiver>();
     packetConverter = Mock.Of<IPacketConverter>();
     responseReceiver = new ResponseReveiver(packetReceiver, packetConverter);
 }
 public object Get(SomeRequest request)
 {
     using (var con = DbFactory.OpenConnection())
     {
         //use SqlCeConnection()
     }
     //more code
 }
        public void InvalidRoutesShouldThrow(SomeRequest command)
        {
            var httpRouteExtractor = new HttpRouteExtractor(AppDomainScanner.ScanForAllTypes);

            Action action = () => httpRouteExtractor.ExtractHttpRoute(command);

            action.ShouldThrow <PayloadRoutingException>();
        }
        public void TheHttpMethodShouldBeCorrect()
        {
            var httpRouteExtractor = new HttpRouteExtractor(AppDomainScanner.ScanForAllTypes);

            var request    = new SomeRequest();
            var httpMethod = httpRouteExtractor.ExtractHttpMethod(request);

            httpMethod.Should().Be(System.Net.Http.HttpMethod.Get);
        }
Beispiel #10
0
        public void Moo()
        {
            var client = new JsonClient("http://example.com");
            var req    = new SomeRequest {
                UserId = 5, Banana = "hello"
            };

            Debug.WriteLine(client.BuildUri(req, Method.Get));
        }
Beispiel #11
0
        /// <summary>
        /// No need to have try catch and logging, since that is all done in the SafeExecutor.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static async Task <SomeResponse> SomeWebControllerApi(SomeRequest request)
        {
            Func <SomeRequest, Task <SomeResponse> > function = async(SomeRequest r) =>
            {
                return(await ErrorHelper.ReadResponse <SomeResponse>(await Task.Run(() => { return FakingConnectionOverTheInternet(); })));
            };

            return(await ErrorHelper.SafeExecutor(function, request));
        }
Beispiel #12
0
        private static async Task <SomeResponse> SomeOtherWebController(SomeRequest request)
        {
            //Local function. Short hand for what is in SomeWebController()
            async Task <SomeResponse> function(SomeRequest r)
            {
                return(await ErrorHelper.ReadResponse <SomeResponse>(await Task.Run(() => { return FakingConnectionOverTheInternet(); })));
            }

            return(await ErrorHelper.SafeExecutor(function, request));
        }
        public void SetUp()
        {
            request = new SomeRequest();
            response = new SomeResponse();
            serverAddress = Mock.Of<IServerAddress>();
            responseTypeFinder = Mock.Of<IResponseTypeFinder>();
            responseReveiver = Mock.Of<IResponseReceiver>();

            server = new Server(serverAddress, responseTypeFinder, responseReveiver);

            Mock.Get(responseTypeFinder).Setup(f => f.FindResponseTypeOf(request.GetType())).Returns(typeof(SomeResponse));
            Mock.Get(responseReveiver).Setup(r => r.ReceiveResponseAsync(It.IsAny<IServerAddress>(), It.IsAny<object>(), It.IsAny<Type>())).ReturnsAsync(response);
        }
Beispiel #14
0
        public async Task When_Send_Then_RoutesToProperBus()
        {
            // arrange
            Mock <MessageBusBase> bus1Mock = null;
            Mock <MessageBusBase> bus2Mock = null;

            _providerSettings["bus1"] = (mbb) =>
            {
                mbb.Produce <SomeMessage>(x => x.DefaultTopic("topic1")).WithProvider(mbs =>
                {
                    bus1Mock = new Mock <MessageBusBase>(new[] { mbs });
                    bus1Mock.SetupGet(x => x.Settings).Returns(mbs);
                    bus1Mock.Setup(x => x.Publish(It.IsAny <SomeMessage>(), It.IsAny <string>())).Returns(Task.CompletedTask);

                    return(bus1Mock.Object);
                });
            };
            _providerSettings["bus2"] = (mbb) =>
            {
                mbb.Produce <SomeRequest>(x => x.DefaultTopic("topic2")).WithProvider(mbs =>
                {
                    bus2Mock = new Mock <MessageBusBase>(new[] { mbs });
                    bus2Mock.SetupGet(x => x.Settings).Returns(mbs);
                    bus2Mock.Setup(x => x.Send(It.IsAny <SomeRequest>(), It.IsAny <string>(), default)).Returns(Task.FromResult(new SomeResponse()));

                    return(bus2Mock.Object);
                });
            };

            var someMessage        = new SomeMessage();
            var someDerivedMessage = new SomeDerivedMessage();
            var someRequest        = new SomeRequest();
            var someDerivedRequest = new SomeDerivedRequest();

            // act
            await _subject.Value.Publish(someMessage);

            await _subject.Value.Publish(someDerivedMessage);

            await _subject.Value.Send(someRequest);

            await _subject.Value.Send(someDerivedRequest);

            // assert
            bus1Mock.Verify(x => x.Publish(someMessage, null), Times.Once);
            bus1Mock.Verify(x => x.Publish <SomeMessage>(someDerivedMessage, null), Times.Once);
            bus2Mock.Verify(x => x.Send(someRequest, null, default), Times.Once);
            bus2Mock.Verify(x => x.Send(someDerivedRequest, null, default), Times.Once);
        }
Beispiel #15
0
        private static async Task Main(string[] args)
        {
            #region Logging
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.Console()
                         .CreateLogger();
            #endregion

            SomeRequest request = new SomeRequest();

            //Lets say this is a web controller and the request is coming from the internet. So lets pretend this is a WebApi Controller.
            SomeResponse response = await SomeWebControllerApi(request);

            Log.Information("If there was an error it's http code is : {code} and http message is : {message}", response.Error.ErrorCode, response.Error.ErrorMessage);
        }
Beispiel #16
0
        public async Task <IActionResult> Index()
        {
            Console.Write(JsonConvert.SerializeObject(new
            {
                Method = $"{GetType().Name}.Index",
                Thread.CurrentThread.ManagedThreadId,
            }, Formatting.Indented));

            //send a message based on your incoming arguments to one of the actors you created earlier
            //and await the result by sending the message to `Ask`
            SomeRequest someRequest = new SomeRequest(DateTime.Now, Guid.NewGuid().ToString());
            SomeMessage someMessage = new SomeMessage(someRequest.Date, someRequest.Guid);
            SomeResult  result      = await Program.MyActor.Ask <SomeResult>(someMessage);

            return(View(result));
        }
Beispiel #17
0
        public void WhenRequestFailsThenOnMessageFaultIsCalledAndErrorResponseIsSent()
        {
            // arrange
            var onMessageFaultMock = new Mock <Action <AbstractConsumerSettings, object, Exception> >();
            var consumerSettings   = new ConsumerSettings
            {
                Instances      = 1,
                Topic          = "topic1",
                ConsumerMode   = ConsumerMode.RequestResponse,
                ConsumerType   = typeof(IRequestHandler <SomeRequest, SomeResponse>),
                MessageType    = typeof(SomeRequest),
                OnMessageFault = onMessageFaultMock.Object
            };

            var p = new ConsumerInstancePool <SomeRequest>(consumerSettings, _busMock.Bus, x => Array.Empty <byte>());

            var request        = new SomeRequest();
            var requestMessage = new MessageWithHeaders();
            var replyTo        = "reply-topic";
            var requestId      = "request-id";

            requestMessage.SetHeader(ReqRespMessageHeaders.RequestId, requestId);
            requestMessage.SetHeader(ReqRespMessageHeaders.ReplyTo, replyTo);
            _busMock.BusMock.Setup(x => x.DeserializeRequest(typeof(SomeRequest), It.IsAny <byte[]>(), out requestMessage))
            .Returns(request);

            var ex = new Exception("Something went bad");

            _busMock.HandlerMock.Setup(x => x.OnHandle(request, consumerSettings.Topic))
            .Returns(Task.FromException <SomeResponse>(ex));

            // act
            p.ProcessMessage(request).Wait();

            // assert
            _busMock.HandlerMock.Verify(x => x.OnHandle(request, consumerSettings.Topic),
                                        Times.Once); // handler called once

            onMessageFaultMock.Verify(
                x => x(consumerSettings, request, ex), Times.Once); // callback called once
            _busMock.BusMock.Verify(
                x => x.ProduceResponse(request, requestMessage, It.IsAny <SomeResponse>(), It.Is <MessageWithHeaders>(m => m.Headers[ReqRespMessageHeaders.RequestId] == requestId), It.IsAny <ConsumerSettings>()));
        }
Beispiel #18
0
        public void WhenRequestFails_OnMessageFault_IsCalled_And_ErrorResponse_IsSent()
        {
            // arrange
            var onMessageFaultMock = new Mock <Action <ConsumerSettings, object, Exception> >();
            var consumerSettings   = new ConsumerSettings
            {
                Instances      = 1,
                Topic          = "topic1",
                ConsumerMode   = ConsumerMode.RequestResponse,
                ConsumerType   = typeof(IRequestHandler <SomeRequest, SomeResponse>),
                MessageType    = typeof(SomeRequest),
                OnMessageFault = onMessageFaultMock.Object
            };

            var p = new ConsumerInstancePool <SomeRequest>(consumerSettings, _busMock.Object, x => new byte[0]);

            var            request = new SomeRequest();
            string         requestId;
            string         replyTo = "reply-topic";
            DateTimeOffset?expires;

            _busMock.Setup(x => x.DeserializeRequest(typeof(SomeRequest), It.IsAny <byte[]>(), out requestId, out replyTo, out expires)).Returns(request);

            var ex = new Exception("Something went bad");

            _handlerMock.Setup(x => x.OnHandle(request, consumerSettings.Topic)).Returns(Task.FromException <SomeResponse>(ex));

            // act
            p.Submit(request);
            var commitedMsg = p.Commit(request);

            // assert
            commitedMsg.Should().BeSameAs(request);                                            // it should commit the failed request message
            _handlerMock.Verify(x => x.OnHandle(request, consumerSettings.Topic), Times.Once); // handler called once

            onMessageFaultMock.Verify(x => x(consumerSettings, request, ex), Times.Once);      // callback called once
            _busMock.Verify(x => x.Publish(typeof(SomeResponse), It.IsAny <byte[]>(), replyTo));
        }
Beispiel #19
0
        public void IncludedCorrelationIdIsAutomaticallyTransferredToReplies()
        {
            // arrange
            var resetEvent = new ManualResetEvent(false);

            adapter.Handle <SomeRequest>(req => bus.Reply(new SomeReply()));

            string receivedCorrelationId = null;

            adapter.Handle <SomeReply>(rep =>
            {
                var currentHeaders = MessageContext
                                     .GetCurrent()
                                     .Headers;

                receivedCorrelationId = currentHeaders.ContainsKey(Headers.CorrelationId)
                                                ? currentHeaders[Headers.CorrelationId].ToString()
                                                : "could not find correlation ID in headers";

                resetEvent.Set();
            });

            var someRequest = new SomeRequest();

            bus.AttachHeader(someRequest, Headers.CorrelationId, "wootadafook!");

            // act
            bus.SendLocal(someRequest);

            if (!resetEvent.WaitOne(2.Seconds()))
            {
                Assert.Fail("Did not receive any reply withing 2 seconds of waiting");
            }

            // assert
            receivedCorrelationId.ShouldBe("wootadafook!");
        }
Beispiel #20
0
        public async Task When_RequestFails_Then_OnMessageFaultIsCalledAndErrorResponseIsSent()
        {
            // arrange
            var onMessageFaultMock = new Mock <Action <IMessageBus, AbstractConsumerSettings, object, Exception, object> >();
            var consumerSettings   = new HandlerBuilder <SomeRequest, SomeResponse>(new MessageBusSettings()).Topic(null).WithHandler <IRequestHandler <SomeRequest, SomeResponse> >().Instances(1).ConsumerSettings;

            consumerSettings.OnMessageFault = onMessageFaultMock.Object;

            var p = new ConsumerInstancePoolMessageProcessor <SomeRequest>(consumerSettings, _busMock.Bus, x => Array.Empty <byte>());

            var request        = new SomeRequest();
            var requestMessage = new MessageWithHeaders();
            var replyTo        = "reply-topic";
            var requestId      = "request-id";

            requestMessage.SetHeader(ReqRespMessageHeaders.RequestId, requestId);
            requestMessage.SetHeader(ReqRespMessageHeaders.ReplyTo, replyTo);
            _busMock.BusMock.Setup(x => x.DeserializeRequest(typeof(SomeRequest), It.IsAny <byte[]>(), out requestMessage)).Returns(request);

            var ex = new Exception("Something went bad");

            _busMock.HandlerMock.Setup(x => x.OnHandle(request, consumerSettings.Topic)).Returns(Task.FromException <SomeResponse>(ex));

            // act
            var exception = await p.ProcessMessage(request);

            // assert
            _busMock.HandlerMock.Verify(x => x.OnHandle(request, consumerSettings.Topic), Times.Once); // handler called once

            onMessageFaultMock.Verify(
                x => x(_busMock.Bus, consumerSettings, request, ex, It.IsAny <object>()), Times.Once); // callback called once

            _busMock.BusMock.Verify(
                x => x.ProduceResponse(request, requestMessage, It.IsAny <SomeResponse>(), It.Is <MessageWithHeaders>(m => m.Headers[ReqRespMessageHeaders.RequestId] == requestId), It.IsAny <ConsumerSettings>()));

            exception.Should().BeSameAs(ex);
        }
 public ActionResult <SomeResponse> Post([FromBody] SomeRequest req)
 {
     return(Ok());
 }
Beispiel #22
0
        //public static Func<string, Task<IActionResult>> Meth { get; }

        public static Task <AcceptedResult> Meth2(SomeRequest request)
        {
            return(_meth(request));
        }
Beispiel #23
0
 public static void Meth3(SomeRequest request)
 {
     return;
 }
Beispiel #24
0
 public static Task <IActionResult> Meth4(SomeRequest hejsan)
 {
     //var hej = $"{hejsan.Value}hello";
     //Console.WriteLine(hej);
     return(Task.FromResult(new OkObjectResult(hejsan) as IActionResult));
 }
 public virtual Action Foo(SomeRequest request)
 {
     return(GenericAction(request));
 }
 public void Handle(SomeRequest request)
 {
     bus.Reply(new SomeReply(...));
 }
Beispiel #27
0
 public SomeContext(SomeRequest someRequest)
 {
     Request  = someRequest;
     Response = new SomeResponse();
 }
Beispiel #28
0
 public SomeResponse Get(SomeRequest request)
 {
     return(new SomeResponse {
         Value = AppSettings.Get <string>(request.Key)
     });
 }