Exemple #1
0
        public async Task ShouldRegisterAndUnregisterPeer()
        {
            var subscription1 = Subscription.Matching <DatabaseStatus>(status => status.DatacenterName == "Paris" && status.Status == "Ko");
            var subscription2 = Subscription.Any <DoSomething>();

            var bytes = _container.GetInstance <IMessageSerializer>().Serialize(subscription1);
            var json  = Encoding.UTF8.GetString(bytes);

            var obj = _container.GetInstance <IMessageSerializer>().Deserialize(bytes, typeof(Subscription));

            var command = new DoSomething();

            Assert.AreEqual(0, GlobalTestContext.Get());

            _bus.Start();

            await _bus.Subscribe(new SubscriptionRequest(subscription1));

            var peers = _directoryRepository.GetPeers(true);

            Assert.AreEqual(1, peers.Count());
            Assert.AreEqual(5, peers.First().Subscriptions.Count());

            await _bus.Subscribe(new SubscriptionRequest(subscription2));

            peers = _directoryRepository.GetPeers(true);
            Assert.AreEqual(1, peers.Count());
            Assert.AreEqual(6, peers.First().Subscriptions.Count());

            await _bus.Send(command);

            await Task.Delay(50);

            Assert.AreEqual(1, GlobalTestContext.Get());
        }
        public void MeasureStaticSubscriptionsPerformance()
        {
            var peers = Enumerable.Range(0, 100).Select(x => new Peer(new PeerId("Abc.Testing" + x), "tcp://testing:" + x)).ToList();

            Console.WriteLine("{0} peers", peers.Count);
            Console.WriteLine();

            var subscriptionList = new PeerSubscriptionList();
            var subscriptionTree = new PeerSubscriptionTree();

            foreach (var peer in peers)
            {
                subscriptionList.Add(peer, Subscription.Any <FakeEvent>());
                subscriptionTree.Add(peer, BindingKey.Empty);
            }

            Console.WriteLine("{0} test -------------", subscriptionList.GetType().Name);
            Console.WriteLine();
            Measure.Execution(x =>
            {
                x.Iteration       = 100000;
                x.WarmUpIteration = 1000;
                x.Action          = _ => subscriptionList.GetPeers(BindingKey.Empty);
            });
            Console.WriteLine();

            Console.WriteLine("{0} test -------------", subscriptionTree.GetType().Name);
            Console.WriteLine();
            Measure.Execution(x =>
            {
                x.Iteration       = 100000;
                x.WarmUpIteration = 1000;
                x.Action          = _ => subscriptionTree.GetPeers(BindingKey.Empty);
            });
        }
Exemple #3
0
        public async Task should_not_return_duplicates_in_peers_handling_messages_after_PeerSubscriptionsUpdated()
        {
            await RegisterSelf();

            var descriptor = _otherPeer.ToPeerDescriptor(true,
                                                         new[]
            {
                Subscription.Any <FakeRoutableCommand>(),
                Subscription.Any <FakeRoutableCommand>(),
            });

            _directory.Handle(new PeerStarted(descriptor));

            var peers = _directory.GetPeersHandlingMessage(new FakeRoutableCommand(42, "Foo"));

            peers.Count.ShouldEqual(1);
            peers[0].Id.ShouldEqual(_otherPeer.Id);

            var updatedDescriptor = _otherPeer.ToPeerDescriptor(true,
                                                                new[]
            {
                Subscription.Any <FakeRoutableCommand>(),
                Subscription.Matching <FakeRoutableCommand>(x => x.Id == 42),
            });

            _directory.Handle(new PeerSubscriptionsUpdated(updatedDescriptor));

            peers = _directory.GetPeersHandlingMessage(new FakeRoutableCommand(42, "Foo"));
            peers.Count.ShouldEqual(1);
            peers[0].Id.ShouldEqual(_otherPeer.Id);
        }
