Exemple #1
0
        public ServerTests()
        {
            _clusterId = new ClusterId();
            _endPoint  = new DnsEndPoint("localhost", 27017);

            _clusterClock = new Mock <IClusterClock>().Object;
#pragma warning disable CS0618 // Type or member is obsolete
            _clusterConnectionMode = ClusterConnectionMode.Standalone;
            _connectionModeSwitch  = ConnectionModeSwitch.UseConnectionMode;
#pragma warning restore CS0618 // Type or member is obsolete
            _directConnection   = null;
            _mockConnectionPool = new Mock <IConnectionPool>();
            _mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny <CancellationToken>())).Returns(new Mock <IConnectionHandle>().Object);
            _mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny <CancellationToken>())).Returns(Task.FromResult(new Mock <IConnectionHandle>().Object));
            _mockConnectionPoolFactory = new Mock <IConnectionPoolFactory>();
            _mockConnectionPoolFactory
            .Setup(f => f.CreateConnectionPool(It.IsAny <ServerId>(), _endPoint))
            .Returns(_mockConnectionPool.Object);

            _mockServerMonitor        = new Mock <IServerMonitor>();
            _mockServerMonitorFactory = new Mock <IServerMonitorFactory>();
            _mockServerMonitorFactory.Setup(f => f.Create(It.IsAny <ServerId>(), _endPoint)).Returns(_mockServerMonitor.Object);

            _capturedEvents = new EventCapturer();
            _serverApi      = new ServerApi(ServerApiVersion.V1, true, true);
            _settings       = new ServerSettings(heartbeatInterval: Timeout.InfiniteTimeSpan);

            _subject      = new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _capturedEvents, _serverApi);
            _connectionId = new ConnectionId(_subject.ServerId);
        }
        public DefaultServer(
            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,
            IServerMonitorFactory monitorFactory,
            IEventSubscriber eventSubscriber,
            ServerApi serverApi)
            : base(
                clusterId,
                clusterClock,
                clusterConnectionMode,
                connectionModeSwitch,
                directConnection,
                settings,
                endPoint,
                connectionPoolFactory,
                eventSubscriber,
                serverApi)
        {
            _monitor         = Ensure.IsNotNull(monitorFactory, nameof(monitorFactory)).Create(ServerId, endPoint);
            _baseDescription = _currentDescription = new ServerDescription(ServerId, endPoint, reasonChanged: "ServerInitialDescription", heartbeatInterval: settings.HeartbeatInterval);
        }
Exemple #3
0
        public void Constructor_should_initialize_instance(ConnectionModeSwitch connectionModeSwitch, ClusterConnectionMode connectionMode, bool?directConnection)
        {
            var dnsMonitorException = new Exception();
            var subject             = new ClusterDescription(
                __clusterId,
                connectionMode,
                connectionModeSwitch,
                directConnection,
                dnsMonitorException,
                ClusterType.ReplicaSet,
                new[] { __serverDescription1, __serverDescription2 });

            subject.ClusterId.Should().Be(__clusterId);
            subject.ConnectionModeSwitch.Should().Be(connectionModeSwitch);
            switch (connectionModeSwitch)
            {
            case ConnectionModeSwitch.UseConnectionMode: subject.ConnectionMode.Should().Be(connectionMode); break;

            case ConnectionModeSwitch.UseDirectConnection: subject.DirectConnection.Should().Be(directConnection); break;
            }
            subject.DnsMonitorException.Should().BeSameAs(dnsMonitorException);
            subject.LogicalSessionTimeout.Should().NotHaveValue();
            subject.Servers.Should().ContainInOrder(new[] { __serverDescription1, __serverDescription2 });
            subject.State.Should().Be(ClusterState.Disconnected);
            subject.Type.Should().Be(ClusterType.ReplicaSet);
        }
