Beispiel #1
0
        // methods
        /// <summary>
        /// Returns a new ClusterSettings instance with some settings changed.
        /// </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="serverApi">The server API.</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>
        /// <returns>A new ClusterSettings instance.</returns>
        public ClusterSettings With(
#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 <TimeSpan>),
            Optional <int> maxServerSelectionWaitQueueSize = default(Optional <int>),
            Optional <string> replicaSetName              = default(Optional <string>),
            Optional <ServerApi> serverApi                = default(Optional <ServerApi>),
            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>))
        {
            return(new ClusterSettings(
                       connectionMode: connectionMode.WithDefault(_connectionMode),
                       connectionModeSwitch: connectionModeSwitch.WithDefault(_connectionModeSwitch),
                       directConnection: directConnection.WithDefault(_directConnection),
                       endPoints: Optional.Enumerable(endPoints.WithDefault(_endPoints)),
                       kmsProviders: Optional.Create(kmsProviders.WithDefault(_kmsProviders)),
                       localThreshold: localThreshold.WithDefault(_localThreshold),
                       maxServerSelectionWaitQueueSize: maxServerSelectionWaitQueueSize.WithDefault(_maxServerSelectionWaitQueueSize),
                       replicaSetName: replicaSetName.WithDefault(_replicaSetName),
                       serverApi: serverApi.WithDefault(_serverApi),
                       serverSelectionTimeout: serverSelectionTimeout.WithDefault(_serverSelectionTimeout),
                       preServerSelector: Optional.Create(preServerSelector.WithDefault(_preServerSelector)),
                       postServerSelector: Optional.Create(postServerSelector.WithDefault(_postServerSelector)),
                       schemaMap: Optional.Create(schemaMap.WithDefault(_schemaMap)),
                       scheme: scheme.WithDefault(_scheme)));
        }
Beispiel #2
0
        private ICluster BuildCluster(BsonDocument definition)
        {
            var connectionString = new ConnectionString((string)definition["uri"]);
            var settings         = new ClusterSettings(
#pragma warning disable CS0618 // Type or member is obsolete
                connectionModeSwitch: connectionString.ConnectionModeSwitch,
                endPoints: Optional.Enumerable(connectionString.Hosts),
                replicaSetName: connectionString.ReplicaSet);

            if (settings.ConnectionModeSwitch == ConnectionModeSwitch.UseDirectConnection)
#pragma warning restore CS0618
            {
                settings = settings.With(directConnection: connectionString.DirectConnection);
            }
            else
            {
#pragma warning disable CS0618
                settings = settings.With(connectionMode: connectionString.Connect);
#pragma warning restore CS0618
            }

            // Passing in an eventCapturer results in Server being used instead of a Mock
            _serverFactory   = new MockClusterableServerFactory(new EventCapturer());
            _eventSubscriber = new Mock <IEventSubscriber>().Object;
            return(new ClusterFactory(settings, _serverFactory, _eventSubscriber)
                   .CreateCluster());
        }
