public void MessageBusCanBeDisposedTwiceWithoutHanging()
        {
            var bus = new MessageBus(new DefaultDependencyResolver());

            bus.Dispose();
            Assert.True(Task.Run(() => bus.Dispose()).Wait(TimeSpan.FromSeconds(10)));
        }
        protected override void ConfigImpl()
        {
            var options = CurrentState;
            var parent  = Context.Parent;

            var messageBus = new MessageBus();

            messageBus.Subscribe(new ClockComponent(options));

            messageBus.Subscribe(new DataFetchComponent(options));

            messageBus.Subscribe(new TrackingEventDeliveryComponent(e =>
            {
                parent.Tell(e);
                return(Task.CompletedTask);
            }));

            messageBus.Subscribe(new PowerComponent());
            messageBus.Subscribe(new CoolDownComponent());
            messageBus.Subscribe(new GoStandByComponent(options));
            messageBus.Subscribe(new StartUpCoolingComponent(options));
            messageBus.Subscribe(new StandByCoolingComponent(options));

            messageBus.Subscribe(new FanControlComponent(options, e =>
            {
                parent.Tell(new FanStatusChange(e));
                return(Task.CompletedTask);
            }));

            Stop.Subscribe(_ => messageBus.Dispose());

            Receive <ClockEvent>(obs => obs.SelectMany(async p => await messageBus.Publish(p)));
        }
        public void RunEventSource_Test1()
        {
            int         sum        = 0;
            IDisposable token      = null;
            var         messageBus = new MessageBus();

            messageBus.InitializeEventSources();
            messageBus.Subscribe <int>(b => b
                                       .WithDefaultTopic()
                                       .Invoke(i => sum += i)
                                       .Immediate());
            var resetEvent = new ManualResetEvent(false);
            var target     = new TestEventSource1(resetEvent);

            try
            {
                token = messageBus.RunEventSource(target);
                resetEvent.WaitOne(5000).Should().BeTrue();
                sum.Should().Be(7);
            }
            finally
            {
                token?.Dispose();
                resetEvent.Dispose();
                messageBus.Dispose();
            }
        }
Exemple #4
0
        public void ListenRequestAndResponse_WorkerThread()
        {
            var target = new MessageBus(new MessageBusCreateParameters
            {
                NumberOfWorkers = 1
            });

            try
            {
                target.Listen <TestRequestWithResponse, TestResponse>(l => l
                                                                      .WithTopic("Test")
                                                                      .Invoke(req => new TestResponse {
                    Text = req.Text + "Responded" + Thread.CurrentThread.ManagedThreadId
                })
                                                                      .OnWorker());
                var response = target.Request <TestRequestWithResponse, TestResponse>("Test", new TestRequestWithResponse {
                    Text = "Request"
                });

                response.Should().NotBeNull();
            }
            finally
            {
                target.Dispose();
            }
        }
        public void ParticipateScatterGather_OnThread()
        {
            var target   = new MessageBus();
            int threadId = target.WorkerPool.StartDedicatedWorker().ThreadId;

            try
            {
                var token = target.Participate <TestRequestWithResponse, TestResponse>(builder => builder
                                                                                       .WithTopic("Test")
                                                                                       .Invoke(e => new TestResponse {
                    Text = Thread.CurrentThread.ManagedThreadId.ToString()
                })
                                                                                       .OnThread(threadId));
                var results = target.Scatter <TestRequestWithResponse, TestResponse>("Test", new TestRequestWithResponse {
                    Text = "Test"
                });

                results.GetNextResponse().Value.Text.Should().NotBeNullOrEmpty();
                token.Dispose();
            }
            finally
            {
                target.Dispose();
            }
        }
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         _bus.Dispose();
     }
     base.Dispose(disposing);
 }
        protected override void Dispose(bool disposing)
        {
            if (_bus != null && disposing)
            {
                _bus.Dispose();
                _bus = null;
            }

            base.Dispose(disposing);
        }
Exemple #8
0
    public void TryingToQueueMessageAfterDisposingThrows()
    {
        var bus = new MessageBus(SpyMessageSink.Create());

        bus.Dispose();

        var exception = Record.Exception(
            () => bus.QueueMessage(Substitute.For <IMessageSinkMessage>())
            );

        Assert.IsType <ObjectDisposedException>(exception);
    }