Exemple #4
0
        public async Task should_not_return_duplicates_in_peers_handling_messages_after_PeerSubscriptionsForTypesUpdated()
        {
            await RegisterSelf();

            var descriptor = _otherPeer.ToPeerDescriptor(true,
                                                         new[]
            {
                Subscription.Any <FakeRoutableCommand>(),
                Subscription.Any <FakeRoutableCommand>(),
            });

            _directory.Handle(new PeerStarted(descriptor));

            var peers = _directory.GetPeersHandlingMessage(new FakeRoutableCommand(42, "Foo"));

            peers.Count.ShouldEqual(1);
            peers[0].Id.ShouldEqual(_otherPeer.Id);

            var subscriptionsForTypes = new[]
            {
                new SubscriptionsForType(MessageUtil.TypeId <FakeRoutableCommand>(), BindingKey.Empty),
                new SubscriptionsForType(MessageUtil.TypeId <FakeRoutableCommand>(), Subscription.Matching <FakeRoutableCommand>(x => x.Id == 42).BindingKey),
            };

            _directory.Handle(new PeerSubscriptionsForTypesUpdated(_otherPeer.Id, DateTime.UtcNow, subscriptionsForTypes));

            peers = _directory.GetPeersHandlingMessage(new FakeRoutableCommand(42, "Foo"));

            peers.Count.ShouldEqual(1);
            peers[0].Id.ShouldEqual(_otherPeer.Id);
        }
Exemple #5
0
            public async Task should_not_fail_subscribe_if_previous_unsubscribe_failed()
            {
                _bus.Start();

                _directoryMock.Setup(i => i.UpdateSubscriptionsAsync(It.IsAny <IBus>(), It.IsAny <IEnumerable <SubscriptionsForType> >()))
                .Returns(Task.CompletedTask);

                var subA = await _bus.SubscribeAsync(Subscription.Any <FakeCommand>(), msg => { }).ConfigureAwait(true);

                var unsubscribeTcs  = new TaskCompletionSource <object>();
                var unsubscribeSent = false;

                _directoryMock.Setup(i => i.UpdateSubscriptionsAsync(It.IsAny <IBus>(), It.IsAny <IEnumerable <SubscriptionsForType> >()))
                .Callback(() => unsubscribeSent = true)
                .Returns(unsubscribeTcs.Task);

                subA.Dispose();
                Wait.Until(() => unsubscribeSent, 2.Seconds());

                var newSubscribeSent = false;

                _directoryMock.Setup(i => i.UpdateSubscriptionsAsync(It.IsAny <IBus>(), It.IsAny <IEnumerable <SubscriptionsForType> >()))
                .Callback(() => newSubscribeSent = true)
                .Returns(Task.CompletedTask);

                var subBTask = _bus.SubscribeAsync(Subscription.Any <FakeCommand>(), msg => { });

                Thread.Sleep(200);
                newSubscribeSent.ShouldBeFalse();

                unsubscribeTcs.SetException(new InvalidOperationException("Test"));
                Wait.Until(() => newSubscribeSent, 2.Seconds());

                await subBTask.ConfigureAwait(true);
            }
Exemple #6
0
            public async Task should_wait_for_unsubscribe_to_complete_before_adding_new_subscriptions()
            {
                _bus.Start();

                _directoryMock.Setup(i => i.UpdateSubscriptionsAsync(It.IsAny <IBus>(), It.IsAny <IEnumerable <SubscriptionsForType> >()))
                .Returns(Task.CompletedTask);

                var subA = await _bus.SubscribeAsync(Subscription.Any <FakeCommand>(), msg => { }).ConfigureAwait(true);

                var unsubscribeTcs  = new TaskCompletionSource <object>();
                var unsubscribeSent = false;

                _directoryMock.Setup(i => i.UpdateSubscriptionsAsync(It.IsAny <IBus>(), It.IsAny <IEnumerable <SubscriptionsForType> >()))
                .Callback(() => unsubscribeSent = true)
                .Returns(unsubscribeTcs.Task);

                subA.Dispose();
                Wait.Until(() => unsubscribeSent, 2.Seconds());

                var newSubscribeSent = false;

                _directoryMock.Setup(i => i.UpdateSubscriptionsAsync(It.IsAny <IBus>(), It.IsAny <IEnumerable <SubscriptionsForType> >()))
                .Callback(() => newSubscribeSent = true)
                .Returns(Task.CompletedTask);

                var subBTask = _bus.SubscribeAsync(Subscription.Any <FakeCommand>(), msg => { });

                Thread.Sleep(200);
                newSubscribeSent.ShouldBeFalse();

                unsubscribeTcs.SetResult(null);
                Wait.Until(() => newSubscribeSent, 2.Seconds());

                await subBTask.ConfigureAwait(true);
            }
        public void should_not_get_part_for_unknown_member()
        {
            // Arrange
            var subscription = Subscription.Any <FakeRoutableCommand>();

            // Act, Assert
            Assert.Throws <InvalidOperationException>(() => subscription.GetBindingKeyPartForMember("something that will not match"));
        }