Beispiel #3
0
 // methods
 /// <summary>
 /// Returns a new ClusterSettings instance with some settings changed.
 /// </summary>
 /// <param name="connectionMode">The connection mode.</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>
 /// <returns>A new ClusterSettings instance.</returns>
 public ClusterSettings With(
     Optional <ClusterConnectionMode> connectionMode = default(Optional <ClusterConnectionMode>),
     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 <TimeSpan>),
     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>))
 {
     return(new ClusterSettings(
                connectionMode: connectionMode.WithDefault(_connectionMode),
                endPoints: Optional.Enumerable(endPoints.WithDefault(_endPoints)),
                kmsProviders: Optional.Create(kmsProviders.WithDefault(_kmsProviders)),
                localThreshold: localThreshold.WithDefault(_localThreshold),
                maxServerSelectionWaitQueueSize: maxServerSelectionWaitQueueSize.WithDefault(_maxServerSelectionWaitQueueSize),
                replicaSetName: replicaSetName.WithDefault(_replicaSetName),
                serverSelectionTimeout: serverSelectionTimeout.WithDefault(_serverSelectionTimeout),
                preServerSelector: Optional.Create(preServerSelector.WithDefault(_preServerSelector)),
                postServerSelector: Optional.Create(postServerSelector.WithDefault(_postServerSelector)),
                schemaMap: Optional.Create(schemaMap.WithDefault(_schemaMap)),
                scheme: scheme.WithDefault(_scheme)));
 }
        private ICluster BuildCluster(BsonDocument definition)
        {
            var connectionString = new ConnectionString(definition["uri"].AsString);
            var settings         = new ClusterSettings(
#pragma warning disable CS0618
                connectionModeSwitch: connectionString.ConnectionModeSwitch,
#pragma warning restore CS0618
                endPoints: Optional.Enumerable(connectionString.Hosts),
                replicaSetName: connectionString.ReplicaSet);

#pragma warning disable CS0618
            if (connectionString.ConnectionModeSwitch == ConnectionModeSwitch.UseDirectConnection)
            {
                settings = settings.With(directConnection: connectionString.DirectConnection);
            }
            else
            {
                settings = settings.With(connectionMode: connectionString.Connect);
            }
#pragma warning restore CS0618

            _eventSubscriber = new EventCapturer();
            _eventSubscriber.Capture <ClusterOpeningEvent>(e => true);
            _eventSubscriber.Capture <ClusterDescriptionChangedEvent>(e => true);
            _eventSubscriber.Capture <ServerOpeningEvent>(e => true);
            _eventSubscriber.Capture <ServerDescriptionChangedEvent>(e => true);
            _eventSubscriber.Capture <ServerClosedEvent>(e => true);
            _serverFactory = new MockClusterableServerFactory(_eventSubscriber);
            return(new ClusterFactory(settings, _serverFactory, _eventSubscriber)
                   .CreateCluster());
        }
 // methods
 /// <summary>
 /// Returns a new ConnectionSettings instance with some settings changed.
 /// </summary>
 /// <param name="authenticators">The authenticators.</param>
 /// <param name="maxIdleTime">The maximum idle time.</param>
 /// <param name="maxLifeTime">The maximum life time.</param>
 /// <returns>A new ConnectionSettings instance.</returns>
 public ConnectionSettings With(
     Optional <IEnumerable <IAuthenticator> > authenticators = default(Optional <IEnumerable <IAuthenticator> >),
     Optional <TimeSpan> maxIdleTime = default(Optional <TimeSpan>),
     Optional <TimeSpan> maxLifeTime = default(Optional <TimeSpan>))
 {
     return(new ConnectionSettings(
                authenticators: Optional.Enumerable(authenticators.WithDefault(_authenticators)),
                maxIdleTime: maxIdleTime.WithDefault(_maxIdleTime),
                maxLifeTime: maxLifeTime.WithDefault(_maxLifeTime)));
 }
Beispiel #6
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);

            _eventSubscriber = new EventCapturer();
            _serverFactory   = new MockClusterableServerFactory(_eventSubscriber);
            return(new ClusterFactory(settings, _serverFactory, _eventSubscriber)
                   .CreateCluster());
        }
