// constructors
        public MultiServerCluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
            : base(settings, serverFactory, eventSubscriber)
        {
            Ensure.IsGreaterThanZero(settings.EndPoints.Count, "settings.EndPoints.Count");
            if (settings.ConnectionMode == ClusterConnectionMode.Standalone)
            {
                throw new ArgumentException("ClusterConnectionMode.StandAlone is not supported for a MultiServerCluster.");
            }
            if (settings.ConnectionMode == ClusterConnectionMode.Direct)
            {
                throw new ArgumentException("ClusterConnectionMode.Direct is not supported for a MultiServerCluster.");
            }

            _monitorServersCancellationTokenSource = new CancellationTokenSource();
            _serverDescriptionChangedQueue = new AsyncQueue<ServerDescriptionChangedEventArgs>();
            _servers = new List<IClusterableServer>();
            _state = new InterlockedInt32(State.Initial);
            _replicaSetName = settings.ReplicaSetName;

            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _addingServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _addedServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _removingServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _removedServerEventHandler);
        }
        protected override void Init()
        {
            this.Kernel.ComponentCreated += this.OnComponentCreated;
            this.Kernel.ComponentDestroyed += this.OnComponentDestroyed;

            this.EventSubscriber = this.Kernel.Resolve<IEventSubscriber>();
        }
        // constructors
        public BinaryConnection(ServerId serverId, EndPoint endPoint, ConnectionSettings settings, IStreamFactory streamFactory, IConnectionInitializer connectionInitializer, IEventSubscriber eventSubscriber)
        {
            Ensure.IsNotNull(serverId, nameof(serverId));
            _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint));
            _settings = Ensure.IsNotNull(settings, nameof(settings));
            _streamFactory = Ensure.IsNotNull(streamFactory, nameof(streamFactory));
            _connectionInitializer = Ensure.IsNotNull(connectionInitializer, nameof(connectionInitializer));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));

            _backgroundTaskCancellationTokenSource = new CancellationTokenSource();
            _backgroundTaskCancellationToken = _backgroundTaskCancellationTokenSource.Token;

            _connectionId = new ConnectionId(serverId);
            _receiveLock = new SemaphoreSlim(1);
            _sendLock = new SemaphoreSlim(1);
            _state = new InterlockedInt32(State.Initial);

            _commandEventHelper = new CommandEventHelper(eventSubscriber);
            eventSubscriber.TryGetEventHandler(out _failedEventHandler);
            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _failedOpeningEventHandler);
            eventSubscriber.TryGetEventHandler(out _receivingMessageEventHandler);
            eventSubscriber.TryGetEventHandler(out _receivedMessageEventHandler);
            eventSubscriber.TryGetEventHandler(out _failedReceivingMessageEventHandler);
            eventSubscriber.TryGetEventHandler(out _sendingMessagesEventHandler);
            eventSubscriber.TryGetEventHandler(out _sentMessagesEventHandler);
            eventSubscriber.TryGetEventHandler(out _failedSendingMessagesEvent);
        }
        // constructors
        public ExclusiveConnectionPool(
            ServerId serverId,
            EndPoint endPoint,
            ConnectionPoolSettings settings,
            IConnectionFactory connectionFactory,
            IEventSubscriber eventSubscriber)
        {
            _serverId = Ensure.IsNotNull(serverId, nameof(serverId));
            _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint));
            _settings = Ensure.IsNotNull(settings, nameof(settings));
            _connectionFactory = Ensure.IsNotNull(connectionFactory, nameof(connectionFactory));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));

            _connectionHolder = new ListConnectionHolder(eventSubscriber);
            _poolQueue = new WaitQueue(settings.MaxConnections);
            _waitQueue = new SemaphoreSlim(settings.WaitQueueSize);
            _maintenanceCancellationTokenSource = new CancellationTokenSource();
            _state = new InterlockedInt32(State.Initial);

            eventSubscriber.TryGetEventHandler(out _checkingOutConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _checkedOutConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _checkingOutConnectionFailedEventHandler);
            eventSubscriber.TryGetEventHandler(out _checkingInConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _checkedInConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _addingConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _addedConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _addingConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _addedConnectionEventHandler);
        }
 // constructors
 public BinaryConnectionFactory(ConnectionSettings settings, IStreamFactory streamFactory, IEventSubscriber eventSubscriber)
 {
     _settings = Ensure.IsNotNull(settings, nameof(settings));
     _streamFactory = Ensure.IsNotNull(streamFactory, nameof(streamFactory));
     _eventSubscriber = Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));
     _connectionInitializer = new ConnectionInitializer(settings.ApplicationName);
 }
        protected override void Init()
        {
            Kernel.ComponentCreated += OnComponentCreated;
            Kernel.ComponentDestroyed += OnComponentDestroyed;

            EventSubscriber = Kernel.Resolve<IEventSubscriber>();
        }
 // constructors
 public ServerFactory(ClusterConnectionMode clusterConnectionMode, ServerSettings settings, IConnectionPoolFactory connectionPoolFactory, IConnectionFactory heartbeatConnectionFactory, IEventSubscriber eventSubscriber)
 {
     _clusterConnectionMode = clusterConnectionMode;
     _settings = Ensure.IsNotNull(settings, "settings");
     _connectionPoolFactory = Ensure.IsNotNull(connectionPoolFactory, "connectionPoolFactory");
     _heartbeatConnectionFactory = Ensure.IsNotNull(heartbeatConnectionFactory, "heartbeatConnectionFactory");
     _eventSubscriber = Ensure.IsNotNull(eventSubscriber, "eventSubscriber");
 }
 // constructors
 public ServerFactory(ClusterConnectionMode clusterConnectionMode, ServerSettings settings, IConnectionPoolFactory connectionPoolFactory, IServerMonitorFactory serverMonitoryFactory, IEventSubscriber eventSubscriber)
 {
     _clusterConnectionMode = clusterConnectionMode;
     _settings = Ensure.IsNotNull(settings, nameof(settings));
     _connectionPoolFactory = Ensure.IsNotNull(connectionPoolFactory, nameof(connectionPoolFactory));
     _serverMonitorFactory = Ensure.IsNotNull(serverMonitoryFactory, nameof(serverMonitoryFactory));
     _eventSubscriber = Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));
 }
