public void Setup()
 {
     _settings = new ClusterSettings(serverSelectionTimeout: TimeSpan.FromSeconds(2),
         postServerSelector: new LatencyLimitingServerSelector(TimeSpan.FromMinutes(2)));
     _serverFactory = Substitute.For<IClusterableServerFactory>();
     _capturedEvents = new EventCapturer();
 }
        // constructor
        internal SingleServerCluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IClusterListener listener)
            : base(settings, serverFactory, listener)
        {
            Ensure.IsEqualTo(settings.EndPoints.Count, 1, "settings.EndPoints.Count");

            _state = new InterlockedInt32(State.Initial);
        }
        public void Constructor_should_throw_if_no_endpoints_are_specified()
        {
            var settings = new ClusterSettings(endPoints: new EndPoint[0]);
            Action act = () => new MultiServerCluster(settings, _serverFactory, _capturedEvents);

            act.ShouldThrow<ArgumentOutOfRangeException>();
        }
        public void Constructor_should_throw_if_more_than_one_endpoint_is_specified()
        {
            _settings = _settings.With(endPoints: new[] { _endPoint, new DnsEndPoint("localhost", 27018) });
            Action act = () => new SingleServerCluster(_settings, _serverFactory, _capturedEvents);

            act.ShouldThrow<ArgumentException>();
        }
        // 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);
        }
 // constructors
 public ClusterBuilder()
 {
     _clusterSettings = new ClusterSettings();
     _serverSettings = new ServerSettings();
     _connectionPoolSettings = new ConnectionPoolSettings();
     _connectionSettings = new ConnectionSettings();
     _tcpStreamSettings = new TcpStreamSettings();
     _streamFactoryWrapper = inner => inner;
 }
        public void Constructor_should_throw_if_cluster_connection_mode_is_not_supported(ClusterConnectionMode mode)
        {
            var settings = new ClusterSettings(
                endPoints: new[] { new DnsEndPoint("localhost", 27017) },
                connectionMode: mode);
            Action act = () => new MultiServerCluster(settings, _serverFactory, _capturedEvents);

            act.ShouldThrow<ArgumentException>();
        }
        public void Initialize_should_throw_when_already_disposed()
        {
            _settings = _settings.WithEndPoints(new [] { _firstEndPoint });
            var subject = CreateSubject();
            subject.Dispose();

            Action act = () => subject.Initialize();

            act.ShouldThrow<ObjectDisposedException>();
        }
        public void constructor_should_initialize_instance()
        {
            var subject = new ClusterSettings();

            subject.ConnectionMode.Should().Be(ClusterConnectionMode.Automatic);
            subject.EndPoints.Should().EqualUsing(new[] { new DnsEndPoint("localhost", 27017) }, EndPointHelper.EndPointEqualityComparer);
            subject.MaxServerSelectionWaitQueueSize.Should().Be(500);
            subject.ReplicaSetName.Should().Be(null);
            subject.ServerSelectionTimeout.Should().Be(TimeSpan.FromSeconds(30));
        }
 private ClusterSettings ConfigureCluster(ClusterSettings settings, ClusterKey clusterKey)
 {
     var endPoints = clusterKey.Servers.Select(s => (EndPoint)new DnsEndPoint(s.Host, s.Port));
     return settings.With(
         connectionMode: clusterKey.ConnectionMode.ToCore(),
         endPoints: Optional.Enumerable(endPoints),
         replicaSetName: clusterKey.ReplicaSetName,
         maxServerSelectionWaitQueueSize: clusterKey.WaitQueueSize,
         serverSelectionTimeout: clusterKey.ServerSelectionTimeout,
         postServerSelector: new LatencyLimitingServerSelector(clusterKey.LocalThreshold));
 }
        // constructors
        public MultiServerCluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IClusterListener listener)
            : base(settings, serverFactory, listener)
        {
            Ensure.IsGreaterThanZero(settings.EndPoints.Count, "settings.EndPoints.Count");

            _monitorServersCancellationTokenSource = new CancellationTokenSource();
            _serverDescriptionChangedQueue = new AsyncQueue<ServerDescriptionChangedEventArgs>();
            _servers = new List<IClusterableServer>();
            _state = new InterlockedInt32(State.Initial);
            _replicaSetName = settings.ReplicaSetName;
        }