Beispiel #7
0
 // methods
 /// <summary>
 /// Returns a new SsslStreamSettings instance with some settings changed.
 /// </summary>
 /// <param name="checkCertificateRevocation">Whether to check certificate revocation.</param>
 /// <param name="clientCertificates">The client certificates.</param>
 /// <param name="clientCertificateSelectionCallback">The client certificate selection callback.</param>
 /// <param name="enabledProtocols">The enabled protocols.</param>
 /// <param name="serverCertificateValidationCallback">The server certificate validation callback.</param>
 /// <returns>A new SsslStreamSettings instance.</returns>
 public SslStreamSettings With(
     Optional <bool> checkCertificateRevocation = default(Optional <bool>),
     Optional <IEnumerable <X509Certificate> > clientCertificates = default(Optional <IEnumerable <X509Certificate> >),
     Optional <LocalCertificateSelectionCallback> clientCertificateSelectionCallback = default(Optional <LocalCertificateSelectionCallback>),
     Optional <SslProtocols> enabledProtocols = default(Optional <SslProtocols>),
     Optional <RemoteCertificateValidationCallback> serverCertificateValidationCallback = default(Optional <RemoteCertificateValidationCallback>))
 {
     return(new SslStreamSettings(
                checkCertificateRevocation: checkCertificateRevocation.WithDefault(_checkCertificateRevocation),
                clientCertificates: Optional.Enumerable(clientCertificates.WithDefault(_clientCertificates)),
                clientCertificateSelectionCallback: clientCertificateSelectionCallback.WithDefault(_clientCertificateSelectionCallback),
                enabledProtocols: enabledProtocols.WithDefault(_enabledSslProtocols),
                serverCertificateValidationCallback: serverCertificateValidationCallback.WithDefault(_serverCertificateValidationCallback)));
 }
 // methods
 /// <summary>
 /// Returns a new ConnectionSettings instance with some settings changed.
 /// </summary>
 /// <param name="authenticatorFactories">The authenticator factories.</param>
 /// <param name="compressors">The compressors.</param>
 /// <param name="maxIdleTime">The maximum idle time.</param>
 /// <param name="maxLifeTime">The maximum life time.</param>
 /// <param name="applicationName">The application name.</param>
 /// <returns>A new ConnectionSettings instance.</returns>
 public ConnectionSettings With(
     Optional <IEnumerable <IAuthenticatorFactory> > authenticatorFactories = default,
     Optional <IEnumerable <CompressorConfiguration> > compressors          = default(Optional <IEnumerable <CompressorConfiguration> >),
     Optional <TimeSpan> maxIdleTime   = default(Optional <TimeSpan>),
     Optional <TimeSpan> maxLifeTime   = default(Optional <TimeSpan>),
     Optional <string> applicationName = default(Optional <string>))
 {
     return(new ConnectionSettings(
                authenticatorFactories: Optional.Enumerable(authenticatorFactories.WithDefault(_authenticatorFactories)),
                compressors: Optional.Enumerable(compressors.WithDefault(_compressors)),
                maxIdleTime: maxIdleTime.WithDefault(_maxIdleTime),
                maxLifeTime: maxLifeTime.WithDefault(_maxLifeTime),
                applicationName: applicationName.WithDefault(_applicationName)));
 }
Beispiel #9
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);

            // Passing in an eventCapturer results in Server being used instead of a Mock
            _serverFactory   = new MockClusterableServerFactory(new EventCapturer());
            _eventSubscriber = new Mock <IEventSubscriber>().Object;
            return(new ClusterFactory(settings, _serverFactory, _eventSubscriber)
                   .CreateCluster());
        }