Exemple #4
0
        // constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="ClusterSettings"/> class.
        /// </summary>
        /// <param name="connectionMode">The connection mode.</param>
        /// <param name="connectionModeSwitch">The connection mode switch.</param>
        /// <param name="directConnection">The directConnection.</param>
        /// <param name="endPoints">The end points.</param>
        /// <param name="kmsProviders">The kms providers.</param>
        /// <param name="localThreshold">The local threshold.</param>
        /// <param name="maxServerSelectionWaitQueueSize">Maximum size of the server selection wait queue.</param>
        /// <param name="replicaSetName">Name of the replica set.</param>
        /// <param name="serverSelectionTimeout">The server selection timeout.</param>
        /// <param name="preServerSelector">The pre server selector.</param>
        /// <param name="postServerSelector">The post server selector.</param>
        /// <param name="schemaMap">The schema map.</param>
        /// <param name="scheme">The connection string scheme.</param>
        public ClusterSettings(
#pragma warning disable CS0618 // Type or member is obsolete
            Optional <ClusterConnectionMode> connectionMode      = default(Optional <ClusterConnectionMode>),
            Optional <ConnectionModeSwitch> connectionModeSwitch = default,
#pragma warning restore CS0618 // Type or member is obsolete
            Optional <bool?> directConnection            = default,
            Optional <IEnumerable <EndPoint> > endPoints = default(Optional <IEnumerable <EndPoint> >),
            Optional <IReadOnlyDictionary <string, IReadOnlyDictionary <string, object> > > kmsProviders = default(Optional <IReadOnlyDictionary <string, IReadOnlyDictionary <string, object> > >),
            Optional <TimeSpan> localThreshold             = default,
            Optional <int> maxServerSelectionWaitQueueSize = default(Optional <int>),
            Optional <string> replicaSetName              = default(Optional <string>),
            Optional <TimeSpan> serverSelectionTimeout    = default(Optional <TimeSpan>),
            Optional <IServerSelector> preServerSelector  = default(Optional <IServerSelector>),
            Optional <IServerSelector> postServerSelector = default(Optional <IServerSelector>),
            Optional <IReadOnlyDictionary <string, BsonDocument> > schemaMap = default(Optional <IReadOnlyDictionary <string, BsonDocument> >),
            Optional <ConnectionStringScheme> scheme = default(Optional <ConnectionStringScheme>))
        {
#pragma warning disable CS0618 // Type or member is obsolete
            _connectionMode       = connectionMode.WithDefault(ClusterConnectionMode.Automatic);
            _connectionModeSwitch = connectionModeSwitch.WithDefault(ConnectionModeSwitch.NotSet);
#pragma warning restore CS0618 // Type or member is obsolete
            _directConnection = directConnection.WithDefault(null);
            _endPoints        = Ensure.IsNotNull(endPoints.WithDefault(__defaultEndPoints), "endPoints").ToList();
            _kmsProviders     = kmsProviders.WithDefault(null);
            _localThreshold   = Ensure.IsGreaterThanOrEqualToZero(localThreshold.WithDefault(TimeSpan.FromMilliseconds(15)), "localThreshold");
            _maxServerSelectionWaitQueueSize = Ensure.IsGreaterThanOrEqualToZero(maxServerSelectionWaitQueueSize.WithDefault(500), "maxServerSelectionWaitQueueSize");
            _replicaSetName         = replicaSetName.WithDefault(null);
            _serverSelectionTimeout = Ensure.IsGreaterThanOrEqualToZero(serverSelectionTimeout.WithDefault(TimeSpan.FromSeconds(30)), "serverSelectionTimeout");
            _preServerSelector      = preServerSelector.WithDefault(null);
            _postServerSelector     = postServerSelector.WithDefault(null);
            _scheme    = scheme.WithDefault(ConnectionStringScheme.MongoDB);
            _schemaMap = schemaMap.WithDefault(null);

            ClusterConnectionModeHelper.EnsureConnectionModeValuesAreValid(_connectionMode, _connectionModeSwitch, _directConnection);
        }