Exemple #8
0
        public async Task should_specify_datetime_kind_when_removing_subscriptions_for_a_type()
        {
            var subscriptionsForTypes = new[] { new SubscriptionsForType(MessageUtil.GetTypeId(typeof(int))) };
            await _peerDirectory.RegisterAsync(_bus, _self, new[] { Subscription.Any <FakeCommand>() });

            await _peerDirectory.UpdateSubscriptionsAsync(_bus, subscriptionsForTypes);

            _repositoryMock.Verify(repo => repo.RemoveDynamicSubscriptionsForTypes(_self.Id, It.Is <DateTime>(date => date.Kind == DateTimeKind.Utc), new[] { MessageUtil.GetTypeId(typeof(int)) }));
        }
        public void should_get_part_for_member_that_matches_all(string memberName)
        {
            // Arrange
            var subscription = Subscription.Any <FakeRoutableCommand>();

            // Act
            var part = subscription.GetBindingKeyPartForMember(memberName);

            // Assert
            part.MatchesAllValues.ShouldBeTrue();
        }
Exemple #10
0
        public async Task should_handle_null_bindingkeys_array_when_removing_subscriptions()
        {
            using (SystemDateTime.PauseTime())
            {
                var subscriptionsForTypes = new[] { new SubscriptionsForType(MessageUtil.GetTypeId(typeof(int)), null) };
                await _peerDirectory.RegisterAsync(_bus, _self, new[] { Subscription.Any <FakeCommand>() });

                await _peerDirectory.UpdateSubscriptionsAsync(_bus, subscriptionsForTypes);

                _repositoryMock.Verify(repo => repo.RemoveDynamicSubscriptionsForTypes(_self.Id, SystemDateTime.UtcNow, new[] { MessageUtil.GetTypeId(typeof(int)) }));
            }
        }
Exemple #11
0
        public async Task should_raise_peer_subscription_updated_event_only_for_enabled_types()
        {
            // Arrange
            var subscriptions = CaptureSubscriptionsUpdated();

            _directory.EnableSubscriptionsUpdatedFor(new[] { typeof(PeerStarted) });

            // Act
            await RegisterSelf(new[] { Subscription.Any <PeerStarted>(), Subscription.Any <PeerStopped>() });

            // Assert
            subscriptions.Count.ShouldEqual(1);
        }
Exemple #12
0
        public IBus CreateAndStartBus()
        {
            var bus = CreateBus();

            bus.Start();

            if (EnableTimeoutCommandDispatch)
            {
                bus.Subscribe(Subscription.Any <TimeoutCommand>());
            }

            return(bus);
        }
Exemple #13
0
            public void should_subscribe_to_message_for_all_binding_keys()
            {
                AddInvoker <FakeCommand>(shouldBeSubscribedOnStartup: false);
                AddInvoker <FakeRoutableCommand>(shouldBeSubscribedOnStartup: false);
                var subscriptions = new List <SubscriptionsForType>();

                _directoryMock.CaptureEnumerable((IBus)_bus, (x, bus, items) => x.UpdateSubscriptions(bus, items), subscriptions);

                _bus.Start();
                _bus.Subscribe(Subscription.Any <FakeCommand>());

                subscriptions.ExpectedSingle();
                subscriptions.ShouldContain(new SubscriptionsForType(MessageUtil.TypeId <FakeCommand>(), BindingKey.Empty));
            }