Beispiel #10
0
        private ICluster BuildCluster(BsonDocument definition)
        {
            var connectionString = new ConnectionString(definition["uri"].AsString);
            var settings         = new ClusterSettings(
                endPoints: Optional.Enumerable(connectionString.Hosts),
                connectionMode: connectionString.Connect,
                replicaSetName: connectionString.ReplicaSet);

            _eventSubscriber = new EventCapturer();
            _eventSubscriber.Capture <ClusterOpeningEvent>(e => true);
            _eventSubscriber.Capture <ClusterDescriptionChangedEvent>(e => true);
            _eventSubscriber.Capture <ServerOpeningEvent>(e => true);
            _eventSubscriber.Capture <ServerDescriptionChangedEvent>(e => true);
            _eventSubscriber.Capture <ServerClosedEvent>(e => true);
            _serverFactory = new MockClusterableServerFactory(_eventSubscriber);
            return(new ClusterFactory(settings, _serverFactory, _eventSubscriber)
                   .CreateCluster());
        }
 // methods
 /// <summary>
 /// Returns a new ClusterSettings instance with some settings changed.
 /// </summary>
 /// <param name="connectionMode">The connection mode.</param>
 /// <param name="endPoints">The end points.</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>
 /// <returns>A new ClusterSettings instance.</returns>
 public ClusterSettings With(
     Optional <ClusterConnectionMode> connectionMode = default(Optional <ClusterConnectionMode>),
     Optional <IEnumerable <EndPoint> > endPoints    = default(Optional <IEnumerable <EndPoint> >),
     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>))
 {
     return(new ClusterSettings(
                connectionMode: connectionMode.WithDefault(_connectionMode),
                endPoints: Optional.Enumerable(endPoints.WithDefault(_endPoints)),
                maxServerSelectionWaitQueueSize: maxServerSelectionWaitQueueSize.WithDefault(_maxServerSelectionWaitQueueSize),
                replicaSetName: replicaSetName.WithDefault(_replicaSetName),
                serverSelectionTimeout: serverSelectionTimeout.WithDefault(_serverSelectionTimeout),
                preServerSelector: Optional.Create(preServerSelector.WithDefault(_preServerSelector)),
                postServerSelector: Optional.Create(postServerSelector.WithDefault(_postServerSelector))));
 }
        /// <summary>
        /// Configures a cluster builder from a connection string.
        /// </summary>
        /// <param name="builder">The cluster builder.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <returns>A reconfigured cluster builder.</returns>
        public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder builder, ConnectionString connectionString)
        {
            Ensure.IsNotNull(builder, nameof(builder));
            Ensure.IsNotNull(connectionString, nameof(connectionString));

            connectionString = connectionString.Resolve();

            // TCP
            if (connectionString.ConnectTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(connectTimeout: connectionString.ConnectTimeout.Value));
            }
            if (connectionString.HeartbeatInterval.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatInterval: connectionString.HeartbeatInterval.Value));
            }
            if (connectionString.HeartbeatTimeout.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatTimeout: connectionString.HeartbeatTimeout.Value));
            }
            if (connectionString.Ipv6.HasValue && connectionString.Ipv6.Value)
            {
                builder = builder.ConfigureTcp(s => s.With(addressFamily: AddressFamily.InterNetworkV6));
            }

            if (connectionString.SocketTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(
                                                   readTimeout: connectionString.SocketTimeout.Value,
                                                   writeTimeout: connectionString.SocketTimeout.Value));
            }

            if (connectionString.Ssl != null)
            {
                builder = builder.ConfigureSsl(ssl =>
                {
                    if (!connectionString.SslVerifyCertificate.GetValueOrDefault(true))
                    {
                        ssl = ssl.With(
                            serverCertificateValidationCallback: new RemoteCertificateValidationCallback(AcceptAnySslCertificate));
                    }

                    return(ssl);
                });
            }

            // Connection
            if (connectionString.Username != null)
            {
                var authenticator = CreateAuthenticator(connectionString);
                builder = builder.ConfigureConnection(s => s.With(authenticators: new[] { authenticator }));
            }
            if (connectionString.ApplicationName != null)
            {
                builder = builder.ConfigureConnection(s => s.With(applicationName: connectionString.ApplicationName));
            }
            if (connectionString.MaxIdleTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxIdleTime: connectionString.MaxIdleTime.Value));
            }
            if (connectionString.MaxLifeTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxLifeTime: connectionString.MaxLifeTime.Value));
            }

            // Connection Pool
            if (connectionString.MaxPoolSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(maxConnections: connectionString.MaxPoolSize.Value));
            }
            if (connectionString.MinPoolSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(minConnections: connectionString.MinPoolSize.Value));
            }
            if (connectionString.WaitQueueSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: connectionString.WaitQueueSize.Value));
            }
            else if (connectionString.WaitQueueMultiple != null)
            {
                var maxConnections = connectionString.MaxPoolSize ?? new ConnectionPoolSettings().MaxConnections;
                var waitQueueSize  = (int)Math.Round(maxConnections * connectionString.WaitQueueMultiple.Value);
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: waitQueueSize));
            }
            if (connectionString.WaitQueueTimeout != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueTimeout: connectionString.WaitQueueTimeout.Value));
            }

            // Server

            // Cluster
            builder = builder.ConfigureCluster(s => s.With(connectionMode: connectionString.Connect));
            if (connectionString.Hosts.Count > 0)
            {
                builder = builder.ConfigureCluster(s => s.With(endPoints: Optional.Enumerable(connectionString.Hosts)));
            }
            if (connectionString.ReplicaSet != null)
            {
                builder = builder.ConfigureCluster(s => s.With(
                                                       connectionMode: ClusterConnectionMode.ReplicaSet,
                                                       replicaSetName: connectionString.ReplicaSet));
            }
            if (connectionString.ServerSelectionTimeout != null)
            {
                builder = builder.ConfigureCluster(s => s.With(serverSelectionTimeout: connectionString.ServerSelectionTimeout.Value));
            }

            return(builder);
        }
