public virtual void Setup()
        {
            Envelope.Replies.Clear();
            Publisher.Messages.Clear();

            Manager = OnManager(Publisher);
            Dispatcher.Subscribe <StorageMessage.PrepareAck>(Manager);
            Dispatcher.Subscribe <StorageMessage.CommitAck>(Manager);
            Dispatcher.Subscribe <StorageMessage.InvalidTransaction>(Manager);
            Dispatcher.Subscribe <StorageMessage.StreamDeleted>(Manager);
            Dispatcher.Subscribe <StorageMessage.WrongExpectedVersion>(Manager);
            Dispatcher.Subscribe <StorageMessage.AlreadyCommitted>(Manager);
            Dispatcher.Subscribe <StorageMessage.RequestManagerTimerTick>(Manager);
            Dispatcher.Subscribe <ReplicationTrackingMessage.IndexedTo>(CommitSource);
            Dispatcher.Subscribe <ReplicationTrackingMessage.ReplicatedTo>(CommitSource);
            if (Manager is TransactionCommit txCommitMrg)
            {
                Dispatcher.Subscribe <StorageMessage.CommitIndexed>(txCommitMrg);
            }

            Manager.Start();
            Given();
            foreach (var msg in WithInitialMessages())
            {
                Dispatcher.Publish(msg);
            }

            Publisher.Messages.Clear();
            Envelope.Replies.Clear();
            Dispatcher.Publish(When());
            Produced = new List <Message>(Publisher.Messages);
        }
        private void StartComponents()
        {
            if (_nodeState != VNodeState.Leader)
            {
                _logger.Debug("PROJECTIONS SUBSYSTEM: Not starting because node is not leader. Current node state: {nodeState}",
                              _nodeState);
                return;
            }
            if (_subsystemState != SubsystemState.Ready && _subsystemState != SubsystemState.Stopped)
            {
                _logger.Debug("PROJECTIONS SUBSYSTEM: Not starting because system is not ready or stopped. Current Subsystem state: {subsystemState}",
                              _subsystemState);
                return;
            }
            if (_runningComponentCount > 0)
            {
                _logger.Warning("PROJECTIONS SUBSYSTEM: Subsystem is stopped, but components are still running.");
                return;
            }

            _subsystemState        = SubsystemState.Starting;
            _restarting            = false;
            _instanceCorrelationId = Guid.NewGuid();
            _logger.Information("PROJECTIONS SUBSYSTEM: Starting components for Instance: {instanceCorrelationId}", _instanceCorrelationId);
            _pendingComponentStarts = _componentCount;
            _leaderMainBus.Publish(new ProjectionSubsystemMessage.StartComponents(_instanceCorrelationId));
        }
 /// <summary>
 /// Custom Stream name
 /// i.e. [StreamName]
 /// </summary>
 /// <param name="streamName"></param>
 /// <param name="checkpoint"></param>
 /// <param name="blockUntilLive"></param>
 /// <param name="timeout">timeout in milliseconds default = 1000</param>
 public virtual void Start(
     string streamName,
     long?checkpoint     = null,
     bool blockUntilLive = false,
     int timeout         = 1000)
 {
     _liveLock.Reset();
     lock (_startlock) {
         if (_started)
         {
             throw new InvalidOperationException("Listener already started.");
         }
         if (!ValidateStreamName(streamName))
         {
             throw new ArgumentException("Stream not found.", streamName);
         }
         StreamName    = streamName;
         _subscription =
             SubscribeToStreamFrom(
                 streamName,
                 checkpoint,
                 true,
                 eventAppeared: GotEvent,
                 liveProcessingStarted: () => {
             _bus.Publish(new StreamStoreMsgs.CatchupSubscriptionBecameLive());
             _liveLock.Set();
         });
         _started = true;
     }
     if (blockUntilLive)
     {
         _liveLock.Wait(timeout);
     }
 }
        public virtual void Setup()
        {
            Envelope.Replies.Clear();
            Publisher.Messages.Clear();

            Given();
            Envelope.Replies.Clear();
            Publisher.Messages.Clear();

            Dispatcher.Publish(When());
        }