Ejemplo n.º 9
0
        public EventSubscription(ScopedEventBus bus, Type messageType, IEventSubscriber subscriber)
        {
            if (subscriber == null)
            throw new ArgumentNullException("subscriber");

              this.bus = bus;
              this.messageType = messageType;
              this.subscriber = subscriber;
        }
Ejemplo n.º 10
0
 public ServerFactoryTests()
 {
     _clusterId = new ClusterId();
     _clusterConnectionMode = ClusterConnectionMode.Standalone;
     _connectionPoolFactory = new Mock<IConnectionPoolFactory>().Object;
     _endPoint = new DnsEndPoint("localhost", 27017);
     _serverMonitorFactory = new Mock<IServerMonitorFactory>().Object;
     _eventSubscriber = new Mock<IEventSubscriber>().Object;
     _settings = new ServerSettings();
 }
 public void Setup()
 {
     _clusterId = new ClusterId();
     _clusterConnectionMode = ClusterConnectionMode.Standalone;
     _connectionPoolFactory = Substitute.For<IConnectionPoolFactory>();
     _endPoint = new DnsEndPoint("localhost", 27017);
     _heartbeatConnectionFactory = Substitute.For<IConnectionFactory>();
     _eventSubscriber = Substitute.For<IEventSubscriber>();
     _settings = new ServerSettings();
 }
Ejemplo n.º 12
0
 public void Unsubscribe(string eventName, IEventSubscriber subscriber)
 {
     for (int i=0; i<_pairs.Length; i++)
     {
         if (_pairs[i].Name == eventName)
         {
             _pairs[i].Events -= subscriber.OnEvent;
             break;
         }
     }
 }
 public void Setup()
 {
     _connectionFactory = Substitute.For<IConnectionFactory>();
     _endPoint = new DnsEndPoint("localhost", 27017);
     _serverId = new ServerId(new ClusterId(), _endPoint);
     _eventSubscriber = Substitute.For<IEventSubscriber>();
     _settings = new ConnectionPoolSettings(
         maintenanceInterval: Timeout.InfiniteTimeSpan,
         maxConnections: 4,
         minConnections: 2,
         waitQueueSize: 1);
 }
 public ExclusiveConnectionPoolFactoryTests()
 {
     _connectionFactory = new Mock<IConnectionFactory>().Object;
     _endPoint = new DnsEndPoint("localhost", 27017);
     _serverId = new ServerId(new ClusterId(), _endPoint);
     _eventSubscriber = new Mock<IEventSubscriber>().Object;
     _settings = new ConnectionPoolSettings(
         maintenanceInterval: Timeout.InfiniteTimeSpan,
         maxConnections: 4,
         minConnections: 2,
         waitQueueSize: 1);
 }
        public ServerMonitor(ServerId serverId, EndPoint endPoint, IConnectionFactory connectionFactory, TimeSpan interval, TimeSpan timeout, IEventSubscriber eventSubscriber)
        {
            _serverId = Ensure.IsNotNull(serverId, nameof(serverId));
            _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint));
            _connectionFactory = Ensure.IsNotNull(connectionFactory, nameof(connectionFactory));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));

            _baseDescription = _currentDescription = new ServerDescription(_serverId, endPoint);
            _interval = interval;
            _timeout = timeout;
            _state = new InterlockedInt32(State.Initial);
            eventSubscriber.TryGetEventHandler(out _heartbeatStartedEventHandler);
            eventSubscriber.TryGetEventHandler(out _heartbeatSucceededEventHandler);
            eventSubscriber.TryGetEventHandler(out _heartbeatFailedEventHandler);
        }
        public CommandEventHelper(IEventSubscriber eventSubscriber)
        {
            eventSubscriber.TryGetEventHandler(out _startedEvent);
            eventSubscriber.TryGetEventHandler(out _succeededEvent);
            eventSubscriber.TryGetEventHandler(out _failedEvent);

            _shouldTrackState = _succeededEvent != null || _failedEvent != null;
            _shouldProcessRequestMessages = _startedEvent != null || _shouldTrackState;

            if (_shouldTrackState)
            {
                // we only need to track state if we have to raise
                // a succeeded or failed event
                _state = new ConcurrentDictionary<int, CommandState>();
            }
        }
        // constructor
        internal SingleServerCluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
            : base(settings, serverFactory, eventSubscriber)
        {
            Ensure.IsEqualTo(settings.EndPoints.Count, 1, "settings.EndPoints.Count");

            _state = new InterlockedInt32(State.Initial);

            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _addingServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _addedServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _removingServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _removedServerEventHandler);
        }