Exemple #9
0
        public static IDisposable Run(int connections, int senders, string payload, int messageBufferSize = 10)
        {
            var resolver                = new DefaultDependencyResolver();
            var bus                     = new MessageBus(resolver);
            var countDown               = new CountdownEvent(senders);
            var subscriptions           = new List <IDisposable>();
            var cancellationTokenSource = new CancellationTokenSource();

            // Initialize performance counters for this run
            Utility.InitializePerformanceCounters(resolver, cancellationTokenSource.Token);

            for (int i = 0; i < connections; i++)
            {
                string      identity     = i.ToString();
                var         subscriber   = new Subscriber(identity, new[] { "a", "b", "c" });
                IDisposable subscription = bus.Subscribe(subscriber,
                                                         cursor: null,
                                                         callback: _ => TaskAsyncHelper.True,
                                                         messageBufferSize: messageBufferSize);

                subscriptions.Add(subscription);
            }

            for (var i = 0; i < senders; i++)
            {
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    while (!cancellationTokenSource.IsCancellationRequested)
                    {
                        string source = i.ToString();
                        bus.Publish(source, "a", payload);
                    }

                    countDown.Signal();
                });
            }

            return(new DisposableAction(() =>
            {
                cancellationTokenSource.Cancel();

                // Wait for all senders to stop
                countDown.Wait(TimeSpan.FromMilliseconds(1000 * senders));

                // Shut the bus down and wait for workers to stop
                bus.Dispose();

                // Dispose of all the subscriptions
                subscriptions.ForEach(s => s.Dispose());
            }));
        }
Exemple #10
0
        public static IDisposable Run(int connections, int senders, string payload, int messageBufferSize = 10)
        {
            var resolver = new DefaultDependencyResolver();
            var bus = new MessageBus(resolver);
            var countDown = new CountdownEvent(senders);
            var subscriptions = new List<IDisposable>();
            var cancellationTokenSource = new CancellationTokenSource();

            // Initialize performance counters for this run
            Utility.InitializePerformanceCounters(resolver, cancellationTokenSource.Token);

            for (int i = 0; i < connections; i++)
            {
                string identity = i.ToString();
                var subscriber = new Subscriber(identity, new[] { "a", "b", "c" });
                IDisposable subscription = bus.Subscribe(subscriber,
                                                         cursor: null,
                                                         callback: _ => TaskAsyncHelper.True,
                                                         maxMessages: messageBufferSize);

                subscriptions.Add(subscription);
            }

            for (var i = 0; i < senders; i++)
            {
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    while (!cancellationTokenSource.IsCancellationRequested)
                    {
                        string source = i.ToString();
                        bus.Publish(source, "a", payload);
                    }

                    countDown.Signal();
                });
            }

            return new DisposableAction(() =>
            {
                cancellationTokenSource.Cancel();

                // Wait for all senders to stop
                countDown.Wait(TimeSpan.FromMilliseconds(1000 * senders));

                // Shut the bus down and wait for workers to stop
                bus.Dispose();

                // Dispose of all the subscriptions
                subscriptions.ForEach(s => s.Dispose());
            });
        }
Exemple #11
0
        public void DisposingBusShutsWorkersDown()
        {
            var         dr           = new DefaultDependencyResolver();
            var         bus          = new MessageBus(dr);
            var         subscriber   = new TestSubscriber(new[] { "key" });
            var         wh           = new ManualResetEventSlim(initialState: false);
            IDisposable subscription = null;

            try
            {
                subscription = bus.Subscribe(subscriber, null, result =>
                {
                    if (!result.Terminal)
                    {
                        var m = result.GetMessages().Single();

                        Assert.Equal("key", m.Key);
                        Assert.Equal("value", m.Value);

                        wh.Set();

                        return(TaskAsyncHelper.True);
                    }

                    return(TaskAsyncHelper.False);
                }, 10);

                bus.Publish("test", "key", "value").Wait();

                Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
            }
            finally
            {
                if (subscription != null)
                {
                    subscription.Dispose();
                }

                Assert.Equal(bus.AllocatedWorkers, 1);

                bus.Dispose();

                Assert.Equal(bus.AllocatedWorkers, 0);
            }
        }
Exemple #12
0
        public void ListenRequestAndResponse_ThreadPool()
        {
            var target = new MessageBus();

            try
            {
                target.Listen <int, int>(l => l
                                         .WithDefaultTopic()
                                         .Invoke(req => req * 5)
                                         .OnThreadPool());
                var response = target.RequestWait <int, int>(1);

                response.Should().Be(5);
            }
            finally
            {
                target.Dispose();
            }
        }