Beispiel #5
0
        public async Task should_publish_with_delay()
        {
            var called = false;

            _bus.Subscribe(x => {
                called = true;
            });
            _bus.Publish(new object(), 1);
            await Task.Delay(10);

            called.ShouldBeTrue();
        }
 private void PublishInitialized()
 {
     if (Interlocked.CompareExchange(ref _subsystemInitialized, 1, 0) == 0)
     {
         _leaderOutputBus.Publish(new SystemMessage.SubSystemInitialized("Projections"));
     }
 }
Beispiel #7
0
        private void NonDisposableTarget(InMemoryBus bus, Action action)
        {
            var target = new OneBlankMessageClass(action);

            bus.AutoWire(target);
            bus.Publish(new BlankMessage());
        }
Beispiel #8
0
        public void When_a_constraint_doesnt_allow_publishing()
        {
            var             bus    = new InMemoryBus();
            Action <String> action = s => { };

            bus.Constraints.Add(new ThrowingBeforePublishConstraint());

            Assert.Throws <ConstraintException>(() => bus.Publish("string"));
        }
 public void should_unsubscrible() {
   var bus = new InMemoryBus();
   bool subscriber_called = false;
   var handler =
     Handlers.Runnable<MyMessage>(msg => { subscriber_called = true; });
   bus.Subscribe(handler);
   bus.Unsubscribe(handler);
   bus.Publish(new MyMessage {Message = "MyMessage"});
   Assert.That(subscriber_called, Is.EqualTo(false));
 }
 public void should_publish_message_to_subscribers() {
   var bus = new InMemoryBus();
   bool subscriber_called = false;
   bus.Subscribe(Handlers.Runnable<MyMessage>(msg => {
     Assert.That(msg.Message, Is.EqualTo("MyMessage"));
     subscriber_called = true;
   }));
   bus.Publish(new MyMessage {Message = "MyMessage"});
   Assert.That(subscriber_called, Is.EqualTo(true));
 }
Beispiel #11
0
        public void When_there_is_one_method_matching()
        {
            var bus    = new InMemoryBus();
            var count  = 0;
            var target = new OneBlankMessageClass(() => count++);

            bus.AutoWire(target);
            bus.Publish(new BlankMessage());

            count.ShouldEqual(1);
        }
Beispiel #12
0
        public void When_the_bus_recives_a_message_it_should_invoke_the_handler()
        {
            var bus   = new InMemoryBus();
            var count = 0;
            Action <BlankMessage> handler = message => count++;

            bus.Wire(handler);
            bus.Publish(new BlankMessage());

            count.ShouldEqual(1);
        }
 public void Handle(CoreProjectionStatusMessage.Stopped message)
 {
     if (_startStandardProjections)
     {
         if (_standardProjections.Contains(message.Name))
         {
             _standardProjections.Remove(message.Name);
             var envelope = new NoopEnvelope();
             _masterMainBus.Publish(new ProjectionManagementMessage.Command.Enable(envelope, message.Name, ProjectionManagementMessage.RunAs.System));
         }
     }
 }
        public MockRepositorySpecification()
        {
            StreamNameBuilder     = new PrefixedCamelCaseStreamNameBuilder();
            StreamStoreConnection = new MockStreamStoreConnection("Test");
            StreamStoreConnection.Connect();
            EventSerializer = new JsonMessageSerializer();
            MockRepository  = new StreamStoreRepository(StreamNameBuilder, StreamStoreConnection, EventSerializer);

            var connectorBus = new InMemoryBus("connector");

            StreamStoreConnection.SubscribeToAll(evt => connectorBus.Publish((IMessage)EventSerializer.Deserialize(evt)));
            RepositoryEvents = new TestQueue(connectorBus, new[] { typeof(Event) });
        }