Ejemplo n.º 18
0
        // constructors
        protected Cluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
        {
            _settings = Ensure.IsNotNull(settings, "settings");
            _serverFactory = Ensure.IsNotNull(serverFactory, "serverFactory");
            Ensure.IsNotNull(eventSubscriber, "eventSubscriber");
            _state = new InterlockedInt32(State.Initial);

            _clusterId = new ClusterId();
            _description = ClusterDescription.CreateInitial(_clusterId, _settings.ConnectionMode);
            _descriptionChangedTaskCompletionSource = new TaskCompletionSource<bool>();

            _rapidHeartbeatTimer = new Timer(RapidHeartbeatTimerCallback, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);

            eventSubscriber.TryGetEventHandler(out _descriptionChangedEventHandler);
            eventSubscriber.TryGetEventHandler(out _selectingServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _selectedServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _selectingServerFailedEventHandler);
        }
Ejemplo n.º 19
0
 public void TriggerEvent(Event _event)
 {
     if (subscriptions.ContainsKey(_event))
     {
         int numLoops = subscriptions[_event].Count;
         for (int i = 0; i < numLoops; i++)
         {
             IEventSubscriber s = subscriptions[_event][i];
             MonoBehaviour    m = s as MonoBehaviour;
             if (s != null && m != null)
             {
                 s.InformOfEvent(_event);
             }
             else
             {
                 subscriptions[_event].RemoveAt(i);
             }
         }
     }
 }
Ejemplo n.º 20
0
        public NewProductEventProcessor(
            ILogger <NewProductEventProcessor> logger,
            IEventSubscriber eventSubscriber,
            IProductRepository productRepository,
            IProductCache productCache
            )
        {
            this.logger     = logger;
            this.subscriber = eventSubscriber;
            this.subscriber.ProductAddedEventReceived += (prd) => {
                //if (prd?.Product != null)
                //{
                //    productRepository.AddProduct(prd.Product);
                //    productCache.Put(prd.Product);
                //}
                //else if (prd?.Catagory != null)
                //{
                //    productRepository.AddCatagory(prd.Catagory);
                //}

                var product = new Product()
                {
                    ProductName = prd.ProductName,
                    ProductId   = prd.ProductId,
                    Description = prd.Description,
                    Price       = prd.Price,
                    CatagoryId  = prd.CatagoryId,
                };
                productRepository.AddProduct(product);
                productRepository.AddCatagory(
                    new Catagory
                {
                    CatagoryId   = prd.CatagoryId,
                    CatagoryCode = prd.CatagoryCode,
                    CatagoryDesc = prd.CatagoryDesc,
                    CatagoryName = prd.CatagoryName
                });

                productCache.Put(product);
            };
        }
Ejemplo n.º 21
0
        public EventConsumerActorTests()
        {
            consumerInfo.Position = Guid.NewGuid().ToString();
            consumerName          = eventConsumer.GetType().Name;

            A.CallTo(() => eventStore.CreateSubscription(A <IEventSubscriber> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(eventSubscription);

            A.CallTo(() => eventConsumer.Name).Returns(consumerName);
            A.CallTo(() => eventConsumerInfoRepository.FindAsync(consumerName)).Returns(consumerInfo);

            A.CallTo(() => formatter.Parse(eventData, true)).Returns(envelope);

            sut = new MyEventConsumerActor(
                formatter,
                eventStore,
                eventConsumerInfoRepository,
                log);

            sutActor      = sut;
            sutSubscriber = sut;
        }
Ejemplo n.º 22
0
        public NewProductEventProcessor(
            ILogger <NewProductEventProcessor> logger,
            IEventSubscriber eventSubscriber,
            IProductRepository productRepository,
            IProductCache productCache
            )
        {
            this.logger     = logger;
            this.subscriber = eventSubscriber;
            this.subscriber.ProductAddedEventReceived += (prd) => {
                var newProduct = new Product
                {
                    Name      = prd.Name,
                    ProductId = prd.ProductId,
                    Category  = prd.Category
                };
                productRepository.Add(newProduct);

                productCache.Put(newProduct);
            };
        }
        public GetEventStoreSubscription(
            IEventStoreConnection connection,
            IEventSubscriber subscriber,
            IJsonSerializer serializer,
            ProjectionClient projectionClient,
            string?position,
            string?prefix,
            string?streamFilter)
        {
            this.connection = connection;

            this.position = projectionClient.ParsePositionOrNull(position);
            this.prefix   = prefix;

            var streamName = projectionClient.CreateProjectionAsync(streamFilter).Result;

            this.serializer = serializer;
            this.subscriber = subscriber;

            subscription = SubscribeToStream(streamName);
        }
Ejemplo n.º 24
0
        public void RaiseEvent()
        {
            IWithEvents eventHolder = (IWithEvents)mocks.StrictMock(typeof(IWithEvents));

            eventHolder.Blah += null;
            LastCall.IgnoreArguments();
            raiser = LastCall.GetEventRaiser();
            eventHolder.RaiseEvent();
            LastCall.Do(new System.Threading.ThreadStart(UseEventRaiser));
            IEventSubscriber eventSubscriber = (IEventSubscriber)mocks.StrictMock(typeof(IEventSubscriber));

            eventSubscriber.Hanlder(this, EventArgs.Empty);

            mocks.ReplayAll();

            eventHolder.Blah += new EventHandler(eventSubscriber.Hanlder);

            eventHolder.RaiseEvent();

            mocks.VerifyAll();
        }
        // constructors
        public ExclusiveConnectionPool(
            ServerId serverId,
            EndPoint endPoint,
            ConnectionPoolSettings settings,
            IConnectionFactory connectionFactory,
            IEventSubscriber eventSubscriber)
        {
            _serverId          = Ensure.IsNotNull(serverId, nameof(serverId));
            _endPoint          = Ensure.IsNotNull(endPoint, nameof(endPoint));
            _settings          = Ensure.IsNotNull(settings, nameof(settings));
            _connectionFactory = Ensure.IsNotNull(connectionFactory, nameof(connectionFactory));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));

            _connectingQueue  = new SemaphoreSlimSignalable(MongoInternalDefaults.ConnectionPool.MaxConnecting);
            _connectionHolder = new ListConnectionHolder(eventSubscriber, _connectingQueue);
            _serviceStates    = new ServiceStates();
            _poolQueue        = new WaitQueue(settings.MaxConnections);
#pragma warning disable 618
            _waitQueue = new SemaphoreSlim(settings.WaitQueueSize);
#pragma warning restore 618
            _maintenanceCancellationTokenSource = new CancellationTokenSource();
            _state = new InterlockedInt32(State.Initial);

            eventSubscriber.TryGetEventHandler(out _checkingOutConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _checkedOutConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _checkingOutConnectionFailedEventHandler);
            eventSubscriber.TryGetEventHandler(out _checkingInConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _checkedInConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _addingConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _addedConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _addingConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _addedConnectionEventHandler);
            eventSubscriber.TryGetEventHandler(out _clearingEventHandler);
            eventSubscriber.TryGetEventHandler(out _clearedEventHandler);
            eventSubscriber.TryGetEventHandler(out _connectionCreatedEventHandler);
        }