Exemple #14
0
        public async Task should_publish_event_when_modifying_subscriptions()
        {
            using (SystemDateTime.PauseTime())
            {
                var subscriptionsForTypes = new[] { new SubscriptionsForType(MessageUtil.GetTypeId(typeof(int)), BindingKey.Empty) };
                await _peerDirectory.RegisterAsync(_bus, _self, new[] { Subscription.Any <FakeCommand>() });

                _bus.ClearMessages();

                await _peerDirectory.UpdateSubscriptionsAsync(_bus, subscriptionsForTypes);

                _bus.ExpectExactly(new PeerSubscriptionsForTypesUpdated(_self.Id, SystemDateTime.UtcNow, subscriptionsForTypes));
            }
        }
Exemple #15
0
            public void should_only_call_specific_handler_once_per_type()
            {
                _bus.Start();
                _bus.Subscribe(new[]
                {
                    Subscription.Matching <FakeRoutableCommand>(x => x.Id == 1),
                    Subscription.Matching <FakeRoutableCommand>(x => x.Id == 2),
                    Subscription.Any <FakeCommand>()
                }, message => { });

                _messageDispatcherMock.Verify(x => x.AddInvoker(It.IsAny <IMessageHandlerInvoker>()), Times.Exactly(2));
                _messageDispatcherMock.Verify(x => x.AddInvoker(It.Is <IMessageHandlerInvoker>(invoker => invoker.MessageType == typeof(FakeRoutableCommand))), Times.Once);
                _messageDispatcherMock.Verify(x => x.AddInvoker(It.Is <IMessageHandlerInvoker>(invoker => invoker.MessageType == typeof(FakeCommand))), Times.Once);
            }
Exemple #16
0
            public async Task should_not_unsubscribe_when_bus_is_stopped()
            {
                AddInvoker <FakeCommand>(shouldBeSubscribedOnStartup: false);

                _bus.Start();
                var subscription = _bus.Subscribe(Subscription.Any <FakeCommand>());

                _bus.Stop();
                _directoryMock.Invocations.Clear();

                subscription.Dispose();
                await _bus.WhenUnsubscribeCompletedAsync();

                _directoryMock.Verify(i => i.UpdateSubscriptionsAsync(_bus, It.IsAny <IEnumerable <SubscriptionsForType> >()), Times.Never);
            }
Exemple #17
0
        public async Task should_raise_peer_subscription_updated_event_when_peer_updates_dynamic_subscription()
        {
            // Arrange
            var subscriptions = CaptureSubscriptionsUpdated();

            _directory.EnableSubscriptionsUpdatedFor(new[] { typeof(PeerStarted) });
            await RegisterSelf();

            _directory.Handle(new PeerStarted(_otherPeer.ToPeerDescriptor(false)));

            // Act
            var subscription = Subscription.Any <PeerStarted>();

            _directory.Handle(new PeerSubscriptionsForTypesUpdated(_otherPeer.Id, DateTime.Now, new SubscriptionsForType(subscription.MessageTypeId, subscription.BindingKey)));

            // Assert
            subscriptions.Count.ShouldEqual(1);
        }
Exemple #18
0
            public void should_throw_when_batch_is_sent_after_bus_is_stopped()
            {
                AddInvoker <FakeCommand>(shouldBeSubscribedOnStartup: false);

                var batch   = new SubscriptionRequestBatch();
                var request = new SubscriptionRequest(Subscription.Any <FakeCommand>());

                request.AddToBatch(batch);

                _bus.Start();
                var _ = _bus.SubscribeAsync(request);

                _bus.Stop();

                var submitTask = batch.SubmitAsync();

                Assert.Throws <AggregateException>(() => submitTask.Wait()).InnerExceptions.ExpectedSingle().ShouldBe <InvalidOperationException>();
            }
Exemple #19
0
        static void Main(string[] args)
        {
            _bus = BusFactory.Create("peer2", Constants.EndpointPeer2, Constants.EndpointDirectory);
            _bus.Start();

            var subscription1 = Subscription.Matching <DatabaseStatus>(ev => ev.DatacenterName == Constants.Paris);
            var subscription2 = Subscription.Any <DoSomething>();

            _bus.Subscribe(new SubscriptionRequest(subscription1)).Wait();
            _bus.Subscribe(new SubscriptionRequest(subscription2)).Wait();

            Task.Delay(100).Wait();

            while (true)
            {
                _bus.Publish(DatabaseStatus.Create(Constants.London));
                Task.Delay(1000);
            }
        }