Beispiel #15
0
        public void When_a_handler_is_unwired()
        {
            var bus   = new InMemoryBus();
            var count = 0;
            Action <BlankMessage> handler = message => count++;

            bus.Wire(handler);
            bus.UnWire(handler);

            bus.Publish(new BlankMessage());

            count.ShouldEqual(0);
        }
Beispiel #16
0
        public void When_the_target_is_disposed_it_should_un_wire()
        {
            var bus   = new InMemoryBus();
            var count = 0;

            DisposableTarget(bus, () => count++);

            GC.WaitForPendingFinalizers();
            GC.Collect();

            bus.Publish(new BlankMessage());

            count.ShouldEqual(1);
        }
        private void AllComponentsStarted()
        {
            _logger.Info("PROJECTIONS SUBSYSTEM: All components started for Instance: {instanceCorrelationId}",
                         _instanceCorrelationId);
            _subsystemState = SubsystemState.Started;
            _masterOutputBus.Publish(new SystemMessage.SubSystemInitialized("Projections"));

            if (_nodeState != VNodeState.Master)
            {
                _logger.Info("PROJECTIONS SUBSYSTEM: Node state is no longer Master. Stopping projections. Current node state: {nodeState}",
                             _nodeState);
                StopComponents();
            }
        }
 /// <summary>
 /// Custom Stream name
 /// i.e. [StreamName]
 /// </summary>
 /// <param name="streamName"></param>
 /// <param name="checkpoint"></param>
 /// <param name="blockUntilLive"></param>
 /// <param name="cancelWaitToken">Cancellation token to cancel waiting if blockUntilLive is true</param>
 public virtual void Start(
     string streamName,
     long?checkpoint     = null,
     bool blockUntilLive = false,
     CancellationToken cancelWaitToken = default(CancellationToken))
 {
     _liveLock.Reset();
     lock (_startLock)
     {
         if (_started)
         {
             throw new InvalidOperationException("Listener already started.");
         }
         if (!ValidateStreamName(streamName))
         {
             throw new ArgumentException("Stream not found.", streamName);
         }
         StreamName    = streamName;
         _subscription =
             SubscribeToStreamFrom(
                 streamName,
                 checkpoint,
                 eventAppeared: GotEvent,
                 liveProcessingStarted: () =>
         {
             Bus.Publish(new StreamStoreMsgs.CatchupSubscriptionBecameLive());
             _liveLock.Set();
             _liveProcessingStarted?.Invoke(Unit.Default);
         });
         _started = true;
     }
     if (blockUntilLive)
     {
         _liveLock.Wait(cancelWaitToken);
     }
 }
Beispiel #19
0
        protected virtual void EventRead(RecordedEvent recordedEvent)
        {
            // do not publish or increase counters if cancelled
            if (_cancelled)
            {
                return;
            }

            Interlocked.Exchange(ref StreamPosition, recordedEvent.EventNumber);
            firstEventRead = true;

            if (Serializer.Deserialize(recordedEvent) is IMessage @event)
            {
                Bus.Publish(@event);
            }
        }
Beispiel #20
0
        public async Task Publish_ToUnsubscribedEvent_NothingHappens()
        {
            var ev = new NewCommitteeEvent(Guid.NewGuid(), "Test Committee", "mandate");
            bool hasRun = false;
            Action<object, IDictionary<string, string>> action = (o, h) => hasRun = true;

            using (var bus = new InMemoryBus())
            {
                await bus.Subscribe<NewDepartmentEvent>(action);
                await bus.Publish(ev);
                await bus.Start();
                Thread.Sleep(20);
            }
            
            Assert.False(hasRun);
        }