Beispiel #13
0
        /// <summary>
        /// Configures a cluster builder from a connection string.
        /// </summary>
        /// <param name="builder">The cluster builder.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <returns>A reconfigured cluster builder.</returns>
        public static ClusterBuilder ConfigureWithConnectionString(this ClusterBuilder builder, ConnectionString connectionString)
        {
            Ensure.IsNotNull(builder, nameof(builder));
            Ensure.IsNotNull(connectionString, nameof(connectionString));

            if (!connectionString.IsResolved)
            {
                var connectionMode = connectionString.Connect;
                var resolveHosts   = connectionMode == ClusterConnectionMode.Direct || connectionMode == ClusterConnectionMode.Standalone;
                connectionString = connectionString.Resolve(resolveHosts);
            }

            // TCP
            if (connectionString.ConnectTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(connectTimeout: connectionString.ConnectTimeout.Value));
            }
            if (connectionString.HeartbeatInterval.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatInterval: connectionString.HeartbeatInterval.Value));
            }
            if (connectionString.HeartbeatTimeout.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatTimeout: connectionString.HeartbeatTimeout.Value));
            }
            if (connectionString.Ipv6.HasValue && connectionString.Ipv6.Value)
            {
                builder = builder.ConfigureTcp(s => s.With(addressFamily: AddressFamily.InterNetworkV6));
            }

            if (connectionString.SocketTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(
                                                   readTimeout: connectionString.SocketTimeout.Value,
                                                   writeTimeout: connectionString.SocketTimeout.Value));
            }

            if (connectionString.Tls != null)
            {
                builder = builder.ConfigureSsl(ssl =>
                {
                    if (connectionString.TlsInsecure.GetValueOrDefault(false))
                    {
                        ssl = ssl.With(serverCertificateValidationCallback: new RemoteCertificateValidationCallback(AcceptAnySslCertificate));
                    }
                    if (connectionString.TlsDisableCertificateRevocationCheck.HasValue)
                    {
                        ssl = ssl.With(
                            checkCertificateRevocation: !connectionString.TlsDisableCertificateRevocationCheck.Value);
                    }

                    return(ssl);
                });
            }

            // Connection
            if (connectionString.Username != null)
            {
                var authenticatorFactory = new AuthenticatorFactory(() => CreateAuthenticator(connectionString));
                builder = builder.ConfigureConnection(s => s.With(authenticatorFactories: new[] { authenticatorFactory }));
            }
            if (connectionString.ApplicationName != null)
            {
                builder = builder.ConfigureConnection(s => s.With(applicationName: connectionString.ApplicationName));
            }
            if (connectionString.MaxIdleTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxIdleTime: connectionString.MaxIdleTime.Value));
            }
            if (connectionString.MaxLifeTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxLifeTime: connectionString.MaxLifeTime.Value));
            }

            if (connectionString.Compressors != null)
            {
                builder = builder.ConfigureConnection(s => s.With(compressors: connectionString.Compressors.ToArray()));
            }

            // Connection Pool
            if (connectionString.MaxPoolSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(maxConnections: connectionString.MaxPoolSize.Value));
            }
            if (connectionString.MinPoolSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(minConnections: connectionString.MinPoolSize.Value));
            }