Ejemplo n.º 26
0
 public TransitionRunner(
     ITransitionScope transitionScope,
     IAsyncStateMachineMetadataProvider asyncStateMachineMetadataProvider,
     //IServiceStateValueContainerProvider serviceStateValueContainerProvider,
     IUniqueIdGenerator idGenerator,
     ITaskCompletionSourceRegistry taskCompletionSourceRegistry,
     IServiceResolver serviceResolver,
     IMethodResolver methodResolver,
     IEventResolver eventResolver,
     ICommunicatorProvider communicatorProvider,
     IEventPublisherProvider eventPublisherProvider,
     IRoutineCompletionSink routineCompletionSink,
     ICommunicationSettingsProvider communicationSettingsProvider,
     IDefaultSerializerProvider defaultSerializerProvider,
     ISerializerProvider serializeProvder,
     IMethodStateStorageProvider methodStateStorageProvider,
     IValueContainerCopier valueContainerCopier,
     IEventSubscriber eventSubscriber,
     ITaskContinuationClassifier taskContinuationClassifier)
 {
     _transitionScope = transitionScope;
     _asyncStateMachineMetadataProvider = asyncStateMachineMetadataProvider;
     //_serviceStateValueContainerProvider = serviceStateValueContainerProvider;
     _idGenerator = idGenerator;
     _taskCompletionSourceRegistry = taskCompletionSourceRegistry;
     _serviceResolver               = serviceResolver;
     _methodResolver                = methodResolver;
     _eventResolver                 = eventResolver;
     _communicatorProvider          = communicatorProvider;
     _eventPublisherProvider        = eventPublisherProvider;
     _routineCompletionSink         = routineCompletionSink;
     _communicationSettingsProvider = communicationSettingsProvider;
     _defaultSerializer             = defaultSerializerProvider.DefaultSerializer;
     _serializeProvder              = serializeProvder;
     _methodStateStorageProvider    = methodStateStorageProvider;
     _valueContainerCopier          = valueContainerCopier;
     _eventSubscriber               = eventSubscriber;
     _taskContinuationClassifier    = taskContinuationClassifier;
 }
 public void Subscribe(string EventName, IEventSubscriber Subscriber)
 {
     bool been = false;
     for (int i=0; i<_pairs.Length; i++)
     {
         if (_pairs[i].Name == EventName)
         {
             _pairs[i].Events += Subscriber.OnEvent;
             been = true;
             break;
         }
     }
     if (!been)
     {
         EventPair x = new EventPair();
         x.Name = EventName;
         x.Events = (a,b) => {};
         x.Events += Subscriber.OnEvent;
         Array.Resize<EventPair>(ref _pairs,_pairs.Length+1);
         _pairs[_pairs.Length-1] = x;
     }
 }
Ejemplo n.º 28
0
 public ServerMonitor(
     ServerId serverId,
     EndPoint endPoint,
     IConnectionFactory connectionFactory,
     ServerMonitorSettings serverMonitorSettings,
     IEventSubscriber eventSubscriber,
     ServerApi serverApi)
     : this(
         serverId,
         endPoint,
         connectionFactory,
         serverMonitorSettings,
         eventSubscriber,
         roundTripTimeMonitor : new RoundTripTimeMonitor(
             connectionFactory,
             serverId,
             endPoint,
             Ensure.IsNotNull(serverMonitorSettings, nameof(serverMonitorSettings)).HeartbeatInterval,
             serverApi),
         serverApi)
 {
 }