Exemple #12
0
        // constructors
        protected Cluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IClusterListener listener)
        {
            _settings = Ensure.IsNotNull(settings, "settings");
            _serverFactory = Ensure.IsNotNull(serverFactory, "serverFactory");
            _listener = listener;
            _state = new InterlockedInt32(State.Initial);

            _clusterId = new ClusterId();
            _description = ClusterDescription.CreateInitial(_clusterId, _settings.ConnectionMode.ToClusterType());
            _descriptionChangedTaskCompletionSource = new TaskCompletionSource<bool>();
        }
        public void constructor_with_endPoints_should_initialize_instance()
        {
            var endPoints = new[] { new DnsEndPoint("remotehost", 27123) };

            var subject = new ClusterSettings(endPoints: endPoints);

            subject.ConnectionMode.Should().Be(__defaults.ConnectionMode);
            subject.EndPoints.Should().EqualUsing(endPoints, EndPointHelper.EndPointEqualityComparer);
            subject.MaxServerSelectionWaitQueueSize.Should().Be(__defaults.MaxServerSelectionWaitQueueSize);
            subject.ReplicaSetName.Should().Be(__defaults.ReplicaSetName);
            subject.ServerSelectionTimeout.Should().Be(__defaults.ServerSelectionTimeout);
        }
        public void constructor_with_connectionMode_should_initialize_instance()
        {
            var connectionMode = ClusterConnectionMode.ReplicaSet;

            var subject = new ClusterSettings(connectionMode: connectionMode);

            subject.ConnectionMode.Should().Be(connectionMode);
            subject.EndPoints.Should().EqualUsing(__defaults.EndPoints, EndPointHelper.EndPointEqualityComparer);
            subject.MaxServerSelectionWaitQueueSize.Should().Be(__defaults.MaxServerSelectionWaitQueueSize);
            subject.ReplicaSetName.Should().Be(__defaults.ReplicaSetName);
            subject.ServerSelectionTimeout.Should().Be(__defaults.ServerSelectionTimeout);
        }
        public void Description_should_be_correct_after_initialization()
        {
            _settings = _settings.WithEndPoints(new [] { _firstEndPoint });

            var subject = CreateSubject();
            subject.Initialize();

            var description = subject.Description;
            description.State.Should().Be(ClusterState.Disconnected);
            description.Type.Should().Be(ClusterType.Unknown);
            description.Servers.Should().BeEquivalentTo(GetDescriptions(_firstEndPoint));
        }