#pragma warning disable 618
            if (connectionString.WaitQueueSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: connectionString.WaitQueueSize.Value));
            }
            else if (connectionString.WaitQueueMultiple != null)
            {
                var maxConnections = connectionString.MaxPoolSize ?? new ConnectionPoolSettings().MaxConnections;
                var waitQueueSize  = (int)Math.Round(maxConnections * connectionString.WaitQueueMultiple.Value);
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: waitQueueSize));
            }
#pragma warning restore 618
            if (connectionString.WaitQueueTimeout != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueTimeout: connectionString.WaitQueueTimeout.Value));
            }

            // Server

            // Cluster
            builder = builder.ConfigureCluster(s => s.With(connectionMode: connectionString.Connect));
            if (connectionString.Hosts.Count > 0)
            {
                builder = builder.ConfigureCluster(s => s.With(endPoints: Optional.Enumerable(connectionString.Hosts)));
            }
            if (connectionString.ReplicaSet != null)
            {
                builder = builder.ConfigureCluster(s => s.With(
                                                       connectionMode: ClusterConnectionMode.ReplicaSet,
                                                       replicaSetName: connectionString.ReplicaSet));
            }
            if (connectionString.ServerSelectionTimeout != null)
            {
                builder = builder.ConfigureCluster(s => s.With(serverSelectionTimeout: connectionString.ServerSelectionTimeout.Value));
            }

            return(builder);
        }
Beispiel #14
0
        /// <summary>
        /// Configures a cluster builder from a connection string.
        /// </summary>
        /// <param name="builder">The cluster builder.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <param name="serverApi">The server API.</param>
        /// <returns>A reconfigured cluster builder.</returns>
        public static ClusterBuilder ConfigureWithConnectionString(
            this ClusterBuilder builder,
            ConnectionString connectionString,
            ServerApi serverApi)
        {
            Ensure.IsNotNull(builder, nameof(builder));
            Ensure.IsNotNull(connectionString, nameof(connectionString));

            if (!connectionString.IsResolved)
            {
                bool resolveHosts;
#pragma warning disable CS0618 // Type or member is obsolete
                if (connectionString.ConnectionModeSwitch == ConnectionModeSwitch.UseDirectConnection)
#pragma warning restore CS0618 // Type or member is obsolete
                {
                    resolveHosts = connectionString.DirectConnection.GetValueOrDefault();
                }
                else
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    resolveHosts = connectionString.Connect == ClusterConnectionMode.Direct || connectionString.Connect == ClusterConnectionMode.Standalone;
#pragma warning restore CS0618 // Type or member is obsolete
                }

                connectionString = connectionString.Resolve(resolveHosts);
            }

            // TCP
            if (connectionString.ConnectTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(connectTimeout: connectionString.ConnectTimeout.Value));
            }
            if (connectionString.HeartbeatInterval.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatInterval: connectionString.HeartbeatInterval.Value));
            }
            if (connectionString.HeartbeatTimeout.HasValue)
            {
                builder = builder.ConfigureServer(s => s.With(heartbeatTimeout: connectionString.HeartbeatTimeout.Value));
            }
            if (connectionString.Ipv6.HasValue && connectionString.Ipv6.Value)
            {
                builder = builder.ConfigureTcp(s => s.With(addressFamily: AddressFamily.InterNetworkV6));
            }

            if (connectionString.SocketTimeout != null)
            {
                builder = builder.ConfigureTcp(s => s.With(
                                                   readTimeout: connectionString.SocketTimeout.Value,
                                                   writeTimeout: connectionString.SocketTimeout.Value));
            }

            if (connectionString.Tls != null)
            {
                builder = builder.ConfigureSsl(ssl =>
                {
                    if (connectionString.TlsInsecure.GetValueOrDefault(false))
                    {
                        ssl = ssl.With(serverCertificateValidationCallback: new RemoteCertificateValidationCallback(AcceptAnySslCertificate));
                    }
                    if (connectionString.TlsDisableCertificateRevocationCheck.HasValue)
                    {
                        ssl = ssl.With(
                            checkCertificateRevocation: !connectionString.TlsDisableCertificateRevocationCheck.Value);
                    }

                    return(ssl);
                });
            }

            // Connection
            if (connectionString.Username != null)
            {
                var authenticatorFactory = new AuthenticatorFactory(() => CreateAuthenticator(connectionString, serverApi));
                builder = builder.ConfigureConnection(s => s.With(authenticatorFactories: new[] { authenticatorFactory }));
            }
            if (connectionString.ApplicationName != null)
            {
                builder = builder.ConfigureConnection(s => s.With(applicationName: connectionString.ApplicationName));
            }
            if (connectionString.LoadBalanced)
            {
                builder = builder.ConfigureConnection(s => s.With(loadBalanced: connectionString.LoadBalanced));
            }
            if (connectionString.MaxIdleTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxIdleTime: connectionString.MaxIdleTime.Value));
            }
            if (connectionString.MaxLifeTime != null)
            {
                builder = builder.ConfigureConnection(s => s.With(maxLifeTime: connectionString.MaxLifeTime.Value));
            }

            if (connectionString.Compressors != null)
            {
                builder = builder.ConfigureConnection(s => s.With(compressors: connectionString.Compressors.ToArray()));
            }

            // Connection Pool
            if (connectionString.MaxPoolSize != null)
            {
                var effectiveMaxConnections = ConnectionStringConversions.GetEffectiveMaxConnections(connectionString.MaxPoolSize.Value);
                builder = builder.ConfigureConnectionPool(s => s.With(maxConnections: effectiveMaxConnections));
            }
            if (connectionString.MinPoolSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(minConnections: connectionString.MinPoolSize.Value));
            }