Exemple #13
0
        public void ListenRequestAndResponse_OnThread()
        {
            var target   = new MessageBus();
            int threadId = target.WorkerPool.StartDedicatedWorker().ThreadId;

            try
            {
                target.Listen <int, int>(l => l
                                         .WithDefaultTopic()
                                         .Invoke(req => req * 5)
                                         .OnThread(threadId));
                var response = target.RequestWait <int, int>(1);

                response.Should().Be(5);
            }
            finally
            {
                target.Dispose();
            }
        }
        public void Subscribe_SubscriptionBuilder_OnThread()
        {
            var target     = new MessageBus();
            var resetEvent = new ManualResetEvent(false);
            var id         = target.WorkerPool.StartDedicatedWorker().ThreadId;

            try
            {
                target.Subscribe <TestPubSubEvent>(builder => builder
                                                   .WithTopic("Test")
                                                   .Invoke(e => resetEvent.Set())
                                                   .OnThread(id));
                target.Publish("Test", new TestPubSubEvent("Test"));

                resetEvent.WaitOne(5000).Should().BeTrue();
            }
            finally
            {
                resetEvent.Dispose();
                target.Dispose();
            }
        }
        public void Subscribe_SubscriptionBuilder_WorkerThread()
        {
            var target = new MessageBus(new MessageBusCreateParameters
            {
                NumberOfWorkers = 1
            });

            try
            {
                var resetEvent = new AutoResetEvent(false);
                target.Subscribe <TestPubSubEvent>(builder => builder
                                                   .WithTopic("Test")
                                                   .Invoke(e => resetEvent.Set())
                                                   .OnWorker());
                target.Publish("Test", new TestPubSubEvent("Test"));
                resetEvent.WaitOne(2000).Should().BeTrue();
            }
            finally
            {
                target.Dispose();
            }
        }
        public void RunEventSource__Delegate()
        {
            IDisposable token      = null;
            var         messageBus = new MessageBus();

            messageBus.InitializeEventSources();
            var resetEvent = new ManualResetEvent(false);
            var target     = new TestEventSource2(resetEvent);

            try
            {
                token = messageBus.RunEventSource(target);
                var report = messageBus.WorkerPool.GetThreadReport();
                report.RegisteredThreads.Count.Should().Be(1);
                var str = report.ToString();
            }
            finally
            {
                token?.Dispose();
                resetEvent.Dispose();
                messageBus.Dispose();
            }
        }
Exemple #17
0
        public void MessageTimer_Start()
        {
            var bus = new MessageBus();
            var ids = new List <long>();

            try
            {
                var moduleToken       = bus.InitializeMessageTimer();
                var timerToken        = bus.StartTimer("test", 100, 100);
                var subscriptionToken = bus.TimerSubscribe("test", 1, builder => builder.Invoke(mte => ids.Add(mte.Id)));

                Thread.Sleep(1000);

                moduleToken.Dispose();
                subscriptionToken.Dispose();
                ids.Should().OnlyHaveUniqueItems();
                ids.Count.Should().BeGreaterOrEqualTo(5);
            }
            finally
            {
                bus.Dispose();
            }
        }
Exemple #18
0
        public void Dispose_Disposes_AllRegistered_Channels()
        {
            var dispose1Called = false;
            var dispose2Called = false;
            const string registeredChannelId1 = nameof(registeredChannelId1);
            const string registeredChannelId2 = nameof(registeredChannelId2);

            var mockMessageChannel1 = new Mock<IMessageChannel>();
            mockMessageChannel1.Setup(x => x.Dispose()).Callback(() => dispose1Called = true);

            var mockMessageChannel2 = new Mock<IMessageChannel>();
            mockMessageChannel2.Setup(x => x.Dispose()).Callback(() => dispose2Called = true);

            IMessageChannel CreateChannel(string channelId)
            {
                if (channelId == registeredChannelId1)
                {
                    return mockMessageChannel1.Object;
                }
                if (channelId == registeredChannelId2)
                {
                    return mockMessageChannel2.Object;
                }
                return null;
            }

            var messageBus = new MessageBus(CreateChannel);

            messageBus.RegisterChannel(registeredChannelId1);
            messageBus.RegisterChannel(registeredChannelId2);

            messageBus.Dispose();

            Assert.True(dispose1Called);
            Assert.True(dispose2Called);
        }
        public void SubscribeAndPublish_TrieStrategy_Dispose()
        {
            var target = new MessageBus(MessageBusCreateParameters.Default.WithWildcards());

            target.Dispose();
        }
Exemple #20
0
        public void DisposingBusShutsWorkersDown()
        {
            var dr = new DefaultDependencyResolver();
            var bus = new MessageBus(dr);
            var subscriber = new TestSubscriber(new[] { "key" });
            var wh = new ManualResetEventSlim(initialState: false);
            IDisposable subscription = null;

            try
            {
                subscription = bus.Subscribe(subscriber, null, result =>
                {
                    if (!result.Terminal)
                    {
                        var m = result.GetMessages().Single();

                        Assert.Equal("key", m.Key);
                        Assert.Equal("value", m.Value);

                        wh.Set();

                        return TaskAsyncHelper.True;
                    }

                    return TaskAsyncHelper.False;

                }, 10);

                bus.Publish("test", "key", "value").Wait();

                Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
            }
            finally
            {
                if (subscription != null)
                {
                    subscription.Dispose();
                }

                Assert.Equal(bus.AllocatedWorkers, 1);

                bus.Dispose();

                Assert.Equal(bus.AllocatedWorkers, 0);
            }
        }
Exemple #21
0
        public override void Dispose()
        {
            _bus.Dispose();

            base.Dispose();
        }
Exemple #22
0
 void ShutDownBus()
 {
     bus.Stop().GetAwaiter().GetResult();
     bus.Dispose();
 }
Exemple #23
0
 public void Dispose() => _messageBus.Dispose();