Beispiel #21
0
        public async Task Publish_ToSubscribedEvent_RunsTask()
        {
            var ev = new NewCommitteeEvent(Guid.NewGuid(), "Test Committee", "mandate");
            bool hasRun = false;
            Action<object, IDictionary<string, string>> action = (o, h) => hasRun = true;

            using (var bus = new InMemoryBus())
            {
                await bus.Subscribe<NewCommitteeEvent>(action);
                await bus.Publish(ev);
                await bus.Start();
                Thread.Sleep(20);//give task time to complete
            }
            
            Assert.True(hasRun);
        }
Beispiel #22
0
        public async Task Publish_ToUnsubscribedEvent_NothingHappens()
        {
            var  ev     = new NewCommitteeEvent(Guid.NewGuid(), "Test Committee", "mandate");
            bool hasRun = false;
            Action <object, IDictionary <string, string> > action = (o, h) => hasRun = true;

            using (var bus = new InMemoryBus())
            {
                await bus.Subscribe <NewDepartmentEvent>(action);

                await bus.Publish(ev);

                await bus.Start();

                Thread.Sleep(20);
            }

            Assert.False(hasRun);
        }
Beispiel #23
0
        public async Task Publish_ToSubscribedEvent_RunsTask()
        {
            var  ev     = new NewCommitteeEvent(Guid.NewGuid(), "Test Committee", "mandate");
            bool hasRun = false;
            Action <object, IDictionary <string, string> > action = (o, h) => hasRun = true;

            using (var bus = new InMemoryBus())
            {
                await bus.Subscribe <NewCommitteeEvent>(action);

                await bus.Publish(ev);

                await bus.Start();

                Thread.Sleep(20);//give task time to complete
            }

            Assert.True(hasRun);
        }
Beispiel #24
0
        public void Start()
        {
            if (_masterInputQueue != null)
            {
                _masterInputQueue.Start();
            }
            foreach (var queue in _coreQueues)
            {
                queue.Value.Start();
            }

            if (_developmentMode)
            {
                var standardProjections = new List <string> {
                    "$by_category", "$stream_by_category", "$streams", "$by_event_type"
                };
                foreach (var standardProjection in standardProjections)
                {
                    var envelope = new NoopEnvelope();
                    _masterMainBus.Publish(new ProjectionManagementMessage.Command.Enable(envelope, standardProjection, ProjectionManagementMessage.RunAs.System));
                }
            }
        }