Exemple #5
0
        public void TestThatNotExpectedPropertyCallThrow(ConnectionModeSwitch connectionModeSwitch, string property, bool shouldFail)
        {
            var connectionString = $"mongodb://localhost";
            var url = new MongoUrl(connectionString);

            url._connectionModeSwitch(connectionModeSwitch);
            Exception exception;

            switch (property)
            {
            case "connect": exception = Record.Exception(() => url.ConnectionMode); break;

            case "directConnection": exception = Record.Exception(() => url.DirectConnection); break;

            default: throw new Exception($"Unexpected property {property}.");
            }

            if (shouldFail)
            {
                exception.Should().BeOfType <InvalidOperationException>();
            }
            else
            {
                exception.Should().BeNull();
            }
        }
        // constructors
        /// <summary>
        /// Creates a new instance of MongoUrlBuilder.
        /// </summary>
        public MongoUrlBuilder()
        {
            _allowInsecureTls                  = false;
            _applicationName                   = null;
            _authenticationMechanism           = MongoDefaults.AuthenticationMechanism;
            _authenticationMechanismProperties = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            _authenticationSource              = null;
            _compressors    = new CompressorConfiguration[0];
            _connectionMode = ConnectionMode.Automatic;
#pragma warning disable CS0618 // Type or member is obsolete
            _connectionModeSwitch = ConnectionModeSwitch.NotSet;
#pragma warning restore CS0618 // Type or member is obsolete
            _connectTimeout   = MongoDefaults.ConnectTimeout;
            _databaseName     = null;
            _directConnection = null;
            _fsync            = null;
#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                _guidRepresentation = MongoDefaults.GuidRepresentation;
            }
#pragma warning restore 618
            _heartbeatInterval = ServerSettings.DefaultHeartbeatInterval;
            _heartbeatTimeout  = ServerSettings.DefaultHeartbeatTimeout;
            _ipv6                   = false;
            _journal                = null;
            _loadBalanced           = false;
            _localThreshold         = MongoDefaults.LocalThreshold;
            _maxConnecting          = MongoInternalDefaults.ConnectionPool.MaxConnecting;
            _maxConnectionIdleTime  = MongoDefaults.MaxConnectionIdleTime;
            _maxConnectionLifeTime  = MongoDefaults.MaxConnectionLifeTime;
            _maxConnectionPoolSize  = MongoDefaults.MaxConnectionPoolSize;
            _minConnectionPoolSize  = MongoDefaults.MinConnectionPoolSize;
            _password               = null;
            _readConcernLevel       = null;
            _readPreference         = null;
            _replicaSetName         = null;
            _retryReads             = null;
            _retryWrites            = null;
            _scheme                 = ConnectionStringScheme.MongoDB;
            _servers                = new[] { new MongoServerAddress("localhost", 27017) };
            _serverSelectionTimeout = MongoDefaults.ServerSelectionTimeout;
            _socketTimeout          = MongoDefaults.SocketTimeout;
            _srvMaxHosts            = null;
            _username               = null;
            _useTls                 = false;
            _w = null;
#pragma warning disable 618
            _waitQueueMultiple = MongoDefaults.WaitQueueMultiple;
            _waitQueueSize     = MongoDefaults.WaitQueueSize;
#pragma warning restore 618
            _waitQueueTimeout = MongoDefaults.WaitQueueTimeout;
            _wTimeout         = null;
        }
Exemple #7
0
        // constructors
#pragma warning disable CS0618 // Type or member is obsolete
        public ServerFactory(ClusterConnectionMode clusterConnectionMode, ConnectionModeSwitch connectionModeSwitch, bool?directConnection, ServerSettings settings, IConnectionPoolFactory connectionPoolFactory, IServerMonitorFactory serverMonitoryFactory, IEventSubscriber eventSubscriber)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            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));
        }