Ejemplo n.º 29
0
        public DiscordService(DiscordSocketClient discordSocketClient,
                              CommandService commands,
                              IServiceScopeFactory scopeFactory,
                              ILogger <DiscordService> loggerService,
                              IOptions <DiscordOptions> options,
                              IEventSubscriber eventSubscriber,
                              IApplicationEnder applicationEnder) : base(applicationEnder)
        {
            _commands        = commands;
            _scopeFactory    = scopeFactory;
            _logger          = loggerService;
            _options         = options.Value;
            _eventSubscriber = eventSubscriber;

            _discordSocketClient = discordSocketClient;
            _retryPolicy         = Policy.Handle <Exception>(ex => ex.GetType() != typeof(TaskCanceledException))
                                   .WaitAndRetryAsync(10, _ => TimeSpan.FromSeconds(2),
                                                      (ex, time) =>
            {
                _logger.LogError(ex, "Exception during NATS connection. Waiting {Time}...", time);
            });
        }
        // constructors
        public MultiServerCluster(
            ClusterSettings settings,
            IClusterableServerFactory serverFactory,
            IEventSubscriber eventSubscriber,
            IDnsMonitorFactory dnsMonitorFactory = null)
            : base(settings, serverFactory, eventSubscriber)
        {
            Ensure.IsGreaterThanZero(settings.EndPoints.Count, "settings.EndPoints.Count");

#pragma warning disable CS0618 // Type or member is obsolete
            if (settings.ConnectionModeSwitch == ConnectionModeSwitch.UseDirectConnection)
            {
                Ensure.That(!settings.DirectConnection.GetValueOrDefault(), "DirectConnection is not supported for a MultiServerCluster.");
            }
            else
            {
                Ensure.That(settings.ConnectionMode != ClusterConnectionMode.Standalone, $"{nameof(ClusterConnectionMode.Standalone)} is not supported for a {nameof(MultiServerCluster)}.");
                Ensure.That(settings.ConnectionMode != ClusterConnectionMode.Direct, $"{nameof(ClusterConnectionMode.Direct)} is not supported for a {nameof(MultiServerCluster)}.");
            }
#pragma warning restore CS0618 // Type or member is obsolete

            _dnsMonitorFactory = dnsMonitorFactory ?? new DnsMonitorFactory(eventSubscriber);
            _monitorServersCancellationTokenSource = new CancellationTokenSource();
            _servers        = new List <IClusterableServer>();
            _state          = new InterlockedInt32(State.Initial);
            _replicaSetName = settings.ReplicaSetName;

            _eventSubscriber = eventSubscriber;
            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _addingServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _addedServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _removingServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _removedServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _sdamInformationEventHandler);
        }
Ejemplo n.º 31
0
        public PollingSubscription(
            IEventStore eventStore,
            IEventSubscriber eventSubscriber,
            string?streamFilter,
            string?position)
        {
            timer = new CompletionTimer(5000, async ct =>
            {
                try
                {
                    await foreach (var storedEvent in eventStore.QueryAllAsync(streamFilter, position, ct: ct))
                    {
                        await eventSubscriber.OnEventAsync(this, storedEvent);

                        position = storedEvent.EventPosition;
                    }
                }
                catch (Exception ex)
                {
                    await eventSubscriber.OnErrorAsync(this, ex);
                }
            });
        }
Ejemplo n.º 32
0
        private void SyncProcessEvent <TEvent>(TEvent @event, IEventSubscriber <TEvent> _h) where TEvent : IEvent
        {
            var _retry = _h.Strategy.Retry;
            var _fail  = false;

            do
            {
                try
                {
                    _fail = false;
                    _h.Handle(@event);
                }
                catch (Exception ex)
                {
                    _fail = true;
                    _h.Error(ex);
                }
            }while (Interlocked.Decrement(ref _retry) > 0 && _fail == true);
            if (_fail && _h.Strategy.PersistentStore.HasValue && _h.Strategy.PersistentStore.Value)
            {
                //TODO:持久化存储,处理失败的事件
            }
        }
Ejemplo n.º 33
0
 public ProxyMethodExecutor(
     ITransitionScope transitionScope,
     IMethodIdProvider routineMethodIdProvider,
     IEventIdProvider eventIdProvider,
     IUniqueIdGenerator numericIdGenerator,
     IRoutineCompletionNotifier routineCompletionNotifier,
     IEventSubscriber eventSubscriber,
     ICommunicationSettingsProvider communicationSettingsProvider,
     IMethodInvokerFactory methodInvokerFactory,
     ISingleMethodInvoker singleMethodInvoker,
     ISingleEventPublisher singleEventPublisher)
 {
     _transitionScope               = transitionScope;
     _routineMethodIdProvider       = routineMethodIdProvider;
     _eventIdProvider               = eventIdProvider;
     _idGenerator                   = numericIdGenerator;
     _routineCompletionNotifier     = routineCompletionNotifier;
     _eventSubscriber               = eventSubscriber;
     _communicationSettingsProvider = communicationSettingsProvider;
     _methodInvokerFactory          = methodInvokerFactory;
     _singleMethodInvoker           = singleMethodInvoker;
     _singleEventPublisher          = singleEventPublisher;
 }