#pragma warning disable 618
            if (connectionString.WaitQueueSize != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: connectionString.WaitQueueSize.Value));
            }
            else if (connectionString.WaitQueueMultiple != null)
            {
                var effectiveMaxConnections = ConnectionStringConversions.GetEffectiveMaxConnections(connectionString.MaxPoolSize) ?? new ConnectionPoolSettings().MaxConnections;
                var computedWaitQueueSize   = ConnectionStringConversions.GetComputedWaitQueueSize(effectiveMaxConnections, connectionString.WaitQueueMultiple.Value);
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueSize: computedWaitQueueSize));
            }
#pragma warning restore 618
            if (connectionString.WaitQueueTimeout != null)
            {
                builder = builder.ConfigureConnectionPool(s => s.With(waitQueueTimeout: connectionString.WaitQueueTimeout.Value));
            }

            // Server

            // Cluster
#pragma warning disable CS0618 // Type or member is obsolete
            var connectionModeSwitch = connectionString.ConnectionModeSwitch;
            var connectionMode       = connectionModeSwitch == ConnectionModeSwitch.UseConnectionMode ? connectionString.Connect : default;
            var directConnection     = connectionModeSwitch == ConnectionModeSwitch.UseDirectConnection ? connectionString.DirectConnection : default;
            builder = builder.ConfigureCluster(
                s =>
                s.With(
                    connectionMode: connectionMode,
                    connectionModeSwitch: connectionModeSwitch,
                    directConnection: directConnection,
                    scheme: connectionString.Scheme,
                    loadBalanced: connectionString.LoadBalanced));
#pragma warning restore CS0618 // Type or member is obsolete
            if (connectionString.Hosts.Count > 0)
            {
                builder = builder.ConfigureCluster(s => s.With(endPoints: Optional.Enumerable(connectionString.Hosts)));
            }
            if (connectionString.ReplicaSet != null)
            {
                builder = builder.ConfigureCluster(s => s.With(replicaSetName: connectionString.ReplicaSet));
            }
            if (connectionString.ServerSelectionTimeout != null)
            {
                builder = builder.ConfigureCluster(s => s.With(serverSelectionTimeout: connectionString.ServerSelectionTimeout.Value));
            }
            if (serverApi != null)
            {
                builder = builder.ConfigureCluster(s => s.With(serverApi: serverApi));
            }

            return(builder);
        }