Exemple #8
0
        public void Constructor_should_throw_when_ConnectionModeSwitch_is_invalid(ConnectionModeSwitch connectionModeSwitch, bool shouldThrow)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            _settings = _settings.With(connectionModeSwitch: connectionModeSwitch);

            var exception = Record.Exception(() => new LoadBalancedCluster(_settings, _mockServerFactory, _capturedEvents));

            if (shouldThrow)
            {
                exception.Should().BeOfType <ArgumentException>();
            }
            else
            {
                exception.Should().BeNull();
            }
        }
        // constructors
        /// <summary>
        /// Creates a new instance of MongoClientSettings. Usually you would use a connection string instead.
        /// </summary>
        public MongoClientSettings()
        {
            _allowInsecureTls = false;
            _applicationName = null;
            _autoEncryptionOptions = null;
            _compressors = new CompressorConfiguration[0];
#pragma warning disable CS0618 // Type or member is obsolete
            _connectionMode = ConnectionMode.Automatic;
            _connectionModeSwitch = ConnectionModeSwitch.NotSet;
#pragma warning restore CS0618 // Type or member is obsolete
            _connectTimeout = MongoDefaults.ConnectTimeout;
            _credentials = new MongoCredentialStore(new MongoCredential[0]);
            _directConnection = null;
#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                _guidRepresentation = MongoDefaults.GuidRepresentation;
            }
#pragma warning restore 618
            _heartbeatInterval = ServerSettings.DefaultHeartbeatInterval;
            _heartbeatTimeout = ServerSettings.DefaultHeartbeatTimeout;
            _ipv6 = false;
            _localThreshold = MongoDefaults.LocalThreshold;
            _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime;
            _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime;
            _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize;
            _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize;
            _readConcern = ReadConcern.Default;
            _readEncoding = null;
            _readPreference = ReadPreference.Primary;
            _replicaSetName = null;
            _retryReads = true;
            _retryWrites = true;
            _scheme = ConnectionStringScheme.MongoDB;
            _sdamLogFilename = null;
            _servers = new List<MongoServerAddress> { new MongoServerAddress("localhost") };
            _serverSelectionTimeout = MongoDefaults.ServerSelectionTimeout;
            _socketTimeout = MongoDefaults.SocketTimeout;
            _sslSettings = null;
            _useTls = false;
#pragma warning disable 618
            _waitQueueSize = MongoDefaults.ComputedWaitQueueSize;
#pragma warning restore 618
            _waitQueueTimeout = MongoDefaults.WaitQueueTimeout;
            _writeConcern = WriteConcern.Acknowledged;
            _writeEncoding = null;
        }
Exemple #10
0
        public void CreateInitial_should_return_initial_description(ConnectionModeSwitch connectionModeSwitch, ClusterConnectionMode connectionMode, bool?directConnection)
        {
            var subject = ClusterDescription.CreateInitial(__clusterId, connectionMode, connectionModeSwitch, directConnection);

            subject.ClusterId.Should().Be(__clusterId);
            subject.ConnectionModeSwitch.Should().Be(connectionModeSwitch);
            switch (connectionModeSwitch)
            {
            case ConnectionModeSwitch.UseConnectionMode: subject.ConnectionMode.Should().Be(connectionMode); break;

            case ConnectionModeSwitch.UseDirectConnection: subject.DirectConnection.Should().Be(directConnection); break;
            }
            subject.DnsMonitorException.Should().BeNull();
            subject.LogicalSessionTimeout.Should().NotHaveValue();
            subject.Servers.Should().BeEmpty();
            subject.State.Should().Be(ClusterState.Disconnected);
            subject.Type.Should().Be(ClusterType.Unknown);
        }
        public ServerFactoryTests()
        {
            _clusterId = new ClusterId();
#pragma warning disable CS0618 // Type or member is obsolete
            _clusterConnectionMode = ClusterConnectionMode.Standalone;
            _connectionModeSwitch  = ConnectionModeSwitch.UseConnectionMode;
#pragma warning restore CS0618 // Type or member is obsolete
            _connectionPoolFactory = new Mock <IConnectionPoolFactory>().Object;
            _directConnection      = null;
            _endPoint = new DnsEndPoint("localhost", 27017);
            var mockServerMonitor = new Mock <IServerMonitor>();
            mockServerMonitor.Setup(m => m.Description).Returns(new ServerDescription(new ServerId(_clusterId, _endPoint), _endPoint));
            var mockServerMonitorFactory = new Mock <IServerMonitorFactory>();
            mockServerMonitorFactory.Setup(f => f.Create(It.IsAny <ServerId>(), _endPoint)).Returns(mockServerMonitor.Object);
            _serverMonitorFactory = mockServerMonitorFactory.Object;
            _eventSubscriber      = new Mock <IEventSubscriber>().Object;
            _settings             = new ServerSettings();
        }