Ejemplo n.º 34
0
    public void Subscribe(string EventName, IEventSubscriber Subscriber)
    {
        bool been = false;

        for (int i = 0; i < _pairs.Length; i++)
        {
            if (_pairs[i].Name == EventName)
            {
                _pairs[i].Events += Subscriber.OnEvent;
                been              = true;
                break;
            }
        }
        if (!been)
        {
            EventPair x = new EventPair();
            x.Name    = EventName;
            x.Events  = (a, b) => {};
            x.Events += Subscriber.OnEvent;
            Array.Resize <EventPair>(ref _pairs, _pairs.Length + 1);
            _pairs[_pairs.Length - 1] = x;
        }
    }
Ejemplo n.º 35
0
        // constructors
        public ServerFactory(
#pragma warning disable CS0618 // Type or member is obsolete
            ClusterConnectionMode clusterConnectionMode,
            ConnectionModeSwitch connectionModeSwitch,
#pragma warning restore CS0618 // Type or member is obsolete
            bool?directConnection,
            ServerSettings settings,
            IConnectionPoolFactory connectionPoolFactory,
            IServerMonitorFactory serverMonitoryFactory,
            IEventSubscriber eventSubscriber,
            ServerApi serverApi)
        {
            ClusterConnectionModeHelper.EnsureConnectionModeValuesAreValid(clusterConnectionMode, connectionModeSwitch, directConnection);

            _clusterConnectionMode = clusterConnectionMode;
            _connectionModeSwitch  = connectionModeSwitch;
            _directConnection      = directConnection;
            _settings = Ensure.IsNotNull(settings, nameof(settings));
            _connectionPoolFactory = Ensure.IsNotNull(connectionPoolFactory, nameof(connectionPoolFactory));
            _serverMonitorFactory  = Ensure.IsNotNull(serverMonitoryFactory, nameof(serverMonitoryFactory));
            _eventSubscriber       = Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));
            _serverApi             = serverApi; // can be null
        }
Ejemplo n.º 36
0
    public void TriggerEvent(Event _event)
    {
        if (subscriptions.ContainsKey(_event))
        {
            int numLoops = subscriptions[_event].Count;
            for (int i = 0; i < numLoops; i++)
            {
                IEventSubscriber s            = subscriptions[_event][i];
                bool             isEventValid = true;
                if (s != null)
                {
                    MonoBehaviour m = s as MonoBehaviour;

                    if (s != null && m != null)
                    {
                        s.InformOfEvent(_event);
                    }
                    else
                    {
                        isEventValid = false;
                    }
                }
                else
                {
                    isEventValid = false;
                }

                if (!isEventValid)
                {
                    subscriptions[_event].RemoveAt(i);

                    i--;
                    numLoops--;
                }
            }
        }
    }
Ejemplo n.º 37
0
        public PollingSubscription(
            IEventStore eventStore,
            IEventSubscriber eventSubscriber,
            string streamFilter,
            string position)
        {
            Guard.NotNull(eventStore, nameof(eventStore));
            Guard.NotNull(eventSubscriber, nameof(eventSubscriber));

            this.position        = position;
            this.eventStore      = eventStore;
            this.eventSubscriber = eventSubscriber;
            this.streamFilter    = streamFilter;

            streamRegex = new Regex(streamFilter);

            timer = new CompletionTimer(5000, async ct =>
            {
                try
                {
                    await eventStore.QueryAsync(async storedEvent =>
                    {
                        await eventSubscriber.OnEventAsync(this, storedEvent);

                        position = storedEvent.EventPosition;
                    }, streamFilter, position, ct);
                }
                catch (Exception ex)
                {
                    if (!ex.Is <OperationCanceledException>())
                    {
                        await eventSubscriber.OnErrorAsync(this, ex);
                    }
                }
            });
        }
Ejemplo n.º 38
0
        // constructors
        public Server(
            ClusterId clusterId,
            IClusterClock clusterClock,
#pragma warning disable CS0618 // Type or member is obsolete
            ClusterConnectionMode clusterConnectionMode,
            ConnectionModeSwitch connectionModeSwitch,
#pragma warning restore CS0618 // Type or member is obsolete
            bool?directConnection,
            ServerSettings settings,
            EndPoint endPoint,
            IConnectionPoolFactory connectionPoolFactory,
            IEventSubscriber eventSubscriber,
            ServerApi serverApi)
        {
            ClusterConnectionModeHelper.EnsureConnectionModeValuesAreValid(clusterConnectionMode, connectionModeSwitch, directConnection);

            _clusterClock          = Ensure.IsNotNull(clusterClock, nameof(clusterClock));
            _clusterConnectionMode = clusterConnectionMode;
            _connectionModeSwitch  = connectionModeSwitch;
            _directConnection      = directConnection;
            _settings = Ensure.IsNotNull(settings, nameof(settings));
            _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));

            _serverId                   = new ServerId(clusterId, endPoint);
            _connectionPool             = Ensure.IsNotNull(connectionPoolFactory, nameof(connectionPoolFactory)).CreateConnectionPool(_serverId, endPoint);
            _state                      = new InterlockedInt32(State.Initial);
            _serverApi                  = serverApi;
            _outstandingOperationsCount = 0;

            eventSubscriber.TryGetEventHandler(out _openingEventHandler);
            eventSubscriber.TryGetEventHandler(out _openedEventHandler);
            eventSubscriber.TryGetEventHandler(out _closingEventHandler);
            eventSubscriber.TryGetEventHandler(out _closedEventHandler);
            eventSubscriber.TryGetEventHandler(out _descriptionChangedEventHandler);
        }