Beispiel #25
0
        public void Setup()
        {
            var address    = IPAddress.Loopback;
            var members    = new List <MemberInfo>();
            var seeds      = new List <IPEndPoint>();
            var seedSource = new ReallyNotSafeFakeGossipSeedSource(seeds);

            _nodes = new Dictionary <IPEndPoint, IPublisher>();
            for (int i = 0; i < 3; i++)
            {
                var inputBus  = new InMemoryBus($"ELECTIONS-INPUT-BUS-NODE-{i}", watchSlowMsg: false);
                var outputBus = new InMemoryBus($"ELECTIONS-OUTPUT-BUS-NODE-{i}", watchSlowMsg: false);
                var endPoint  = new IPEndPoint(address, 1000 + i);
                seeds.Add(endPoint);
                var instanceId = Guid.Parse($"101EFD13-F9CD-49BE-9C6D-E6AF9AF5540{i}");
                members.Add(MemberInfo.ForVNode(instanceId, DateTime.UtcNow, VNodeState.Unknown, true,
                                                endPoint, null, endPoint, null, endPoint, endPoint, -1, 0, 0, -1, -1, Guid.Empty, 0, false)
                            );
                var nodeInfo = new VNodeInfo(instanceId, 0, endPoint, endPoint, endPoint, endPoint, endPoint,
                                             endPoint, false);
                _fakeTimeProvider = new FakeTimeProvider();
                _scheduler        = new FakeScheduler(new FakeTimer(), _fakeTimeProvider);
                var timerService = new TimerService(_scheduler);

                var         writerCheckpoint   = new InMemoryCheckpoint();
                var         readerCheckpoint   = new InMemoryCheckpoint();
                var         epochManager       = new FakeEpochManager();
                Func <long> lastCommitPosition = () => - 1;
                var         electionsService   = new Core.Services.ElectionsService(outputBus,
                                                                                    nodeInfo,
                                                                                    3,
                                                                                    writerCheckpoint,
                                                                                    readerCheckpoint,
                                                                                    epochManager,
                                                                                    () => - 1, 0, new FakeTimeProvider());
                electionsService.SubscribeMessages(inputBus);

                outputBus.Subscribe <HttpMessage.SendOverHttp>(this);
                var nodeId = i;
                outputBus.Subscribe(new AdHocHandler <Message>(
                                        m => {
                    switch (m)
                    {
                    case TimerMessage.Schedule sm:
                        TestContext.WriteLine(
                            $"Node {nodeId} : Delay {sm.TriggerAfter} : {sm.ReplyMessage.GetType()}");
                        timerService.Handle(sm);
                        break;

                    case HttpMessage.SendOverHttp hm:
                        TestContext.WriteLine($"Node {nodeId} : EP {hm.EndPoint} : {hm.Message.GetType()}");
                        break;

                    default:
                        TestContext.WriteLine($"Node {nodeId} : EP {m.GetType()}");
                        inputBus.Publish(m);
                        break;
                    }
                }
                                        ));
                _nodes.Add(endPoint, inputBus);

                var gossip = new NodeGossipService(outputBus, seedSource, nodeInfo, writerCheckpoint, readerCheckpoint,
                                                   epochManager, lastCommitPosition, 0, TimeSpan.FromMilliseconds(500), TimeSpan.FromDays(1),
                                                   _fakeTimeProvider);
                inputBus.Subscribe <SystemMessage.SystemInit>(gossip);
                inputBus.Subscribe <GossipMessage.RetrieveGossipSeedSources>(gossip);
                inputBus.Subscribe <GossipMessage.GotGossipSeedSources>(gossip);
                inputBus.Subscribe <GossipMessage.Gossip>(gossip);
                inputBus.Subscribe <GossipMessage.GossipReceived>(gossip);
                inputBus.Subscribe <SystemMessage.StateChangeMessage>(gossip);
                inputBus.Subscribe <GossipMessage.GossipSendFailed>(gossip);
                inputBus.Subscribe <GossipMessage.UpdateNodePriority>(gossip);
                inputBus.Subscribe <SystemMessage.VNodeConnectionEstablished>(gossip);
                inputBus.Subscribe <SystemMessage.VNodeConnectionLost>(gossip);
            }

            _members = members;
        }
Beispiel #26
0
 public void Publish(Message message)
 {
     _bus.Publish(message);
 }
        public void one_handler_to_one_message_it_should_be_handled()
        {
            var handler = new TestHandler <TestMessage>();

            _bus.Subscribe <TestMessage>(handler);

            _bus.Publish(new TestMessage());

            Assert.That(handler.HandledMessages.ContainsSingle <TestMessage>());
        }
 public void null_message_app_should_throw()
 {
     Assert.Throws <ArgumentNullException>(() => _bus.Publish(null));
 }
Beispiel #29
0
        public void When_the_bus_recieves_a_message_and_there_is_no_handler()
        {
            var bus = new InMemoryBus();

            Assert.DoesNotThrow(() => bus.Publish(new BlankMessage()));
        }
Beispiel #30
0
        public void handler_from_message_it_should_not_handle_this_message_anymore()
        {
            var handler = new TestHandler <TestMessage>();

            _bus.Subscribe <TestMessage>(handler);

            _bus.Unsubscribe <TestMessage>(handler);
            _bus.Publish(new TestMessage());

            Assert.That(handler.HandledMessages.IsEmpty());
        }
Beispiel #31
0
 public void Publish(Message message)
 {
     InputMessages.Add(message);
     _bus.Publish(message);
 }