Exemple #12
0
#pragma warning disable CS0618 // Type or member is obsolete
        internal ClusterDescription(
            ClusterId clusterId,
            ClusterConnectionMode connectionMode,
            ConnectionModeSwitch connectionModeSwitch,
            bool?directConnection,
            Exception dnsMonitorException,
            ClusterType type,
            IEnumerable <ServerDescription> servers)
        {
            ClusterConnectionModeHelper.EnsureConnectionModeValuesAreValid(connectionMode, connectionModeSwitch, directConnection);

            _clusterId            = Ensure.IsNotNull(clusterId, nameof(clusterId));
            _connectionMode       = connectionMode;
            _connectionModeSwitch = connectionModeSwitch;
            _directConnection     = directConnection;
            _dnsMonitorException  = dnsMonitorException; // can be null
            _type    = type;
            _servers = (servers ?? new ServerDescription[0]).OrderBy(n => n.EndPoint, new ToStringComparer <EndPoint>()).ToList();
            _logicalSessionTimeout = CalculateLogicalSessionTimeout(this, _servers);
        }
Exemple #13
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);
        }
Exemple #14
0
        // constructors
        /// <summary>
        /// Creates a new instance of MongoUrl.
        /// </summary>
        /// <param name="url">The URL containing the settings.</param>
        public MongoUrl(string url)
        {
            _originalUrl = url;

            var builder = new MongoUrlBuilder(url); // parses url
            _allowInsecureTls = builder.AllowInsecureTls;
            _applicationName = builder.ApplicationName;
            _authenticationMechanism = builder.AuthenticationMechanism;
            _authenticationMechanismProperties = builder.AuthenticationMechanismProperties;
            _authenticationSource = builder.AuthenticationSource;
            _compressors = builder.Compressors;
#pragma warning disable CS0618 // Type or member is obsolete
            if (builder.ConnectionModeSwitch == ConnectionModeSwitch.UseConnectionMode)
            {
                _connectionMode = builder.ConnectionMode;
            }
            _connectionModeSwitch = builder.ConnectionModeSwitch;
#pragma warning restore CS0618 // Type or member is obsolete
            _connectTimeout = builder.ConnectTimeout;
            _databaseName = builder.DatabaseName;
#pragma warning disable CS0618 // Type or member is obsolete
            if (builder.ConnectionModeSwitch == ConnectionModeSwitch.UseDirectConnection)
            {
                _directConnection = builder.DirectConnection;
            }
#pragma warning restore CS0618 // Type or member is obsolete
            _fsync = builder.FSync;
#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                _guidRepresentation = builder.GuidRepresentation;
            }