Exemple #20
0
        public void should_get_binding_key_parts_for_member()
        {
            // Arrange
            var bindingKeys = new[]
            {
                Subscription.Matching <StrangeRoutableMessage>(x => x.Id == 123).BindingKey,
                Subscription.Matching <StrangeRoutableMessage>(x => x.Code == "456").BindingKey,
                Subscription.Matching <StrangeRoutableMessage>(x => x.Id == 123 && x.Code == "456").BindingKey,
                Subscription.Any <StrangeRoutableMessage>().BindingKey,
            };

            // Act
            var partsForId   = BindingKeyUtil.GetPartsForMember(MessageUtil.TypeId <StrangeRoutableMessage>(), nameof(StrangeRoutableMessage.Id), bindingKeys);
            var partsForCode = BindingKeyUtil.GetPartsForMember(MessageUtil.TypeId <StrangeRoutableMessage>(), nameof(StrangeRoutableMessage.Code), bindingKeys);

            // Assert
            partsForId.ShouldBeEquivalentTo(BindingKeyPart.Parse("123"), BindingKeyPart.Star, BindingKeyPart.Parse("123"), BindingKeyPart.Star);
            partsForCode.ShouldBeEquivalentTo(BindingKeyPart.Star, BindingKeyPart.Parse("456"), BindingKeyPart.Parse("456"), BindingKeyPart.Star);
        }
Exemple #21
0
        public void should_subscribe_with_untype_handler()
        {
            _bus.Start();

            var invokers = new List<IMessageHandlerInvoker>();
            _messageDispatcherMock.Setup(x => x.AddInvoker(It.IsAny<EventHandlerInvoker>())).Callback((IMessageHandlerInvoker i) => invokers.Add(i));

            var handlerMock = new Mock<IMessageHandler<IMessage>>();
            var subscriptions = new[] { Subscription.Any<FakeEvent>() };
            _bus.Subscribe(subscriptions, handlerMock.Object.Handle);

            invokers.Count.ShouldEqual(1);
            invokers[0].CanInvokeSynchronously.ShouldBeTrue();
            invokers[0].DispatchQueueName.ShouldEqual(DispatchQueueNameScanner.DefaultQueueName);
            invokers[0].MessageHandlerType.ShouldNotBeNull();
            invokers[0].MessageType.ShouldEqual(typeof(FakeEvent));
            invokers[0].MessageTypeId.ShouldEqual(new MessageTypeId(typeof(FakeEvent)));
            invokers[0].ShouldCreateStartedTasks.ShouldBeFalse();
        }
Exemple #22
0
        public async Task ShouldMakeSubscription()
        {
            var subscription1 = Subscription.Matching <DatabaseStatus>(status => status.DatacenterName == "Paris" && status.Status == "Ko");
            var subscription2 = Subscription.Any <DoSomething>();

            var command = new DoSomething();

            Assert.AreEqual(0, GlobalTestContext.Get());

            var @event = new DatabaseStatus()
            {
                DatacenterName = "Paris",
                Status         = "Ko"
            };

            _bus.Start();

            //registration
            Assert.AreEqual(1, TestBusTransportTestContext.TransportHitCounter);

            await _bus.Subscribe(new SubscriptionRequest(subscription1));

            Assert.AreEqual(2, TestBusTransportTestContext.TransportHitCounter);

            await _bus.Subscribe(new SubscriptionRequest(subscription2));

            Assert.AreEqual(3, TestBusTransportTestContext.TransportHitCounter);

            //as the transport is mocked, register manually
            await _directory.RegisterAsync(_bus.Self, _bus.GetSubscriptions());

            //register directory transport call
            Assert.AreEqual(4, TestBusTransportTestContext.TransportHitCounter);

            _bus.Publish(@event);

            Assert.AreEqual(5, TestBusTransportTestContext.TransportHitCounter);

            await _bus.Send(command);

            Assert.AreEqual(6, TestBusTransportTestContext.TransportHitCounter);
        }