Ejemplo n.º 39
0
        public GetEventStoreSubscription(
            IEventStoreConnection eventStoreConnection,
            IEventSubscriber eventSubscriber,
            string projectionHost,
            string prefix,
            string position,
            string streamFilter)
        {
            Guard.NotNull(eventSubscriber, nameof(eventSubscriber));
            Guard.NotNullOrEmpty(streamFilter, nameof(streamFilter));

            this.eventStoreConnection = eventStoreConnection;
            this.eventSubscriber      = eventSubscriber;
            this.position             = ParsePosition(position);
            this.prefix         = prefix;
            this.projectionHost = projectionHost;
            this.streamFilter   = streamFilter;

            var streamName = ParseFilter(prefix, streamFilter);

            InitializeAsync(streamName).Wait();

            subscription = SubscribeToStream(streamName);
        }
Ejemplo n.º 40
0
        public LoadBalancedServer(
            ClusterId clusterId,
            IClusterClock clusterClock,
            ServerSettings serverSettings,
            EndPoint endPoint,
            IConnectionPoolFactory connectionPoolFactory,
            IEventSubscriber eventSubscriber,
            ServerApi serverApi)
            : base(
                clusterId,
                clusterClock,
#pragma warning disable CS0618 // Type or member is obsolete
                ClusterConnectionMode.Automatic,
                ConnectionModeSwitch.UseConnectionMode,
#pragma warning restore CS0618 // Type or member is obsolete
                directConnection: null,
                serverSettings,
                endPoint,
                connectionPoolFactory,
                eventSubscriber,
                serverApi)
        {
            _baseDescription = _currentDescription = new ServerDescription(ServerId, endPoint, reasonChanged: "ServerInitialDescription");
        }
Ejemplo n.º 41
0
        public void RaiseEvent()
        {
            IWithEvents eventHolder = MockRepository.Mock <IWithEvents>();

            eventHolder.ExpectEvent(x => x.Blah += null)
            .IgnoreArguments();

            eventHolder.Expect(x => x.RaiseEvent())
            .DoInstead(new System.Threading.ThreadStart(delegate()
            {
                eventHolder.Raise(x => x.Blah += null,
                                  new object[] { this, EventArgs.Empty });
            }));

            IEventSubscriber eventSubscriber = MockRepository.Mock <IEventSubscriber>();

            eventSubscriber.Expect(x => x.Hanlder(this, EventArgs.Empty));

            eventHolder.Blah += new EventHandler(eventSubscriber.Hanlder);
            eventHolder.RaiseEvent();

            eventHolder.VerifyExpectations();
            eventSubscriber.VerifyExpectations();
        }
Ejemplo n.º 42
0
 public bool Unsubscribe(IEventSubscriber subscriber)
 {
     PublisherEvent -= subscriber.OnEvent;
     return(true);
 }
Ejemplo n.º 43
0
 protected override IEventSubscription CreateSubscription(IEventStore store, IEventSubscriber subscriber, string streamFilter, string position)
 {
     return(store.CreateSubscription(subscriber, streamFilter, position));
 }
Ejemplo n.º 44
0
 protected virtual IEventSubscription CreateSubscription(IEventStore store, IEventSubscriber subscriber, string streamFilter, string position)
 {
     return(new RetrySubscription(store, subscriber, streamFilter, position));
 }
Ejemplo n.º 45
0
            protected override IEventSubscription CreateSubscription(IEventSubscriber subscriber)
            {
                currentSubscriber = subscriber;

                return(base.CreateSubscription(subscriber));
            }
Ejemplo n.º 46
0
 protected override IEventSubscription CreateRetrySubscription(IEventSubscriber subscriber)
 {
     return(CreateSubscription(subscriber));
 }
            public StubCluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
                : base(settings, serverFactory, eventSubscriber)
            {


            }