#pragma warning restore 618
            _heartbeatInterval = builder.HeartbeatInterval;
            _heartbeatTimeout = builder.HeartbeatTimeout;
            _ipv6 = builder.IPv6;
            _isResolved = builder.Scheme != ConnectionStringScheme.MongoDBPlusSrv;
            _journal = builder.Journal;
            _localThreshold = builder.LocalThreshold;
            _maxConnectionIdleTime = builder.MaxConnectionIdleTime;
            _maxConnectionLifeTime = builder.MaxConnectionLifeTime;
            _maxConnectionPoolSize = builder.MaxConnectionPoolSize;
            _minConnectionPoolSize = builder.MinConnectionPoolSize;
            _password = builder.Password;
            _readConcernLevel = builder.ReadConcernLevel;
            _readPreference = builder.ReadPreference;
            _replicaSetName = builder.ReplicaSetName;
            _retryReads = builder.RetryReads;
            _retryWrites = builder.RetryWrites;
            _scheme = builder.Scheme;
            _servers = builder.Servers;
            _serverSelectionTimeout = builder.ServerSelectionTimeout;
            _socketTimeout = builder.SocketTimeout;
            _tlsDisableCertificateRevocationCheck = builder.TlsDisableCertificateRevocationCheck;
            _username = builder.Username;
            _useTls = builder.UseTls;
            _w = builder.W;
#pragma warning disable 618
            _waitQueueMultiple = builder.WaitQueueMultiple;
            _waitQueueSize = builder.WaitQueueSize;
#pragma warning restore 618
            _waitQueueTimeout = builder.WaitQueueTimeout;
            _wTimeout = builder.WTimeout;
            _url = builder.ToString(); // keep canonical form
        }
Exemple #15
0
#pragma warning disable CS0618 // Type or member is obsolete
        public static void EnsureConnectionModeValuesAreValid(ConnectionMode connectionMode, ConnectionModeSwitch connectionModeSwitch, bool?directConnection)
        {
            switch (connectionModeSwitch)
            {
            case ConnectionModeSwitch.NotSet:
                if (connectionMode != default)
                {
                    throw new ArgumentException($"When connectionModeSwitch is NotSet connectionMode must have the default value.", nameof(connectionMode));
                }
                if (directConnection != default)
                {
                    throw new ArgumentException($"When connectionModeSwitch is NotSet directConnection must have the default value.", nameof(directConnection));
                }
                break;

            case ConnectionModeSwitch.UseConnectionMode:
                if (directConnection != default)
                {
                    throw new ArgumentException($"When connectionModeSwitch is UseConnectionMode directConnection must have the default value.", nameof(directConnection));
                }
                break;

            case ConnectionModeSwitch.UseDirectConnection:
                if (connectionMode != default)
                {
                    throw new ArgumentException($"When connectionModeSwitch is UseDirectConnection connectionMode must have the default value.", nameof(connectionMode));
                }
                break;

            default:
                throw new ArgumentException($"Invalid connectionModeSwitch: {connectionModeSwitch}.", nameof(connectionModeSwitch));
            }
        }
Exemple #16
0
        // internal static methods