Exemple #16
0
 public ClusterTests()
 {
     _settings = new ClusterSettings(serverSelectionTimeout: TimeSpan.FromSeconds(2),
         postServerSelector: new LatencyLimitingServerSelector(TimeSpan.FromMinutes(2)));
     _mockServerFactory = new Mock<IClusterableServerFactory>();
     _mockServerFactory.Setup(f => f.CreateServer(It.IsAny<ClusterId>(), It.IsAny<EndPoint>()))
         .Returns((ClusterId clusterId, EndPoint endPoint) =>
         {
             var mockServer = new Mock<IClusterableServer>();
             mockServer.SetupGet(s => s.EndPoint).Returns(endPoint);
             return mockServer.Object;
         });
     _capturedEvents = new EventCapturer();
 }
        public void Description_should_not_contain_any_servers_if_the_provided_server_is_not_of_the_required_type(ClusterConnectionMode connectionMode, ServerType serverType)
        {
            var server = Substitute.For<IClusterableServer>();
            _serverFactory.CreateServer(null, null).ReturnsForAnyArgs(server);

            _settings = _settings.WithConnectionMode(connectionMode);

            var subject = CreateSubject();
            subject.Initialize();

            var connected = ServerDescriptionHelper.Connected(subject.Description.ClusterId, serverType: serverType);

            server.DescriptionChanged += Raise.EventWith(new object(), new ServerDescriptionChangedEventArgs(connected, connected));

            subject.Description.Servers.Should().BeEmpty();
        }
        // 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);
        }
        // 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);
        }
        public void Description_should_be_correct_after_initialization()
        {
            _settings = _settings.With(endPoints: new[] { _firstEndPoint });

            var subject = CreateSubject();
            subject.Initialize();

            var description = subject.Description;
            description.State.Should().Be(ClusterState.Disconnected);
            description.Type.Should().Be(ClusterType.Unknown);
            description.Servers.Should().BeEquivalentTo(GetDescriptions(_firstEndPoint));

            _capturedEvents.Next().Should().BeOfType<ClusterOpeningEvent>();
            _capturedEvents.Next().Should().BeOfType<ClusterAddingServerEvent>();
            _capturedEvents.Next().Should().BeOfType<ClusterAddedServerEvent>();
            _capturedEvents.Next().Should().BeOfType<ClusterDescriptionChangedEvent>();
            _capturedEvents.Next().Should().BeOfType<ClusterOpenedEvent>();
            _capturedEvents.Any().Should().BeFalse();
        }
        public void With_connectionMode_should_return_expected_result()
        {
#pragma warning disable CS0618 // Type or member is obsolete
            var oldConnectionMode = ClusterConnectionMode.Automatic;
            var newConnectionMode = ClusterConnectionMode.ReplicaSet;
            var subject           = new ClusterSettings(connectionModeSwitch: ConnectionModeSwitch.UseConnectionMode, connectionMode: oldConnectionMode);
#pragma warning restore CS0618 // Type or member is obsolete

            var result = subject.With(connectionMode: newConnectionMode);

#pragma warning disable CS0618 // Type or member is obsolete
            result.ConnectionMode.Should().Be(newConnectionMode);
#pragma warning restore CS0618 // Type or member is obsolete
            result.EndPoints.Should().EqualUsing(subject.EndPoints, EndPointHelper.EndPointEqualityComparer);
            result.LoadBalanced.Should().BeFalse();
            result.LocalThreshold.Should().Be(subject.LocalThreshold);
            result.MaxServerSelectionWaitQueueSize.Should().Be(subject.MaxServerSelectionWaitQueueSize);
            result.ReplicaSetName.Should().Be(subject.ReplicaSetName);
            result.Scheme.Should().Be(subject.Scheme);
            result.ServerSelectionTimeout.Should().Be(subject.ServerSelectionTimeout);
        }
 public void Setup()
 {
     _settings = new ClusterSettings();
     _serverFactory = new MockClusterableServerFactory();
     _capturedEvents = new EventCapturer();
 }
        public void Description_should_regain_a_server_if_the_provided_server_is_rebooted_to_its_expected_type()
        {
            _settings = _settings.With(connectionMode: ClusterConnectionMode.Standalone);

            var subject = CreateSubject();
            subject.Initialize();
            _capturedEvents.Clear();

            PublishDescription(_endPoint, ServerType.ReplicaSetGhost);
            PublishDescription(_endPoint, ServerType.Standalone);

            subject.Description.Servers.Count.Should().Be(1);

            _capturedEvents.Next().Should().BeOfType<ClusterDescriptionChangedEvent>();
            _capturedEvents.Next().Should().BeOfType<ClusterDescriptionChangedEvent>();
            _capturedEvents.Any().Should().BeFalse();
        }
 // constructors
 public Builder(ClusterSettings other)
 {
     _connectionMode = other._connectionMode;
     _endPoints      = other._endPoints;
     _replicaSetName = other._replicaSetName;
 }
        public void Constructor_with_valid_srvMaxHosts_should_initialize_instance([Values(0, 42)] int srvMaxHosts)
        {
            var subject = new ClusterSettings(srvMaxHosts: srvMaxHosts);

            subject.SrvMaxHosts.Should().Be(srvMaxHosts);
        }
 private MultiServerCluster CreateMultiServerCluster(ClusterSettings settings)
 {
     var shardedCluster = new MultiServerCluster(settings, _serverFactory, _eventSubscriber);
     shardedCluster.Initialize();
     return shardedCluster;
 }
        public void Description_should_not_contain_any_servers_if_the_provided_server_is_not_of_the_required_type(ClusterConnectionMode connectionMode, ServerType serverType)
        {
            _settings = _settings.With(connectionMode: connectionMode);

            var subject = CreateSubject();
            subject.Initialize();
            _capturedEvents.Clear();

            PublishDescription(_endPoint, serverType);

            subject.Description.Servers.Should().BeEmpty();
            _capturedEvents.Next().Should().BeOfType<ClusterDescriptionChangedEvent>();
            _capturedEvents.Any().Should().BeFalse();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ClusterOpenedEvent"/> struct.
 /// </summary>
 /// <param name="clusterId">The cluster identifier.</param>
 /// <param name="clusterSettings">The cluster settings.</param>
 /// <param name="duration">The duration of time it took to open the cluster.</param>
 public ClusterOpenedEvent(ClusterId clusterId, ClusterSettings clusterSettings, TimeSpan duration)
 {
     _clusterId = clusterId;
     _clusterSettings = clusterSettings;
     _duration = duration;
 }
        public async Task SelectServerAsync_should_apply_both_pre_and_post_server_selectors()
        {
            _serverFactory.CreateServer(null, null).ReturnsForAnyArgs(ci =>
            {
                var endPoint = ci.Arg<EndPoint>();
                var server = Substitute.For<IClusterableServer>();
                server.EndPoint.Returns(endPoint);
                return server;
            });

            var preSelector = new DelegateServerSelector((cd, sds) => sds.Where(x => ((DnsEndPoint)x.EndPoint).Port != 27017));
            var middleSelector = new DelegateServerSelector((cd, sds) => sds.Where(x => ((DnsEndPoint)x.EndPoint).Port != 27018));
            var postSelector = new DelegateServerSelector((cd, sds) => sds.Where(x => ((DnsEndPoint)x.EndPoint).Port != 27019));

            var settings = new ClusterSettings(
                preServerSelector: preSelector,
                postServerSelector: postSelector);

            var subject = new StubCluster(settings, _serverFactory, _capturedEvents);
            subject.Initialize();

            subject.SetServerDescriptions(
                ServerDescriptionHelper.Connected(subject.Description.ClusterId, new DnsEndPoint("localhost", 27017)),
                ServerDescriptionHelper.Connected(subject.Description.ClusterId, new DnsEndPoint("localhost", 27018)),
                ServerDescriptionHelper.Connected(subject.Description.ClusterId, new DnsEndPoint("localhost", 27019)),
                ServerDescriptionHelper.Connected(subject.Description.ClusterId, new DnsEndPoint("localhost", 27020)));
            _capturedEvents.Clear();

            var selected = await subject.SelectServerAsync(middleSelector, CancellationToken.None);
            ((DnsEndPoint)selected.EndPoint).Port.Should().Be(27020);
            _capturedEvents.Next().Should().BeOfType<ClusterSelectingServerEvent>();
            _capturedEvents.Next().Should().BeOfType<ClusterSelectedServerEvent>();
            _capturedEvents.Any().Should().BeFalse();
        }
 // constructors
 public ClusterFactory(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
 {
     _settings = Ensure.IsNotNull(settings, "settings");
     _serverFactory = Ensure.IsNotNull(serverFactory, "serverFactory");
     _eventSubscriber = Ensure.IsNotNull(eventSubscriber, "eventSubscriber");
 }
        private StubCluster CreateSubject(ClusterConnectionMode connectionMode = ClusterConnectionMode.Automatic)
        {
            _settings = _settings.With(connectionMode: connectionMode);

            return new StubCluster(_settings, _serverFactory, _capturedEvents);
        }
 private SingleServerCluster CreateSingleServerCluster(ClusterSettings settings)
 {
     var standaloneCluster = new SingleServerCluster(settings, _serverFactory, _eventSubscriber);
     standaloneCluster.Initialize();
     return standaloneCluster;
 }
            public StubCluster(ClusterSettings settings, IClusterableServerFactory serverFactory, IEventSubscriber eventSubscriber)
                : base(settings, serverFactory, eventSubscriber)
            {


            }