Exemple #23
0
            public void should_subscribe_to_single_subscription_with_untype_handler()
            {
                _bus.Start();

                var invokers = new List <IMessageHandlerInvoker>();

                _messageDispatcherMock.Setup(x => x.AddInvoker(It.IsAny <DynamicMessageHandlerInvoker>())).Callback((IMessageHandlerInvoker i) => invokers.Add(i));

                var handlerMock = new Mock <IMessageHandler <IMessage> >();

                _bus.Subscribe(Subscription.Any <FakeEvent>(), handlerMock.Object.Handle);

                var invoker = invokers.ExpectedSingle();

                invoker.Mode.ShouldEqual(MessageHandlerInvokerMode.Synchronous);
                invoker.DispatchQueueName.ShouldEqual(DispatchQueueNameScanner.DefaultQueueName);
                invoker.MessageHandlerType.ShouldNotBeNull();
                invoker.MessageType.ShouldEqual(typeof(FakeEvent));
                invoker.MessageTypeId.ShouldEqual(new MessageTypeId(typeof(FakeEvent)));
            }
Exemple #24
0
            public void should_not_subscribe_when_bus_is_stopped()
            {
                AddInvoker <FakeCommand>(shouldBeSubscribedOnStartup: false);

                Assert.Throws <InvalidOperationException>(() => _bus.Subscribe(Subscription.Any <FakeCommand>()));
            }
Exemple #25
0
        public async Task ShouldTestE2E()
        {
            GlobalTestContext.Reset();

            var subscription1 = Subscription.Matching <DatabaseStatus>(status => status.DatacenterName == "Paris" && status.Status == "Ko");
            var subscription2 = Subscription.Any <DoSomething>();

            Assert.AreEqual(0, GlobalTestContext.Get());

            await _bus.Subscribe(new SubscriptionRequest(subscription1));

            await Task.Delay(50);

            await _bus.Subscribe(new SubscriptionRequest(subscription2));

            await Task.Delay(50);

            //should be consumed
            var command = new DoSomething();

            await _bus.Send(command);

            await Task.Delay(50);

            Assert.AreEqual(1, GlobalTestContext.Get());

            //should be consumed
            var @event = new DatabaseStatus()
            {
                DatacenterName = "Paris",
                Status         = "Ko"
            };

            _bus.Publish(@event);

            await Task.Delay(50);

            Assert.AreEqual(2, GlobalTestContext.Get());

            //should be consumed
            @event = new DatabaseStatus()
            {
                DatacenterName = "Paris",
                Status         = "Ko"
            };

            _bus.Publish(@event);

            await Task.Delay(50);

            Assert.AreEqual(3, GlobalTestContext.Get());

            //should not be consumed
            @event = new DatabaseStatus()
            {
                DatacenterName = "Paris",
                Status         = "Ok"
            };

            _bus.Publish(@event);

            await Task.Delay(50);

            Assert.AreEqual(3, GlobalTestContext.Get());
        }
 private static PeerDescriptor CreatePeerDescriptor(PeerId peerId, bool isPersistent = true, bool isResponding = true)
 {
     return(new PeerDescriptor(peerId, "endpoint", isPersistent, true, isResponding, DateTime.UtcNow, new[] { Subscription.Any <TestMessage>() }));
 }
Exemple #27
0
        public async Task should_raise_peer_subscription_updated_event_when_peer_updates_static_subscription()
        {
            // Arrange
            var subscriptions = CaptureSubscriptionsUpdated();

            _directory.EnableSubscriptionsUpdatedFor(new[] { typeof(PeerStarted) });
            await RegisterSelf();

            _directory.Handle(new PeerStarted(_otherPeer.ToPeerDescriptor(true)));

            // Act
            _directory.Handle(new PeerSubscriptionsUpdated(_otherPeer.ToPeerDescriptor(false, new[] { Subscription.Any <PeerStarted>() })));

            // Assert
            subscriptions.Count.ShouldEqual(1);
        }
Exemple #28
0
 public async Task should_not_send_update_to_directory_unnecessarily()
 {
     AddInvoker <FakeCommand>(shouldBeSubscribedOnStartup: false);
     await TestUnnecessaryDirectoryUpdatesAsync(Subscription.Any <FakeCommand>());
 }