#pragma warning disable CS0618 // Type or member is obsolete
        internal static ClusterDescription CreateInitial(ClusterId clusterId, ClusterConnectionMode connectionMode, ConnectionModeSwitch connectionModeSwitch, bool?directConnection)
        {
            return(new ClusterDescription(
                       clusterId,
                       connectionMode,
                       connectionModeSwitch,
                       directConnection,
                       dnsMonitorException: null,
                       type: ClusterType.Unknown,
                       servers: Enumerable.Empty <ServerDescription>()));
        }
        // constructors
        public ClusterKey(
            bool allowInsecureTls,
            string applicationName,
            Action <ClusterBuilder> clusterConfigurator,
            IReadOnlyList <CompressorConfiguration> compressors,
#pragma warning disable CS0618 // Type or member is obsolete
            ConnectionMode connectionMode,
            ConnectionModeSwitch connectionModeSwitch,
#pragma warning restore CS0618 // Type or member is obsolete
            TimeSpan connectTimeout,
            IReadOnlyList <MongoCredential> credentials,
            bool?directConnection,
            TimeSpan heartbeatInterval,
            TimeSpan heartbeatTimeout,
            bool ipv6,
            IReadOnlyDictionary <string, IReadOnlyDictionary <string, object> > kmsProviders,
            TimeSpan localThreshold,
            TimeSpan maxConnectionIdleTime,
            TimeSpan maxConnectionLifeTime,
            int maxConnectionPoolSize,
            int minConnectionPoolSize,
            int receiveBufferSize,
            string replicaSetName,
            IReadOnlyDictionary <string, BsonDocument> schemaMap,
            ConnectionStringScheme scheme,
            string sdamLogFilename,
            int sendBufferSize,
            ServerApi serverApi,
            IReadOnlyList <MongoServerAddress> servers,
            TimeSpan serverSelectionTimeout,
            TimeSpan socketTimeout,
            SslSettings sslSettings,
            bool useTls,
            int waitQueueSize,
            TimeSpan waitQueueTimeout)
        {
            ConnectionModeHelper.EnsureConnectionModeValuesAreValid(connectionMode, connectionModeSwitch, directConnection);

            _allowInsecureTls     = allowInsecureTls;
            _applicationName      = applicationName;
            _clusterConfigurator  = clusterConfigurator;
            _compressors          = compressors;
            _connectionMode       = connectionMode;
            _connectionModeSwitch = connectionModeSwitch;
            _connectTimeout       = connectTimeout;
            _credentials          = credentials;
            _directConnection     = directConnection;
            _heartbeatInterval    = heartbeatInterval;
            _heartbeatTimeout     = heartbeatTimeout;
            _ipv6                   = ipv6;
            _kmsProviders           = kmsProviders;
            _localThreshold         = localThreshold;
            _maxConnectionIdleTime  = maxConnectionIdleTime;
            _maxConnectionLifeTime  = maxConnectionLifeTime;
            _maxConnectionPoolSize  = maxConnectionPoolSize;
            _minConnectionPoolSize  = minConnectionPoolSize;
            _receiveBufferSize      = receiveBufferSize;
            _replicaSetName         = replicaSetName;
            _schemaMap              = schemaMap;
            _scheme                 = scheme;
            _sdamLogFilename        = sdamLogFilename;
            _sendBufferSize         = sendBufferSize;
            _serverApi              = serverApi;
            _servers                = servers;
            _serverSelectionTimeout = serverSelectionTimeout;
            _socketTimeout          = socketTimeout;
            _sslSettings            = sslSettings;
            _useTls                 = useTls;
            _waitQueueSize          = waitQueueSize;
            _waitQueueTimeout       = waitQueueTimeout;

            _hashCode = CalculateHashCode();
        }
Exemple #18
0
        // private methods
#pragma warning disable CS0618 // Type or member is obsolete
        private StubCluster CreateSubject(ClusterConnectionMode connectionMode = ClusterConnectionMode.Automatic, ConnectionModeSwitch connectionModeSwitch = ConnectionModeSwitch.UseConnectionMode, TimeSpan?serverSelectionTimeout = null)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            _settings = _settings.With(connectionMode: connectionMode, connectionModeSwitch: connectionModeSwitch);
            if (serverSelectionTimeout != null)
            {
                _settings = _settings.With(serverSelectionTimeout: serverSelectionTimeout.Value);
            }

            return(new StubCluster(_settings, _mockServerFactory.Object, _capturedEvents));
        }
        internal ClusterKey CreateSubjectWith(
            Dictionary <string, IReadOnlyDictionary <string, object> > kmsProvidersValue = null,
            Dictionary <string, BsonDocument> schemaMapValue = null,
#pragma warning disable CS0618 // Type or member is obsolete
            ConnectionModeSwitch connectionModeSwitch = ConnectionModeSwitch.UseConnectionMode)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            var allowInsecureTls    = true;
            var applicationName     = "app1";
            var clusterConfigurator = new Action <ClusterBuilder>(b => { });
            var compressors         = new CompressorConfiguration[0];

#pragma warning disable CS0618 // Type or member is obsolete
            var connectionMode = connectionModeSwitch != ConnectionModeSwitch.UseConnectionMode ? ConnectionMode.Automatic : ConnectionMode.Direct;
#pragma warning restore CS0618 // Type or member is obsolete
            var connectTimeout = TimeSpan.FromSeconds(1);