Ejemplo n.º 48
0
        // constructors
        protected Cluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
        {
            _settings      = Ensure.IsNotNull(settings, nameof(settings));
            _serverFactory = Ensure.IsNotNull(serverFactory, nameof(serverFactory));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));
            _state = new InterlockedInt32(State.Initial);

            _clusterId   = new ClusterId();
            _description = ClusterDescription.CreateInitial(_clusterId, _settings.ConnectionMode);
            _descriptionChangedTaskCompletionSource = new TaskCompletionSource <bool>();
            _latencyLimitingServerSelector          = new LatencyLimitingServerSelector(settings.LocalThreshold);

            _rapidHeartbeatTimer = new Timer(RapidHeartbeatTimerCallback, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);

            eventSubscriber.TryGetEventHandler(out _descriptionChangedEventHandler);
            eventSubscriber.TryGetEventHandler(out _selectingServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _selectedServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _selectingServerFailedEventHandler);

            _serverSessionPool = new CoreServerSessionPool(this);
        }
 // constructors
 public ClusterFactory(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
 {
     _settings = Ensure.IsNotNull(settings, "settings");
     _serverFactory = Ensure.IsNotNull(serverFactory, "serverFactory");
     _eventSubscriber = Ensure.IsNotNull(eventSubscriber, "eventSubscriber");
 }
 // constructors
 public BinaryConnectionFactory(ConnectionSettings settings, IStreamFactory streamFactory, IEventSubscriber eventSubscriber)
 {
     _settings = Ensure.IsNotNull(settings, "settings");
     _streamFactory = Ensure.IsNotNull(streamFactory, "streamFactory");
     _eventSubscriber = Ensure.IsNotNull(eventSubscriber, "eventSubscriber");
 }
 public ExclusiveConnectionPoolFactory(ConnectionPoolSettings settings, IConnectionFactory connectionFactory, IEventSubscriber eventSubscriber)
 {
     _settings = Ensure.IsNotNull(settings, nameof(settings));
     _connectionFactory = Ensure.IsNotNull(connectionFactory, nameof(connectionFactory));
     _eventSubscriber = Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));
 }
 // constructors
 public BinaryConnectionFactory(ConnectionSettings settings, IStreamFactory streamFactory, IEventSubscriber eventSubscriber)
 {
     _settings = Ensure.IsNotNull(settings, nameof(settings));
     _streamFactory = Ensure.IsNotNull(streamFactory, nameof(streamFactory));
     _eventSubscriber = Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));
 }
Ejemplo n.º 53
0
 // constructors
 public ClusterFactory(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
 {
     _settings = Ensure.IsNotNull(settings, nameof(settings));
     _serverFactory = Ensure.IsNotNull(serverFactory, nameof(serverFactory));
     _eventSubscriber = Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));
 }
 public void Unsubscribe(IEventSubscriber Subscriber)
 {
     for (int i=0; i<_pairs.Length; i++)
     {
         _pairs[i].Events -= Subscriber.OnEvent;
     }
 }
 public void SubscribeToAllEvents(IEventSubscriber Subscciber)
 {
     _onAll += Subscciber.OnEvent;
 }
Ejemplo n.º 56
0
 public CommonSubscribtionBuilder(IWebHost webHost, IMessageBus bus, IEventSubscriber subscriber)
 {
     _webHost    = webHost;
     _bus        = bus;
     _subscriber = subscriber;
 }
Ejemplo n.º 57
0
        // constructors
        protected Cluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
        {
            _settings      = Ensure.IsNotNull(settings, nameof(settings));
            _serverFactory = Ensure.IsNotNull(serverFactory, nameof(serverFactory));
            Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber));
            _state = new InterlockedInt32(State.Initial);
            _rapidHeartbeatTimerCallbackState = new InterlockedInt32(RapidHeartbeatTimerCallbackState.NotRunning);

            _clusterId   = new ClusterId();
            _description = CreateInitialDescription();
            _descriptionChangedTaskCompletionSource = new TaskCompletionSource <bool>();
            _latencyLimitingServerSelector          = new LatencyLimitingServerSelector(settings.LocalThreshold);

            _rapidHeartbeatTimer = new Timer(RapidHeartbeatTimerCallback, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);

            eventSubscriber.TryGetEventHandler(out _descriptionChangedEventHandler);
            eventSubscriber.TryGetEventHandler(out _selectingServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _selectedServerEventHandler);
            eventSubscriber.TryGetEventHandler(out _selectingServerFailedEventHandler);

            _serverSessionPool = new CoreServerSessionPool(this);

            ClusterDescription CreateInitialDescription()
            {
#pragma warning disable CS0618 // Type or member is obsolete
                var connectionModeSwitch  = _settings.ConnectionModeSwitch;
                var clusterConnectionMode = connectionModeSwitch == ConnectionModeSwitch.UseConnectionMode ? _settings.ConnectionMode : default;
                var directConnection      = connectionModeSwitch == ConnectionModeSwitch.UseDirectConnection ? _settings.DirectConnection : default;
                return(ClusterDescription.CreateInitial(_clusterId, clusterConnectionMode, _settings.ConnectionModeSwitch, directConnection));

#pragma warning restore CS0618 // Type or member is obsolete
            }
        }
Ejemplo n.º 58
0
 public void UnsubscribeToAllEvents(IEventSubscriber Subscriber)
 {
     _onAll -= Subscriber.OnEvent;
 }
            public ListConnectionHolder(IEventSubscriber eventSubscriber)
            {
                _connections = new List<PooledConnection>();

                eventSubscriber.TryGetEventHandler(out _removingConnectionEventHandler);
                eventSubscriber.TryGetEventHandler(out _removedConnectionEventHandler);
            }
Ejemplo n.º 60
0
        private ICluster BuildCluster(BsonDocument definition)
        {
            var connectionString = new ConnectionString((string)definition["uri"]);
            var settings = new ClusterSettings(
                endPoints: Optional.Enumerable(connectionString.Hosts),
                connectionMode: connectionString.Connect,
                replicaSetName: connectionString.ReplicaSet);

            _serverFactory = new MockClusterableServerFactory();
            _eventSubscriber = Substitute.For<IEventSubscriber>();
            return new ClusterFactory(settings, _serverFactory, _eventSubscriber)
                .CreateCluster();
        }