#pragma warning disable 618
            var credentials = new List <MongoCredential> {
                MongoCredential.CreateMongoCRCredential("source", "username", "password")
            };
#pragma warning restore 618
            bool?directConnection  = null;
            var  heartbeatInterval = TimeSpan.FromSeconds(7);
            var  heartbeatTimeout  = TimeSpan.FromSeconds(8);
            var  ipv6                   = false;
            var  kmsProviders           = kmsProvidersValue ?? new Dictionary <string, IReadOnlyDictionary <string, object> >();
            var  localThreshold         = TimeSpan.FromMilliseconds(20);
            var  maxConnectionIdleTime  = TimeSpan.FromSeconds(2);
            var  maxConnectionLifeTime  = TimeSpan.FromSeconds(3);
            var  maxConnectionPoolSize  = 50;
            var  minConnectionPoolSize  = 5;
            var  receiveBufferSize      = 1;
            var  replicaSetName         = "abc";
            var  schemaMap              = schemaMapValue ?? new Dictionary <string, BsonDocument>();
            var  scheme                 = ConnectionStringScheme.MongoDB;
            var  sdamLogFileName        = "stdout";
            var  sendBufferSize         = 1;
            var  servers                = new[] { new MongoServerAddress("localhost") };
            var  serverSelectionTimeout = TimeSpan.FromSeconds(6);
            var  socketTimeout          = TimeSpan.FromSeconds(4);
            var  sslSettings            = new SslSettings
            {
                CheckCertificateRevocation = true,
                EnabledSslProtocols        = SslProtocols.Tls
            };
            var useTls           = false;
            var waitQueueSize    = 20;
            var waitQueueTimeout = TimeSpan.FromSeconds(5);

            return(new ClusterKey(
                       allowInsecureTls,
                       applicationName,
                       clusterConfigurator,
                       compressors,
                       connectionMode,
                       connectionModeSwitch,
                       connectTimeout,
                       credentials,
                       directConnection,
                       heartbeatInterval,
                       heartbeatTimeout,
                       ipv6,
                       kmsProviders,
                       localThreshold,
                       maxConnectionIdleTime,
                       maxConnectionLifeTime,
                       maxConnectionPoolSize,
                       minConnectionPoolSize,
                       receiveBufferSize,
                       replicaSetName,
                       schemaMap,
                       scheme,
                       sdamLogFileName,
                       sendBufferSize,
                       servers,
                       serverSelectionTimeout,
                       socketTimeout,
                       sslSettings,
                       useTls,
                       waitQueueSize,
                       waitQueueTimeout));
        }
        public void Property_getter_shoud_throw_when_connectionModeSwitch_is_unexpected(ConnectionModeSwitch connectionModeSwitch, string property, bool shouldFail)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            var subject = CreateSubjectWith(connectionModeSwitch: connectionModeSwitch);

            Exception exception;

            switch (property)
            {
#pragma warning disable CS0618 // Type or member is obsolete
            case "connect": exception = Record.Exception(() => subject.ConnectionMode); break;

#pragma warning restore CS0618 // Type or member is obsolete
            case "directConnection": exception = Record.Exception(() => subject.DirectConnection); break;

            default: throw new Exception($"Unexpected property {property}.");
            }

            if (shouldFail)
            {
                exception.Should().BeOfType <InvalidOperationException>();
            }
            else
            {
                exception.Should().BeNull();
            }
        }
Exemple #21
0
#pragma warning disable CS0618 // Type or member is obsolete
        public static void _connectionModeSwitch(this MongoUrl url, ConnectionModeSwitch connectionModeSwitch)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            Reflector.SetFieldValue(url, nameof(_connectionModeSwitch), connectionModeSwitch);
        }
#pragma warning disable CS0618 // Type or member is obsolete
        public static void _connectionModeSwitch(this MongoClientSettings obj, ConnectionModeSwitch connectionModeSwitch)
        => Reflector.SetFieldValue(obj, nameof(_connectionModeSwitch), connectionModeSwitch);