public void TestFixtureSetUp()
 {
     var ipEndpoint = UriExtensions.GetEndPoint(_address);
     var connectionPoolConfig = new PoolConfiguration { UseSsl = false };
     _connectionPool = new ConnectionPool<Connection>(connectionPoolConfig, ipEndpoint);
     _ioService = new PooledIOService(_connectionPool);
 }
 public void TestFixtureSetUp()
 {
     var ipEndpoint = UriExtensions.GetEndPoint(Address);
     var connectionPoolConfig = new PoolConfiguration();
     _connectionPool = new ConnectionPool<EapConnection>(connectionPoolConfig, ipEndpoint);
     _ioStrategy = new DefaultIOStrategy(_connectionPool);
 }
 public void OneTimeSetUp()
 {
     var ipEndpoint = UriExtensions.GetEndPoint(_address);
     var connectionPoolConfig = new PoolConfiguration();
     _connectionPool = new ConnectionPool<Connection>(connectionPoolConfig, ipEndpoint);
     _ioService = new PooledIOService(_connectionPool);
 }
        public ClientConfiguration()
        {
            UseSsl                          = false;
            SslPort                         = 11207;
            ApiPort                         = 8092;
            DirectPort                      = 11210;
            MgmtPort                        = 8091;
            HttpsMgmtPort                   = 18091;
            HttpsApiPort                    = 18092;
            ObserveInterval                 = 10;    //ms
            ObserveTimeout                  = 500;   //ms
            MaxViewRetries                  = 2;
            ViewHardTimeout                 = 30000; //ms
            HeartbeatConfigInterval         = 10000; //ms
            EnableConfigHeartBeat           = true;
            SerializationContractResolver   = new CamelCasePropertyNamesContractResolver();
            DeserializationContractResolver = new CamelCasePropertyNamesContractResolver();

            PoolConfiguration = new PoolConfiguration();
            BucketConfigs     = new Dictionary <string, BucketConfiguration>
            {
                { DefaultBucket, new BucketConfiguration
                  {
                      PoolConfiguration = PoolConfiguration
                  } }
            };
            Servers = new List <Uri> {
                _defaultServer
            };

            //Set back to default
            _serversChanged           = false;
            _poolConfigurationChanged = false;
        }
        public ClientConfiguration()
        {
            UseSsl        = false;
            SslPort       = 11207;
            ApiPort       = 8092;
            DirectPort    = 11210;
            MgmtPort      = 8091;
            HttpsMgmtPort = 18091;
            HttpsApiPort  = 18092;

            PoolConfiguration = new PoolConfiguration();
            BucketConfigs     = new Dictionary <string, BucketConfiguration>
            {
                { DefaultBucket, new BucketConfiguration
                  {
                      PoolConfiguration = PoolConfiguration
                  } }
            };
            Servers = new List <Uri> {
                _defaultServer
            };

            //Set back to default
            _serversChanged           = false;
            _poolConfigurationChanged = false;
        }
        public void When_Connecting_To_Dead_IP_Connection_Fails_After_n_Seconds()
        {
            const int connectionTimedOut = 10060;
            const string ipThatDoesNotExist = "198.0.0.1:11210";
            var ipEndpoint = UriExtensions.GetEndPoint(ipThatDoesNotExist);
            var connectionPoolConfig = new PoolConfiguration
            {
                ConnectTimeout = 1000 //set really low for test
            };
            var connectionPool = new ConnectionPool<Connection>(connectionPoolConfig, ipEndpoint);

            var stopWatch = new Stopwatch();
            try
            {
                stopWatch.Start();
                var connection = connectionPool.Acquire();
            }
            catch (SocketException e)
            {
                Assert.AreEqual(connectionTimedOut, e.ErrorCode);
            }
            finally
            {
                stopWatch.Stop();
                Assert.AreEqual(1.0d, Math.Round((double)stopWatch.Elapsed.Seconds));
            }
        }
        public ClientConfiguration()
        {
            UseSsl = false;
            SslPort = 11207;
            ApiPort = 8092;
            DirectPort = 11210;
            MgmtPort = 8091;
            HttpsMgmtPort = 18091;
            HttpsApiPort = 18092;
            ObserveInterval = 10; //ms
            ObserveTimeout = 500; //ms
            MaxViewRetries = 2;
            ViewHardTimeout = 30000; //ms
            SerializationContractResolver = new CamelCasePropertyNamesContractResolver();
            DeserializationContractResolver = new CamelCasePropertyNamesContractResolver();

            PoolConfiguration = new PoolConfiguration();
            BucketConfigs = new Dictionary<string, BucketConfiguration>
            {
                {DefaultBucket, new BucketConfiguration
                {
                    PoolConfiguration = PoolConfiguration
                }}
            };
            Servers = new List<Uri> { _defaultServer };

            //Set back to default
            _serversChanged = false;
            _poolConfigurationChanged = false;
        }
        /// <summary>
        /// For synchronization with App.config or Web.configs.
        /// </summary>
        /// <param name="couchbaseClientSection"></param>
        public ClientConfiguration(CouchbaseClientSection couchbaseClientSection)
        {
            //For operation timing
            Timer = TimingFactory.GetTimer(Log);

            UseSsl                = couchbaseClientSection.UseSsl;
            SslPort               = couchbaseClientSection.SslPort;
            ApiPort               = couchbaseClientSection.ApiPort;
            DirectPort            = couchbaseClientSection.DirectPort;
            MgmtPort              = couchbaseClientSection.MgmtPort;
            HttpsMgmtPort         = couchbaseClientSection.HttpsMgmtPort;
            HttpsApiPort          = couchbaseClientSection.HttpsApiPort;
            ObserveInterval       = couchbaseClientSection.ObserveInterval;
            ObserveTimeout        = couchbaseClientSection.ObserveTimeout;
            MaxViewRetries        = couchbaseClientSection.MaxViewRetries;
            ViewHardTimeout       = couchbaseClientSection.ViewHardTimeout;
            SerializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            EnableConfigHeartBeat   = couchbaseClientSection.EnableConfigHeartBeat;
            HeartbeatConfigInterval = couchbaseClientSection.HeartbeatConfigInterval;
            ViewRequestTimeout      = couchbaseClientSection.ViewRequestTimeout;
            Expect100Continue       = couchbaseClientSection.Expect100Continue;
            EnableOperationTiming   = couchbaseClientSection.EnableOperationTiming;
            PoolConfiguration       = new PoolConfiguration(this);

            foreach (var server in couchbaseClientSection.Servers)
            {
                Servers.Add(((UriElement)server).Uri);
                _serversChanged = true;
            }

            BucketConfigs = new Dictionary <string, BucketConfiguration>();
            foreach (var bucketElement in couchbaseClientSection.Buckets)
            {
                var bucket = (BucketElement)bucketElement;
                var bucketConfiguration = new BucketConfiguration
                {
                    BucketName        = bucket.Name,
                    UseSsl            = bucket.UseSsl,
                    Password          = bucket.Password,
                    ObserveInterval   = bucket.ObserveInterval,
                    ObserveTimeout    = bucket.ObserveTimeout,
                    PoolConfiguration = new PoolConfiguration
                    {
                        MaxSize             = bucket.ConnectionPool.MaxSize,
                        MinSize             = bucket.ConnectionPool.MinSize,
                        WaitTimeout         = bucket.ConnectionPool.WaitTimeout,
                        ShutdownTimeout     = bucket.ConnectionPool.ShutdownTimeout,
                        UseSsl              = bucket.ConnectionPool.UseSsl,
                        ClientConfiguration = this
                    }
                };
                BucketConfigs.Add(bucket.Name, bucketConfiguration);
            }
        }
 public void SetUp()
 {
     var ipEndpoint = UriExtensions.GetEndPoint(Address);
     var factory = DefaultConnectionFactory.GetDefault();
     _configuration = new PoolConfiguration(MaxSize, MinSize, WaitTimeout, RecieveTimeout, ShutdownTimeout, SendTimeout);
     _connectionPool = new DefaultConnectionPool(_configuration, ipEndpoint, factory);
     _connectionPool.Initialize();
 }
Пример #10
0
        public PoolConfiguration ClonePoolConfiguration(Uri server)
        {
            var poolConfig = PoolConfiguration.Clone(server);

            poolConfig.UseEnhancedDurability = UseEnhancedDurability;
            poolConfig.UseSsl = UseSsl;
            return(poolConfig);
        }
 public void TestFixtureSetUp()
 {
     var ipEndpoint = UriExtensions.GetEndPoint(_address);
     var connectionPoolConfig = new PoolConfiguration();
     _connectionPool = new ConnectionPool<Connection>(connectionPoolConfig, ipEndpoint);
     _connectionPool.Initialize();
     _ioService = new PooledIOService(_connectionPool, null);
 }
 public virtual void TestFixtureSetUp()
 {
     EndPoint = UriExtensions.GetEndPoint(Address);
     var connectionPoolConfig = new PoolConfiguration();
     _connectionPool = new ConnectionPool<Connection>(connectionPoolConfig, EndPoint);
     _ioService = new PooledIOService(_connectionPool);
     Transcoder = new DefaultTranscoder();
 }
 public void SetUp()
 {
     var ipEndpoint = UriExtensions.GetEndPoint(_address);
     var factory = DefaultConnectionFactory.GetGeneric<Connection>();
     _configuration = new PoolConfiguration(MaxSize, MinSize, WaitTimeout, RecieveTimeout, ShutdownTimeout, SendTimeout, ConnectTimeout, MaxConnectionAcquireCount);
     _connectionPool = new ConnectionPool<Connection>(_configuration, ipEndpoint, factory, new DefaultConverter());
     _connectionPool.Initialize();
 }
        public PoolConfiguration ClonePoolConfiguration(Uri server)
        {
            var poolConfig = PoolConfiguration.Clone(server);

            poolConfig.UseEnhancedDurability = UseEnhancedDurability;
            poolConfig.UseKvErrorMap         = UseKvErrorMap;
            poolConfig.UseSsl     = UseSsl;
            poolConfig.BucketName = BucketName;
            return(poolConfig);
        }
 public void TestFixtureSetUp()
 {
     var ipEndpoint = UriExtensions.GetEndPoint(_address.Replace("11210", "11207"));
     var connectionPoolConfig = new PoolConfiguration
     {
         UseSsl = true
     };
     _connectionPool = new ConnectionPool<SslConnection>(connectionPoolConfig, ipEndpoint);
     _connectionPool.Initialize();
     _ioService = new PooledIOService(_connectionPool, null);
 }
        public void TestFixtureSetUp()
        {
            _endPoint = UriExtensions.GetEndPoint(_address);
            var connectionPoolConfig = new PoolConfiguration
            {
                MinSize = 1,
                MaxSize = 1
            };
            _connectionPool = new ConnectionPool<Connection>(connectionPoolConfig, _endPoint);

            _ioService = new PooledIOService(_connectionPool);
        }
 public void OneTimeSetUp()
 {
     var ipEndpoint = UriExtensions.GetEndPoint(_address.Replace("11210", "11207"));
     var connectionPoolConfig = new PoolConfiguration
     {
         UseSsl = true,
         Uri = new Uri(ConfigurationManager.AppSettings["bootstrapUrl"])
     };
     _connectionPool = new ConnectionPool<SslConnection>(connectionPoolConfig, ipEndpoint);
     _connectionPool.Initialize();
     _ioService = new PooledIOService(_connectionPool, null);
 }
 /// <summary>
 /// Default CTOR for localhost.
 /// </summary>
 public BucketConfiguration()
 {
     Servers = new List<Uri> { new Uri("http://localhost:8091/pools") };
     Port = 11210;
     Password = string.Empty;
     Username = string.Empty;
     BucketName = "default";
     ObserveInterval = 10; //ms
     ObserveTimeout = 500; //ms
     _operationLifespan = 2500; //ms, work around property that flags as changed
     PoolConfiguration = new PoolConfiguration();
 }
 /// <summary>
 /// Default CTOR for localhost.
 /// </summary>
 public BucketConfiguration()
 {
     Servers = new List<Uri> { new Uri("http://localhost:8091/pools") };
     Port = Defaults.Port;
     Password = Defaults.Password;
     Username = Defaults.Username;
     BucketName = Defaults.BucketName;
     ObserveInterval = Defaults.ObserveInternal; //ms
     ObserveTimeout = Defaults.ObserverTimeout; //ms
     _operationLifespan = Defaults.OperationLifespan; //ms, work around property that flags as changed
     UseSsl = Defaults.UseSsl;
     PoolConfiguration = new PoolConfiguration();
 }
 public void SetUp()
 {
     _address = string.Format("{0}:11207", ConfigurationManager.AppSettings["serverIp"]);
     var ipEndpoint = UriExtensions.GetEndPoint(_address);
     var factory = DefaultConnectionFactory.GetGeneric<SslConnection>();
     var converter = new DefaultConverter();
     _configuration = new PoolConfiguration(MaxSize, MinSize, WaitTimeout, RecieveTimeout, ShutdownTimeout, SendTimeout, ConnectTimeout, MaxConnectionAcquireCount)
     {
         UseSsl = true
     };
     _connectionPool = new ConnectionPool<SslConnection>(_configuration, ipEndpoint, factory, converter);
     _connectionPool.Initialize();
 }
 /// <summary>
 /// Default CTOR for localhost.
 /// </summary>
 public BucketConfiguration()
 {
     Servers = new List <Uri> {
         new Uri("http://localhost:8091/pools")
     };
     Port               = 11210;
     Password           = string.Empty;
     Username           = string.Empty;
     BucketName         = "default";
     ObserveInterval    = 10;   //ms
     ObserveTimeout     = 500;  //ms
     _operationLifespan = 2500; //ms, work around property that flags as changed
     PoolConfiguration  = new PoolConfiguration();
 }
        public void Can_Clone_PoolConfiguration()
        {
            var poolConfig = new PoolConfiguration
            {
                MaxSize = 10,
                MinSize = 5
            };

            var clonedConfig = poolConfig.Clone(new Uri("http://test.com"));

            Assert.IsNotNull(clonedConfig);
            Assert.AreEqual(poolConfig.MaxSize, clonedConfig.MaxSize);
            Assert.AreEqual(poolConfig.MinSize, clonedConfig.MinSize);
        }
        public ClientConfiguration()
        {
            //For operation timing
            Timer = TimingFactory.GetTimer(Log);

            UseSsl                  = false;
            SslPort                 = 11207;
            ApiPort                 = 8092;
            DirectPort              = 11210;
            MgmtPort                = 8091;
            HttpsMgmtPort           = 18091;
            HttpsApiPort            = 18092;
            ObserveInterval         = 10;    //ms
            ObserveTimeout          = 500;   //ms
            MaxViewRetries          = 2;
            ViewHardTimeout         = 30000; //ms
            HeartbeatConfigInterval = 10000; //ms
            EnableConfigHeartBeat   = true;
            SerializationSettings   = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            ViewRequestTimeout     = 5000; //ms
            DefaultConnectionLimit = 5;    //connections
            Expect100Continue      = false;
            EnableOperationTiming  = false;
            BufferSize             = 1024 * 16;

            PoolConfiguration = new PoolConfiguration(this)
            {
                BufferSize      = BufferSize,
                BufferAllocator = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize)
            };
            BucketConfigs = new Dictionary <string, BucketConfiguration>
            {
                { DefaultBucket, new BucketConfiguration
                  {
                      PoolConfiguration = PoolConfiguration
                  } }
            };
            Servers = new List <Uri> {
                _defaultServer
            };

            //Set back to default
            _serversChanged           = false;
            _poolConfigurationChanged = false;
        }
 /// <summary>
 /// Default CTOR for localhost.
 /// </summary>
 public BucketConfiguration()
 {
     Servers = new List <Uri> {
         new Uri("http://localhost:8091/pools")
     };
     Port               = Defaults.Port;
     Password           = Defaults.Password;
     Username           = Defaults.Username;
     BucketName         = Defaults.BucketName;
     ObserveInterval    = Defaults.ObserveInternal;   //ms
     ObserveTimeout     = Defaults.ObserverTimeout;   //ms
     _operationLifespan = Defaults.OperationLifespan; //ms, work around property that flags as changed
     UseSsl             = Defaults.UseSsl;
     PoolConfiguration  = new PoolConfiguration();
 }
        public void Test_Acquire_2ndRequest_Gets_Connection_From_Pool_While_1stRequest_Waits_For_Opening()
        {
            //Arrange
            var ipEndpoint = UriExtensions.GetEndPoint(_address);
            var factoryWithDelay = new Func<ConnectionPool<Connection>, IByteConverter, BufferAllocator, Connection>(
                (a, b, c) =>
                {
                    var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //remove sleep and use Moq for threads synchronization
                    Thread.Sleep(500);
                    return new Connection(a, socket, b, c);
                });

            _configuration = new PoolConfiguration(MaxSize, 1, WaitTimeout, RecieveTimeout, ShutdownTimeout, SendTimeout, ConnectTimeout, MaxConnectionAcquireCount);
            _connectionPool = new ConnectionPool<Connection>(_configuration, ipEndpoint, factoryWithDelay, new DefaultConverter());
            _connectionPool.Initialize();

            //Act
            var connectionFromPool = _connectionPool.Acquire();
            var task1 = new Task<IConnection>(() => _connectionPool.Acquire());
            var task2 = new Task<IConnection>(() => _connectionPool.Acquire());

            task1.Start();
            Thread.Sleep(100);
            task2.Start();
            //enqueue connection to pool
            //at this point task2 should get released connection
            _connectionPool.Release(connectionFromPool);

            Task.WaitAll(task1, task2);

            var connectionFromFactory = task1.Result;
            var connectionFromPoolReleased = task2.Result;


            //Assert
            Assert.IsNotNull(connectionFromFactory);
            Assert.AreNotEqual(connectionFromPool, connectionFromFactory);
            Assert.AreEqual(connectionFromPool, connectionFromPoolReleased);
        }
Пример #26
0
        internal void Initialize()
        {
            if (PoolConfiguration == null)
            {
                PoolConfiguration = new PoolConfiguration(this);
            }
            if (PoolConfiguration.ClientConfiguration == null)
            {
                PoolConfiguration.ClientConfiguration = this;
            }

            if (_serversChanged)
            {
                for (var i = 0; i < _servers.Count(); i++)
                {
                    if (_servers[i].OriginalString.EndsWith("/pools"))
                    {
                        /*noop*/
                    }
                    else
                    {
                        var newUri = _servers[i].ToString();
                        newUri      = string.Concat(newUri, newUri.EndsWith("/") ? "pools" : "/pools");
                        _servers[i] = new Uri(newUri);
                    }
                }
            }

            //Update the bucket configs
            foreach (var keyValue in BucketConfigs)
            {
                var bucketConfiguration = keyValue.Value;
                if (string.IsNullOrEmpty(bucketConfiguration.BucketName))
                {
                    if (string.IsNullOrWhiteSpace(keyValue.Key))
                    {
                        throw new ArgumentException("bucketConfiguration.BucketName is null or empty.");
                    }
                    bucketConfiguration.BucketName = keyValue.Key;
                }
                if (bucketConfiguration.PoolConfiguration == null || _poolConfigurationChanged)
                {
                    bucketConfiguration.PoolConfiguration = PoolConfiguration;
                }
                if (bucketConfiguration.Servers == null || HasServersChanged())
                {
                    bucketConfiguration.Servers = Servers.Select(x => x).ToList();
                }
                if (bucketConfiguration.Servers.Count == 0)
                {
                    bucketConfiguration.Servers.AddRange(Servers.Select(x => x).ToList());
                }
                if (bucketConfiguration.Port == (int)DefaultPorts.Proxy)
                {
                    var message = string.Format("Proxy port {0} is not supported by the .NET client.",
                                                bucketConfiguration.Port);
                    throw new NotSupportedException(message);
                }
                if (bucketConfiguration.UseSsl)
                {
                    bucketConfiguration.PoolConfiguration.UseSsl = true;
                }
                if (UseSsl)
                {
                    //Setting ssl to true at parent level overrides child level ssl settings
                    bucketConfiguration.UseSsl = true;
                    bucketConfiguration.Port   = SslPort;
                    bucketConfiguration.PoolConfiguration.UseSsl = true;
                }
                if (_useSslChanged)
                {
                    for (var i = 0; i < _servers.Count(); i++)
                    {
                        var useSsl = UseSsl || bucketConfiguration.UseSsl;
                        //Rewrite the URI's for bootstrapping to use SSL.
                        if (useSsl)
                        {
                            var oldUri = _servers[i];
                            var newUri = new Uri(string.Concat("https://", _servers[i].Host,
                                                               ":", HttpsMgmtPort, oldUri.PathAndQuery));
                            _servers[i] = newUri;
                        }
                    }
                }
                //operation lifespan: if it has changed at bucket level, use bucket level, else use global level
                if (_operationLifespanChanged)
                {
                    bucketConfiguration.UpdateOperationLifespanDefault(_operationLifespan);
                }
            }
        }
Пример #27
0
        /// <summary>
        /// For synchronization with App.config or Web.configs.
        /// </summary>
        /// <param name="section"></param>
        public ClientConfiguration(CouchbaseClientSection section)
        {
            Timer = TimingFactory.GetTimer(Log);

            UseSsl                = section.UseSsl;
            SslPort               = section.SslPort;
            ApiPort               = section.ApiPort;
            DirectPort            = section.DirectPort;
            MgmtPort              = section.MgmtPort;
            HttpsMgmtPort         = section.HttpsMgmtPort;
            HttpsApiPort          = section.HttpsApiPort;
            ObserveInterval       = section.ObserveInterval;
            ObserveTimeout        = section.ObserveTimeout;
            MaxViewRetries        = section.MaxViewRetries;
            ViewHardTimeout       = section.ViewHardTimeout;
            SerializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            EnableConfigHeartBeat    = section.EnableConfigHeartBeat;
            HeartbeatConfigInterval  = section.HeartbeatConfigInterval;
            ViewRequestTimeout       = section.ViewRequestTimeout;
            Expect100Continue        = section.Expect100Continue;
            EnableOperationTiming    = section.EnableOperationTiming;
            PoolConfiguration        = new PoolConfiguration(this);
            DefaultOperationLifespan = section.OperationLifespan;

            //transcoders, converters, and serializers...o mai.
            Serializer = SerializerFactory.GetSerializer(this, section.Serializer);
            Converter  = ConverterFactory.GetConverter(section.Converter);
            Transcoder = TranscoderFactory.GetTranscoder(this, section.Transcoder);

            //to enable tcp keep-alives
            EnableTcpKeepAlives  = section.EnableTcpKeepAlives;
            TcpKeepAliveInterval = section.TcpKeepAliveInterval;
            TcpKeepAliveTime     = section.TcpKeepAliveTime;

            var keepAlivesChanged = EnableTcpKeepAlives != true ||
                                    TcpKeepAliveInterval != 1000 ||
                                    TcpKeepAliveTime != 2 * 60 * 60 * 1000;

            foreach (var server in section.Servers)
            {
                Servers.Add(((UriElement)server).Uri);
                _serversChanged = true;
            }

            BucketConfigs = new Dictionary <string, BucketConfiguration>();
            foreach (var bucketElement in section.Buckets)
            {
                var bucket = (BucketElement)bucketElement;
                var bucketConfiguration = new BucketConfiguration
                {
                    BucketName               = bucket.Name,
                    UseSsl                   = bucket.UseSsl,
                    Password                 = bucket.Password,
                    ObserveInterval          = bucket.ObserveInterval,
                    DefaultOperationLifespan = bucket.OperationLifespan ?? (uint)DefaultOperationLifespan,
                    ObserveTimeout           = bucket.ObserveTimeout,
                    PoolConfiguration        = new PoolConfiguration
                    {
                        MaxSize              = bucket.ConnectionPool.MaxSize,
                        MinSize              = bucket.ConnectionPool.MinSize,
                        WaitTimeout          = bucket.ConnectionPool.WaitTimeout,
                        ShutdownTimeout      = bucket.ConnectionPool.ShutdownTimeout,
                        UseSsl               = bucket.ConnectionPool.UseSsl,
                        BufferSize           = bucket.ConnectionPool.BufferSize,
                        BufferAllocator      = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                        ConnectTimeout       = bucket.ConnectionPool.ConnectTimeout,
                        SendTimeout          = bucket.ConnectionPool.SendTimeout,
                        EnableTcpKeepAlives  = keepAlivesChanged ? EnableTcpKeepAlives : bucket.ConnectionPool.EnableTcpKeepAlives,
                        TcpKeepAliveInterval = keepAlivesChanged ? TcpKeepAliveInterval : bucket.ConnectionPool.TcpKeepAliveInterval,
                        TcpKeepAliveTime     = keepAlivesChanged ? TcpKeepAliveTime : bucket.ConnectionPool.TcpKeepAliveTime,
                        CloseAttemptInterval = bucket.ConnectionPool.CloseAttemptInterval,
                        MaxCloseAttempts     = bucket.ConnectionPool.MaxCloseAttempts,
                        ClientConfiguration  = this
                    }
                };
                BucketConfigs.Add(bucket.Name, bucketConfiguration);
            }

            //Set back to default
            _operationLifespanChanged = false;
            _poolConfigurationChanged = false;
        }
 /// <summary>
 /// CTOR for testing/dependency injection.
 /// </summary>
 /// <param name="configuration">The <see cref="PoolConfiguration"/> to use.</param>
 /// <param name="endPoint">The <see cref="IPEndPoint"/> of the Couchbase Server.</param>
 /// <param name="factory">A functory for creating <see cref="IConnection"/> objects./></param>
 public DefaultConnectionPool(PoolConfiguration configuration, IPEndPoint endPoint, Func<IConnectionPool, IConnection> factory)
 {
     _configuration = configuration;
     _factory = factory;
     EndPoint = endPoint;
 }
        public ClientConfiguration()
        {
            //For operation timing
            Timer = TimingFactory.GetTimer();
            QueryRequestTimeout = Defaults.QueryRequestTimeout;
            EnableQueryTiming   = Defaults.EnableQueryTiming;
            UseSsl          = Defaults.UseSsl;
            SslPort         = (int)Defaults.SslPort;
            ApiPort         = (int)Defaults.ApiPort;
            DirectPort      = (int)Defaults.DirectPort;
            MgmtPort        = (int)Defaults.MgmtPort;
            HttpsMgmtPort   = (int)Defaults.HttpsMgmtPort;
            HttpsApiPort    = (int)Defaults.HttpsApiPort;
            ObserveInterval = (int)Defaults.ObserveInterval; //ms
            ObserveTimeout  = (int)Defaults.ObserveTimeout;  //ms
            MaxViewRetries  = (int)Defaults.MaxViewRetries;
#pragma warning disable 618
            ViewHardTimeout = (int)Defaults.ViewHardTimeout;            //ms
#pragma warning restore 618
            HeartbeatConfigInterval = Defaults.HeartbeatConfigInterval; //ms
            EnableConfigHeartBeat   = Defaults.EnableConfigHeartBeat;
#pragma warning disable 618
            SerializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
#pragma warning restore 618
            ViewRequestTimeout    = (int)Defaults.ViewRequestTimeout; //ms
            SearchRequestTimeout  = Defaults.SearchRequestTimeout;
            VBucketRetrySleepTime = Defaults.VBucketRetrySleepTime;

            //service point settings
            DefaultConnectionLimit  = Defaults.DefaultConnectionLimit; //connections
            Expect100Continue       = Defaults.Expect100Continue;
            MaxServicePointIdleTime = (int)Defaults.MaxServicePointIdleTime;

            EnableOperationTiming    = Defaults.EnableOperationTiming;
            BufferSize               = (int)Defaults.BufferSize;
            DefaultOperationLifespan = Defaults.DefaultOperationLifespan;//ms
            EnableTcpKeepAlives      = Defaults.EnableTcpKeepAlives;
            QueryFailedThreshold     = (int)Defaults.QueryFailedThreshold;

            TcpKeepAliveTime     = Defaults.TcpKeepAliveTime;
            TcpKeepAliveInterval = Defaults.TcpKeepAliveInterval;

            NodeAvailableCheckInterval = Defaults.NodeAvailableCheckInterval;//ms
            IOErrorCheckInterval       = Defaults.IOErrorCheckInterval;
            IOErrorThreshold           = Defaults.IOErrorThreshold;
            EnableDeadServiceUriPing   = Defaults.EnableDeadServiceUriPing;

            //the default serializer
            Serializer = SerializerFactory.GetSerializer();

            //the default byte converter
            Converter = ConverterFactory.GetConverter();

            //the default transcoder
            Transcoder = TranscoderFactory.GetTranscoder(this);

            //the default ioservice
            IOServiceCreator = IOServiceFactory.GetFactory(this);

            //the default connection pool creator
            ConnectionPoolCreator = ConnectionPoolFactory.GetFactory();

            //The default sasl mechanism creator
            CreateSaslMechanism = SaslFactory.GetFactory();

#if NETSTANDARD
            LoggerFactory = new LoggerFactory();
#endif

            PoolConfiguration = new PoolConfiguration(this)
            {
                BufferSize      = BufferSize,
                BufferAllocator = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize)
            };

            BucketConfigs = new Dictionary <string, BucketConfiguration>
            {
                { DefaultBucket, new BucketConfiguration
                  {
                      PoolConfiguration = PoolConfiguration,
                  } }
            };
            Servers = new List <Uri> {
                Defaults.Server
            };

            //Set back to default
            _operationLifespanChanged = false;
            _serversChanged           = false;
            _poolConfigurationChanged = false;
        }
        /// <summary>
        /// For synchronization with App.config or Web.configs.
        /// </summary>
        /// <param name="definition"></param>
        public ClientConfiguration(ICouchbaseClientDefinition definition)
        {
            Timer = TimingFactory.GetTimer();
            UseConnectionPooling       = definition.UseConnectionPooling;
            EnableDeadServiceUriPing   = definition.EnableDeadServiceUriPing;
            NodeAvailableCheckInterval = definition.NodeAvailableCheckInterval;
            UseSsl          = definition.UseSsl;
            SslPort         = definition.SslPort;
            ApiPort         = definition.ApiPort;
            DirectPort      = definition.DirectPort;
            MgmtPort        = definition.MgmtPort;
            HttpsMgmtPort   = definition.HttpsMgmtPort;
            HttpsApiPort    = definition.HttpsApiPort;
            ObserveInterval = definition.ObserveInterval;
            ObserveTimeout  = definition.ObserveTimeout;
            MaxViewRetries  = definition.MaxViewRetries;
#pragma warning disable 618
            ViewHardTimeout       = definition.ViewHardTimeout;
            SerializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
#pragma warning restore 618
            EnableConfigHeartBeat    = definition.EnableConfigHeartBeat;
            HeartbeatConfigInterval  = definition.HeartbeatConfigInterval;
            ViewRequestTimeout       = definition.ViewRequestTimeout;
            Expect100Continue        = definition.Expect100Continue;
            DefaultConnectionLimit   = definition.DefaultConnectionLimit;
            MaxServicePointIdleTime  = definition.MaxServicePointIdleTime;
            EnableOperationTiming    = definition.EnableOperationTiming;
            DefaultOperationLifespan = definition.OperationLifespan;
            QueryFailedThreshold     = definition.QueryFailedThreshold;
            QueryRequestTimeout      = definition.QueryRequestTimeout;
            EnableQueryTiming        = definition.EnableQueryTiming;
            SearchRequestTimeout     = definition.SearchRequestTimeout;
            VBucketRetrySleepTime    = definition.VBucketRetrySleepTime;

            IOErrorCheckInterval = definition.IOErrorCheckInterval;
            IOErrorThreshold     = definition.IOErrorThreshold;

            //transcoders, converters, and serializers...o mai.
            Serializer = definition.Serializer != null
                ? SerializerFactory.GetSerializer(definition.Serializer)
                : SerializerFactory.GetSerializer();

            Converter = definition.Converter != null
                ? ConverterFactory.GetConverter(definition.Converter)
                : ConverterFactory.GetConverter();

            Transcoder = definition.Transcoder != null
                ? TranscoderFactory.GetTranscoder(this, definition.Transcoder)
                : TranscoderFactory.GetTranscoder(this);

            IOServiceCreator = definition.IOService != null
                ? IOServiceFactory.GetFactory(definition.IOService)
                : IOServiceFactory.GetFactory(this);

#if NETSTANDARD
            //TODO not implemented for json configs...yet, so default
            LoggerFactory = new LoggerFactory();
#endif

            //to enable tcp keep-alives
            EnableTcpKeepAlives  = definition.EnableTcpKeepAlives;
            TcpKeepAliveInterval = definition.TcpKeepAliveInterval;
            TcpKeepAliveTime     = definition.TcpKeepAliveTime;

            var keepAlivesChanged = EnableTcpKeepAlives != true ||
                                    TcpKeepAliveInterval != 1000 ||
                                    TcpKeepAliveTime != 2 * 60 * 60 * 1000;

            //The default sasl mechanism creator
            CreateSaslMechanism = SaslFactory.GetFactory();

            //NOTE: this is a global setting and applies to all instances
            IgnoreRemoteCertificateNameMismatch = definition.IgnoreRemoteCertificateNameMismatch;

            UseInterNetworkV6Addresses = definition.UseInterNetworkV6Addresses;

            List <Uri> servers;
            if (!string.IsNullOrEmpty(definition.ServerResolverType))
            {
                servers = ServerResolverUtil.GetServers(definition.ServerResolverType);
            }
            else if (definition.Servers != null && definition.Servers.Any())
            {
                servers = definition.Servers.ToList();
            }
            else
            {
                servers = new List <Uri> {
                    Defaults.Server
                };
            }

            Servers         = servers;
            _serversChanged = true;

            if (definition.ConnectionPool != null)
            {
                ConnectionPoolCreator = definition.ConnectionPool.Type != null
                    ? ConnectionPoolFactory.GetFactory(definition.ConnectionPool.Type)
                    : ConnectionPoolFactory.GetFactory();

                PoolConfiguration = new PoolConfiguration
                {
                    MaxSize             = definition.ConnectionPool.MaxSize,
                    MinSize             = definition.ConnectionPool.MinSize,
                    WaitTimeout         = definition.ConnectionPool.WaitTimeout,
                    ShutdownTimeout     = definition.ConnectionPool.ShutdownTimeout,
                    UseSsl              = UseSsl ? UseSsl : definition.ConnectionPool.UseSsl,
                    BufferSize          = definition.ConnectionPool.BufferSize,
                    BufferAllocator     = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                    ConnectTimeout      = definition.ConnectionPool.ConnectTimeout,
                    SendTimeout         = definition.ConnectionPool.SendTimeout,
                    EnableTcpKeepAlives =
                        keepAlivesChanged ? EnableTcpKeepAlives : definition.ConnectionPool.EnableTcpKeepAlives,
                    TcpKeepAliveInterval =
                        keepAlivesChanged ? TcpKeepAliveInterval : definition.ConnectionPool.TcpKeepAliveInterval,
                    TcpKeepAliveTime     = keepAlivesChanged ? TcpKeepAliveTime : definition.ConnectionPool.TcpKeepAliveTime,
                    CloseAttemptInterval = definition.ConnectionPool.CloseAttemptInterval,
                    MaxCloseAttempts     = definition.ConnectionPool.MaxCloseAttempts,
                    ClientConfiguration  = this
                };
            }
            else
            {
                ConnectionPoolCreator = ConnectionPoolFactory.GetFactory();
                PoolConfiguration     = new PoolConfiguration(this);
            }

            BucketConfigs = new Dictionary <string, BucketConfiguration>();
            if (definition.Buckets != null)
            {
                foreach (var bucket in definition.Buckets)
                {
                    var bucketConfiguration = new BucketConfiguration
                    {
                        BucketName               = bucket.Name,
                        UseSsl                   = bucket.UseSsl,
                        Password                 = bucket.Password,
                        ObserveInterval          = bucket.ObserveInterval,
                        DefaultOperationLifespan = bucket.OperationLifespan ?? (uint)DefaultOperationLifespan,
                        ObserveTimeout           = bucket.ObserveTimeout,
                        UseEnhancedDurability    = bucket.UseEnhancedDurability
                    };

                    //By skipping the bucket specific connection pool settings we allow inheritance from clien-wide connection pool settings.
                    if (bucket.ConnectionPool != null)
                    {
                        bucketConfiguration.PoolConfiguration = new PoolConfiguration
                        {
                            MaxSize             = bucket.ConnectionPool.MaxSize,
                            MinSize             = bucket.ConnectionPool.MinSize,
                            WaitTimeout         = bucket.ConnectionPool.WaitTimeout,
                            ShutdownTimeout     = bucket.ConnectionPool.ShutdownTimeout,
                            UseSsl              = bucket.ConnectionPool.UseSsl,
                            BufferSize          = bucket.ConnectionPool.BufferSize,
                            BufferAllocator     = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                            ConnectTimeout      = bucket.ConnectionPool.ConnectTimeout,
                            SendTimeout         = bucket.ConnectionPool.SendTimeout,
                            EnableTcpKeepAlives =
                                keepAlivesChanged ? EnableTcpKeepAlives : bucket.ConnectionPool.EnableTcpKeepAlives,
                            TcpKeepAliveInterval =
                                keepAlivesChanged ? TcpKeepAliveInterval : bucket.ConnectionPool.TcpKeepAliveInterval,
                            TcpKeepAliveTime =
                                keepAlivesChanged ? TcpKeepAliveTime : bucket.ConnectionPool.TcpKeepAliveTime,
                            CloseAttemptInterval  = bucket.ConnectionPool.CloseAttemptInterval,
                            MaxCloseAttempts      = bucket.ConnectionPool.MaxCloseAttempts,
                            UseEnhancedDurability = bucket.UseEnhancedDurability,
                            ClientConfiguration   = this
                        };
                    }
                    else
                    {
                        bucketConfiguration.PoolConfiguration        = PoolConfiguration;
                        bucketConfiguration.PoolConfiguration.UseSsl = bucketConfiguration.UseSsl;
                        bucketConfiguration.PoolConfiguration.UseEnhancedDurability = bucketConfiguration.UseEnhancedDurability;
                    }
                    BucketConfigs.Add(bucket.Name, bucketConfiguration);
                }
            }

            //Set back to default
            _operationLifespanChanged = false;
            _poolConfigurationChanged = false;
        }
        internal void Initialize()
        {
#if NETSTANDARD
            //configure logging
            LogManager.ConfigureLoggerFactory(LoggerFactory);
#endif
            if (PoolConfiguration == null)
            {
                PoolConfiguration = new PoolConfiguration(this);
            }
            if (PoolConfiguration.ClientConfiguration == null)
            {
                PoolConfiguration.ClientConfiguration = this;
            }
            if (TcpKeepAliveTime != Defaults.TcpKeepAliveTime &&
                PoolConfiguration.TcpKeepAliveTime == Defaults.TcpKeepAliveTime)
            {
                PoolConfiguration.TcpKeepAliveTime = TcpKeepAliveTime;
            }
            if (TcpKeepAliveInterval != Defaults.TcpKeepAliveInterval &&
                PoolConfiguration.TcpKeepAliveInterval == Defaults.TcpKeepAliveInterval)
            {
                PoolConfiguration.TcpKeepAliveInterval = TcpKeepAliveInterval;
            }
            if (EnableTcpKeepAlives != Defaults.EnableTcpKeepAlives &&
                PoolConfiguration.EnableTcpKeepAlives == Defaults.EnableTcpKeepAlives)
            {
                PoolConfiguration.EnableTcpKeepAlives = EnableTcpKeepAlives;
            }

            if (_serversChanged)
            {
                for (var i = 0; i < _servers.Count(); i++)
                {
                    if (!_servers[i].OriginalString.EndsWith("/pools") || _servers[i].Port == 80)
                    {
                        var builder = new UriBuilder(_servers[i])
                        {
                            Port = _servers[i].Port == 80 ? 8091 : _servers[i].Port,
                            Path = _servers[i].OriginalString.EndsWith("/") ? "pools" : "/pools"
                        };
                        _servers[i] = builder.Uri;
                    }
                }
            }

            //Update the bucket configs
            foreach (var keyValue in BucketConfigs)
            {
                var bucketConfiguration = keyValue.Value;
                if (string.IsNullOrEmpty(bucketConfiguration.BucketName))
                {
                    if (string.IsNullOrWhiteSpace(keyValue.Key))
                    {
                        throw new ArgumentException("bucketConfiguration.BucketName is null or empty.");
                    }
                    bucketConfiguration.BucketName = keyValue.Key;
                }
                if (bucketConfiguration.PoolConfiguration == null || _poolConfigurationChanged)
                {
                    bucketConfiguration.PoolConfiguration = PoolConfiguration;
                }
                if (bucketConfiguration.Servers == null || HasServersChanged())
                {
                    bucketConfiguration.Servers = Servers.Select(x => x).ToList();
                }
                if (bucketConfiguration.Servers.Count == 0)
                {
                    bucketConfiguration.Servers.AddRange(Servers.Select(x => x).ToList());
                }
                if (bucketConfiguration.Port == (int)DefaultPorts.Proxy)
                {
                    var message = string.Format("Proxy port {0} is not supported by the .NET client.",
                                                bucketConfiguration.Port);
                    throw new NotSupportedException(message);
                }
                if (bucketConfiguration.UseSsl)
                {
                    bucketConfiguration.PoolConfiguration.UseSsl = true;
                }
                if (UseSsl)
                {
                    //Setting ssl to true at parent level overrides child level ssl settings
                    bucketConfiguration.UseSsl = true;
                    bucketConfiguration.Port   = SslPort;
                    bucketConfiguration.PoolConfiguration.UseSsl = true;
                }
                if (_useSslChanged)
                {
                    for (var i = 0; i < _servers.Count(); i++)
                    {
                        var useSsl = UseSsl || bucketConfiguration.UseSsl;
                        //Rewrite the URI's for bootstrapping to use SSL.
                        if (useSsl)
                        {
                            var oldUri = _servers[i];
                            var newUri = new Uri(string.Concat("https://", _servers[i].Host,
                                                               ":", HttpsMgmtPort, oldUri.PathAndQuery));
                            _servers[i] = newUri;
                        }
                    }
                }
                //operation lifespan: if it has changed at bucket level, use bucket level, else use global level
                if (_operationLifespanChanged)
                {
                    bucketConfiguration.UpdateOperationLifespanDefault(_operationLifespan);
                }
            }
        }
        public void When_Connecting_To_Good_IP_Connection_Succeeds_Before_ConnectTimeout()
        {
            const int connectionTimedOut = 10060;
            string ipThatDoesExist = ConfigurationManager.AppSettings["OperationTestAddress"];
            var ipEndpoint = UriExtensions.GetEndPoint(ipThatDoesExist);
            var connectionPoolConfig = new PoolConfiguration
            {
                ConnectTimeout = 5000 //set really low for test
            };
            var connectionPool = new ConnectionPool<Connection>(connectionPoolConfig, ipEndpoint);

            IConnection connection = null;
            var stopWatch = new Stopwatch();
            try
            {
                stopWatch.Start();
                connection = connectionPool.Acquire();
            }
            catch (SocketException e)
            {
                Assert.AreEqual(connectionTimedOut, e.ErrorCode);
            }
            finally
            {
                stopWatch.Stop();
                Assert.IsNotNull(connection);
                Assert.IsTrue(connection.Socket.Connected);
                connection.Dispose();
            }
        }
        /// <summary>
        /// For synchronization with App.config or Web.configs.
        /// </summary>
        /// <param name="section"></param>
        public ClientConfiguration(CouchbaseClientSection section)
        {
            Timer = TimingFactory.GetTimer(Log);
            NodeAvailableCheckInterval = section.NodeAvailableCheckInterval;
            UseSsl                = section.UseSsl;
            SslPort               = section.SslPort;
            ApiPort               = section.ApiPort;
            DirectPort            = section.DirectPort;
            MgmtPort              = section.MgmtPort;
            HttpsMgmtPort         = section.HttpsMgmtPort;
            HttpsApiPort          = section.HttpsApiPort;
            ObserveInterval       = section.ObserveInterval;
            ObserveTimeout        = section.ObserveTimeout;
            MaxViewRetries        = section.MaxViewRetries;
            ViewHardTimeout       = section.ViewHardTimeout;
            SerializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            EnableConfigHeartBeat    = section.EnableConfigHeartBeat;
            HeartbeatConfigInterval  = section.HeartbeatConfigInterval;
            ViewRequestTimeout       = section.ViewRequestTimeout;
            Expect100Continue        = section.Expect100Continue;
            EnableOperationTiming    = section.EnableOperationTiming;
            DefaultOperationLifespan = section.OperationLifespan;
            QueryRequestTimeout      = section.QueryRequestTimeout;
            IOErrorCheckInterval     = section.IOErrorCheckInterval;
            IOErrorThreshold         = section.IOErrorThreshold;

            //transcoders, converters, and serializers...o mai.
            Serializer = SerializerFactory.GetSerializer(this, section.Serializer);
            Converter  = ConverterFactory.GetConverter(section.Converter);
            Transcoder = TranscoderFactory.GetTranscoder(this, section.Transcoder);

            //to enable tcp keep-alives
            EnableTcpKeepAlives  = section.EnableTcpKeepAlives;
            TcpKeepAliveInterval = section.TcpKeepAliveInterval;
            TcpKeepAliveTime     = section.TcpKeepAliveTime;

            var keepAlivesChanged = EnableTcpKeepAlives != true ||
                                    TcpKeepAliveInterval != 1000 ||
                                    TcpKeepAliveTime != 2 * 60 * 60 * 1000;

            foreach (var server in section.Servers)
            {
                Servers.Add(((UriElement)server).Uri);
                _serversChanged = true;
            }

            PoolConfiguration = new PoolConfiguration
            {
                MaxSize              = section.ConnectionPool.MaxSize,
                MinSize              = section.ConnectionPool.MinSize,
                WaitTimeout          = section.ConnectionPool.WaitTimeout,
                ShutdownTimeout      = section.ConnectionPool.ShutdownTimeout,
                UseSsl               = section.ConnectionPool.UseSsl,
                BufferSize           = section.ConnectionPool.BufferSize,
                BufferAllocator      = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                ConnectTimeout       = section.ConnectionPool.ConnectTimeout,
                SendTimeout          = section.ConnectionPool.SendTimeout,
                EnableTcpKeepAlives  = keepAlivesChanged ? EnableTcpKeepAlives : section.ConnectionPool.EnableTcpKeepAlives,
                TcpKeepAliveInterval = keepAlivesChanged ? TcpKeepAliveInterval : section.ConnectionPool.TcpKeepAliveInterval,
                TcpKeepAliveTime     = keepAlivesChanged ? TcpKeepAliveTime : section.ConnectionPool.TcpKeepAliveTime,
                CloseAttemptInterval = section.ConnectionPool.CloseAttemptInterval,
                MaxCloseAttempts     = section.ConnectionPool.MaxCloseAttempts,
                ClientConfiguration  = this
            };

            BucketConfigs = new Dictionary <string, BucketConfiguration>();
            foreach (var bucketElement in section.Buckets)
            {
                var bucket = (BucketElement)bucketElement;
                var bucketConfiguration = new BucketConfiguration
                {
                    BucketName               = bucket.Name,
                    UseSsl                   = bucket.UseSsl,
                    Password                 = bucket.Password,
                    ObserveInterval          = bucket.ObserveInterval,
                    DefaultOperationLifespan = bucket.OperationLifespan ?? (uint)DefaultOperationLifespan,
                    ObserveTimeout           = bucket.ObserveTimeout,
                    UseEnhancedDurability    = bucket.UseEnhancedDurability
                };
                //Configuration properties (including elements) can not be null, but we can check if it was originally presnt in xml and skip it.
                //By skipping the bucket specific connection pool settings we allow inheritance from clien-wide connection pool settings.
                if (bucket.ConnectionPool.ElementInformation.IsPresent)
                {
                    bucketConfiguration.PoolConfiguration = new PoolConfiguration
                    {
                        MaxSize             = bucket.ConnectionPool.MaxSize,
                        MinSize             = bucket.ConnectionPool.MinSize,
                        WaitTimeout         = bucket.ConnectionPool.WaitTimeout,
                        ShutdownTimeout     = bucket.ConnectionPool.ShutdownTimeout,
                        UseSsl              = bucket.ConnectionPool.UseSsl,
                        BufferSize          = bucket.ConnectionPool.BufferSize,
                        BufferAllocator     = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                        ConnectTimeout      = bucket.ConnectionPool.ConnectTimeout,
                        SendTimeout         = bucket.ConnectionPool.SendTimeout,
                        EnableTcpKeepAlives =
                            keepAlivesChanged ? EnableTcpKeepAlives : bucket.ConnectionPool.EnableTcpKeepAlives,
                        TcpKeepAliveInterval =
                            keepAlivesChanged ? TcpKeepAliveInterval : bucket.ConnectionPool.TcpKeepAliveInterval,
                        TcpKeepAliveTime      = keepAlivesChanged ? TcpKeepAliveTime : bucket.ConnectionPool.TcpKeepAliveTime,
                        CloseAttemptInterval  = bucket.ConnectionPool.CloseAttemptInterval,
                        MaxCloseAttempts      = bucket.ConnectionPool.MaxCloseAttempts,
                        UseEnhancedDurability = bucket.UseEnhancedDurability,
                        ClientConfiguration   = this
                    };
                }
                else
                {
                    bucketConfiguration.PoolConfiguration = PoolConfiguration;
                }
                BucketConfigs.Add(bucket.Name, bucketConfiguration);
            }

            //Set back to default
            _operationLifespanChanged = false;
            _poolConfigurationChanged = false;
        }
        /// <summary>
        /// For synchronization with App.config or Web.configs.
        /// </summary>
        /// <param name="definition"></param>
        public ClientConfiguration(ICouchbaseClientDefinition definition, ILoggerFactory loggerFactory)
        {
            _loggerFactory = loggerFactory;
            Log = _loggerFactory.CreateLogger<ClientConfiguration>();
            Timer = TimingFactory.GetTimer(_loggerFactory);
            NodeAvailableCheckInterval = definition.NodeAvailableCheckInterval;
            UseSsl = definition.UseSsl;
            SslPort = definition.SslPort;
            ApiPort = definition.ApiPort;
            DirectPort = definition.DirectPort;
            MgmtPort = definition.MgmtPort;
            HttpsMgmtPort = definition.HttpsMgmtPort;
            HttpsApiPort = definition.HttpsApiPort;
            ObserveInterval = definition.ObserveInterval;
            ObserveTimeout = definition.ObserveTimeout;
            MaxViewRetries = definition.MaxViewRetries;
            ViewHardTimeout = definition.ViewHardTimeout;
            SerializationSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            DeserializationSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            EnableConfigHeartBeat = definition.EnableConfigHeartBeat;
            HeartbeatConfigInterval = definition.HeartbeatConfigInterval;
            ViewRequestTimeout = definition.ViewRequestTimeout;
            Expect100Continue = definition.Expect100Continue;
            DefaultConnectionLimit = definition.DefaultConnectionLimit;
            MaxServicePointIdleTime = definition.MaxServicePointIdleTime;
            EnableOperationTiming = definition.EnableOperationTiming;
            DefaultOperationLifespan = definition.OperationLifespan;
            QueryRequestTimeout = definition.QueryRequestTimeout;
            SearchRequestTimeout = definition.SearchRequestTimeout;

            IOErrorCheckInterval = definition.IOErrorCheckInterval;
            IOErrorThreshold = definition.IOErrorThreshold;

            //transcoders, converters, and serializers...o mai.
            Serializer = definition.Serializer != null
                ? SerializerFactory.GetSerializer(definition.Serializer)
                : SerializerFactory.GetSerializer();
            Converter = definition.Converter != null
                ? ConverterFactory.GetConverter(definition.Converter)
                : ConverterFactory.GetConverter();
            Transcoder = definition.Transcoder != null
                ? TranscoderFactory.GetTranscoder(this, definition.Transcoder)
                : TranscoderFactory.GetTranscoder(this);
            IOServiceCreator = definition.IOService != null
                ? IOServiceFactory.GetFactory(definition.IOService)
                : IOServiceFactory.GetFactory();

            //to enable tcp keep-alives
            EnableTcpKeepAlives = definition.EnableTcpKeepAlives;
            TcpKeepAliveInterval = definition.TcpKeepAliveInterval;
            TcpKeepAliveTime = definition.TcpKeepAliveTime;

            var keepAlivesChanged = EnableTcpKeepAlives != true ||
                                    TcpKeepAliveInterval != 1000 ||
                                    TcpKeepAliveTime != 2*60*60*1000;

            //The default sasl mechanism creator
            CreateSaslMechanism = SaslFactory.GetFactory(_loggerFactory);

            //NOTE: this is a global setting and applies to all instances
            IgnoreRemoteCertificateNameMismatch = definition.IgnoreRemoteCertificateNameMismatch;

            UseInterNetworkV6Addresses = definition.UseInterNetworkV6Addresses;

            foreach (var server in definition.Servers ?? new[] { Defaults.Server })
            {
                Servers.Add(server);
                _serversChanged = true;
            }

            if (definition.ConnectionPool != null)
            {
                ConnectionPoolCreator = definition.ConnectionPool.Type != null
                    ? ConnectionPoolFactory.GetFactory(definition.ConnectionPool.Type)
                    : ConnectionPoolFactory.GetFactory(_loggerFactory);

                PoolConfiguration = new PoolConfiguration
                {
                    MaxSize = definition.ConnectionPool.MaxSize,
                    MinSize = definition.ConnectionPool.MinSize,
                    WaitTimeout = definition.ConnectionPool.WaitTimeout,
                    ShutdownTimeout = definition.ConnectionPool.ShutdownTimeout,
                    UseSsl = UseSsl ? UseSsl : definition.ConnectionPool.UseSsl,
                    BufferSize = definition.ConnectionPool.BufferSize,
                    BufferAllocator = (p) => new BufferAllocator(p.MaxSize*p.BufferSize, p.BufferSize, _loggerFactory),
                    ConnectTimeout = definition.ConnectionPool.ConnectTimeout,
                    SendTimeout = definition.ConnectionPool.SendTimeout,
                    EnableTcpKeepAlives =
                        keepAlivesChanged ? EnableTcpKeepAlives : definition.ConnectionPool.EnableTcpKeepAlives,
                    TcpKeepAliveInterval =
                        keepAlivesChanged ? TcpKeepAliveInterval : definition.ConnectionPool.TcpKeepAliveInterval,
                    TcpKeepAliveTime = keepAlivesChanged ? TcpKeepAliveTime : definition.ConnectionPool.TcpKeepAliveTime,
                    CloseAttemptInterval = definition.ConnectionPool.CloseAttemptInterval,
                    MaxCloseAttempts = definition.ConnectionPool.MaxCloseAttempts,
                    ClientConfiguration = this
                };
            }
            else
            {
                ConnectionPoolCreator = ConnectionPoolFactory.GetFactory(_loggerFactory);
                PoolConfiguration = new PoolConfiguration(_loggerFactory, this);
            }

            BucketConfigs = new Dictionary<string, BucketConfiguration>();
            if (definition.Buckets != null)
            {
                foreach (var bucket in definition.Buckets)
                {
                    var bucketConfiguration = new BucketConfiguration
                    {
                        BucketName = bucket.Name,
                        UseSsl = bucket.UseSsl,
                        Password = bucket.Password,
                        ObserveInterval = bucket.ObserveInterval,
                        DefaultOperationLifespan = bucket.OperationLifespan ?? (uint) DefaultOperationLifespan,
                        ObserveTimeout = bucket.ObserveTimeout,
                        UseEnhancedDurability = bucket.UseEnhancedDurability
                    };

                    //By skipping the bucket specific connection pool settings we allow inheritance from clien-wide connection pool settings.
                    if (bucket.ConnectionPool != null)
                    {
                        bucketConfiguration.PoolConfiguration = new PoolConfiguration
                        {
                            Log = Log,
                            MaxSize = bucket.ConnectionPool.MaxSize,
                            MinSize = bucket.ConnectionPool.MinSize,
                            WaitTimeout = bucket.ConnectionPool.WaitTimeout,
                            ShutdownTimeout = bucket.ConnectionPool.ShutdownTimeout,
                            UseSsl = bucket.ConnectionPool.UseSsl,
                            BufferSize = bucket.ConnectionPool.BufferSize,
                            BufferAllocator = (p) => new BufferAllocator(p.MaxSize*p.BufferSize, p.BufferSize, _loggerFactory),
                            ConnectTimeout = bucket.ConnectionPool.ConnectTimeout,
                            SendTimeout = bucket.ConnectionPool.SendTimeout,
                            EnableTcpKeepAlives =
                                keepAlivesChanged ? EnableTcpKeepAlives : bucket.ConnectionPool.EnableTcpKeepAlives,
                            TcpKeepAliveInterval =
                                keepAlivesChanged ? TcpKeepAliveInterval : bucket.ConnectionPool.TcpKeepAliveInterval,
                            TcpKeepAliveTime =
                                keepAlivesChanged ? TcpKeepAliveTime : bucket.ConnectionPool.TcpKeepAliveTime,
                            CloseAttemptInterval = bucket.ConnectionPool.CloseAttemptInterval,
                            MaxCloseAttempts = bucket.ConnectionPool.MaxCloseAttempts,
                            UseEnhancedDurability = bucket.UseEnhancedDurability,
                            ClientConfiguration = this
                        };
                    }
                    else
                    {
                        bucketConfiguration.PoolConfiguration = PoolConfiguration;
                        bucketConfiguration.PoolConfiguration.UseSsl = bucketConfiguration.UseSsl;
                        bucketConfiguration.PoolConfiguration.UseEnhancedDurability = bucketConfiguration.UseEnhancedDurability;
                    }
                    BucketConfigs.Add(bucket.Name, bucketConfiguration);
                }
            }

            //Set back to default
            _operationLifespanChanged = false;
            _poolConfigurationChanged = false;
        }
        public ClientConfiguration(ILoggerFactory loggerFactory)
        {
            _loggerFactory = loggerFactory;
            Log = _loggerFactory.CreateLogger<ClientConfiguration>();
            //For operation timing
            Timer = TimingFactory.GetTimer(_loggerFactory);

            QueryRequestTimeout = Defaults.QueryRequestTimeout;
            UseSsl = Defaults.UseSsl;
            SslPort = (int) Defaults.SslPort;
            ApiPort = (int) Defaults.ApiPort;
            DirectPort = (int) Defaults.DirectPort;
            MgmtPort = (int) Defaults.MgmtPort;
            HttpsMgmtPort = (int) Defaults.HttpsMgmtPort;
            HttpsApiPort = (int) Defaults.HttpsApiPort;
            ObserveInterval = (int) Defaults.ObserveInterval; //ms
            ObserveTimeout = (int) Defaults.ObserveTimeout; //ms
            MaxViewRetries = (int) Defaults.MaxViewRetries;
            ViewHardTimeout = (int) Defaults.ViewHardTimeout; //ms
            HeartbeatConfigInterval = Defaults.HeartbeatConfigInterval; //ms
            EnableConfigHeartBeat = Defaults.EnableConfigHeartBeat;
            SerializationSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            DeserializationSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            ViewRequestTimeout = (int) Defaults.ViewRequestTimeout; //ms
            SearchRequestTimeout = Defaults.SearchRequestTimeout;

            //service point settings
            DefaultConnectionLimit = Defaults.DefaultConnectionLimit; //connections
            Expect100Continue = Defaults.Expect100Continue;
            MaxServicePointIdleTime = (int) Defaults.MaxServicePointIdleTime;

            EnableOperationTiming = Defaults.EnableOperationTiming;
            BufferSize = (int) Defaults.BufferSize;
            DefaultOperationLifespan = Defaults.DefaultOperationLifespan;//ms
            EnableTcpKeepAlives = Defaults.EnableTcpKeepAlives;
            QueryFailedThreshold = (int) Defaults.QueryFailedThreshold;

            TcpKeepAliveTime = Defaults.TcpKeepAliveTime;
            TcpKeepAliveInterval = Defaults.TcpKeepAliveInterval;

            NodeAvailableCheckInterval = Defaults.NodeAvailableCheckInterval;//ms
            IOErrorCheckInterval = Defaults.IOErrorCheckInterval;
            IOErrorThreshold = Defaults.IOErrorThreshold;

            //the default serializer
            Serializer = SerializerFactory.GetSerializer();

            //the default byte converter
            Converter = ConverterFactory.GetConverter();

            //the default transcoder
            Transcoder = TranscoderFactory.GetTranscoder(this);

            //the default ioservice
            IOServiceCreator = IOServiceFactory.GetFactory();

            //the default connection pool creator
            ConnectionPoolCreator = ConnectionPoolFactory.GetFactory(_loggerFactory);

            //The default sasl mechanism creator
            CreateSaslMechanism = SaslFactory.GetFactory(_loggerFactory);

            PoolConfiguration = new PoolConfiguration(_loggerFactory, this)
            {
                BufferSize = BufferSize,
                BufferAllocator = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize, _loggerFactory)
            };

            BucketConfigs = new Dictionary<string, BucketConfiguration>
            {
                {DefaultBucket, new BucketConfiguration
                {
                    PoolConfiguration = PoolConfiguration,
                }}
            };
            Servers = new List<Uri> { Defaults.Server };

            //Set back to default
            _operationLifespanChanged = false;
            _serversChanged = false;
            _poolConfigurationChanged = false;
        }
        /// <summary>
        /// For synchronization with App.config or Web.configs.
        /// </summary>
        /// <param name="section"></param>
        public ClientConfiguration(CouchbaseClientSection section)
        {
            Timer = TimingFactory.GetTimer(Log);
            NodeAvailableCheckInterval = section.NodeAvailableCheckInterval;
            UseSsl = section.UseSsl;
            SslPort = section.SslPort;
            ApiPort = section.ApiPort;
            DirectPort = section.DirectPort;
            MgmtPort = section.MgmtPort;
            HttpsMgmtPort = section.HttpsMgmtPort;
            HttpsApiPort = section.HttpsApiPort;
            ObserveInterval = section.ObserveInterval;
            ObserveTimeout = section.ObserveTimeout;
            MaxViewRetries = section.MaxViewRetries;
            ViewHardTimeout = section.ViewHardTimeout;
            SerializationSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            DeserializationSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            EnableConfigHeartBeat = section.EnableConfigHeartBeat;
            HeartbeatConfigInterval = section.HeartbeatConfigInterval;
            ViewRequestTimeout = section.ViewRequestTimeout;
            Expect100Continue = section.Expect100Continue;
            DefaultConnectionLimit = section.DefaultConnectionLimit;
            MaxServicePointIdleTime = section.MaxServicePointIdleTime;
            EnableOperationTiming = section.EnableOperationTiming;
            DefaultOperationLifespan = section.OperationLifespan;
            QueryRequestTimeout = section.QueryRequestTimeout;
            IOErrorCheckInterval = section.IOErrorCheckInterval;
            IOErrorThreshold = section.IOErrorThreshold;

            //transcoders, converters, and serializers...o mai.
            Serializer = SerializerFactory.GetSerializer(this, section.Serializer);
            Converter = ConverterFactory.GetConverter(section.Converter);
            Transcoder = TranscoderFactory.GetTranscoder(this, section.Transcoder);

            //to enable tcp keep-alives
            EnableTcpKeepAlives = section.EnableTcpKeepAlives;
            TcpKeepAliveInterval = section.TcpKeepAliveInterval;
            TcpKeepAliveTime = section.TcpKeepAliveTime;

            var keepAlivesChanged = EnableTcpKeepAlives != true ||
                                    TcpKeepAliveInterval != 1000 ||
                                    TcpKeepAliveTime != 2*60*60*1000;

            //the default ioservice - this should be refactored to come from the configsection
            IOServiceCreator = IOServiceFactory.GetFactory(section.IOService);

            //the default connection pool creator
            ConnectionPoolCreator = ConnectionPoolFactory.GetFactory(section.ConnectionPool);

            //The default sasl mechanism creator
            CreateSaslMechanism = SaslFactory.GetFactory();

            foreach (var server in section.Servers)
            {
                Servers.Add(((UriElement)server).Uri);
                _serversChanged = true;
            }

            PoolConfiguration = new PoolConfiguration
            {
                MaxSize = section.ConnectionPool.MaxSize,
                MinSize = section.ConnectionPool.MinSize,
                WaitTimeout = section.ConnectionPool.WaitTimeout,
                ShutdownTimeout = section.ConnectionPool.ShutdownTimeout,
                UseSsl = UseSsl ? UseSsl : section.ConnectionPool.UseSsl,
                BufferSize = section.ConnectionPool.BufferSize,
                BufferAllocator = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize),
                ConnectTimeout = section.ConnectionPool.ConnectTimeout,
                SendTimeout = section.ConnectionPool.SendTimeout,
                EnableTcpKeepAlives = keepAlivesChanged ? EnableTcpKeepAlives : section.ConnectionPool.EnableTcpKeepAlives,
                TcpKeepAliveInterval = keepAlivesChanged ? TcpKeepAliveInterval : section.ConnectionPool.TcpKeepAliveInterval,
                TcpKeepAliveTime = keepAlivesChanged ? TcpKeepAliveTime : section.ConnectionPool.TcpKeepAliveTime,
                CloseAttemptInterval = section.ConnectionPool.CloseAttemptInterval,
                MaxCloseAttempts = section.ConnectionPool.MaxCloseAttempts,
                ClientConfiguration = this
            };

            BucketConfigs = new Dictionary<string, BucketConfiguration>();
            foreach (var bucketElement in section.Buckets)
            {
                var bucket = (BucketElement)bucketElement;
                var bucketConfiguration = new BucketConfiguration
                {
                    BucketName = bucket.Name,
                    UseSsl = bucket.UseSsl,
                    Password = bucket.Password,
                    ObserveInterval = bucket.ObserveInterval,
                    DefaultOperationLifespan = bucket.OperationLifespan ??(uint) DefaultOperationLifespan,
                    ObserveTimeout = bucket.ObserveTimeout,
                    UseEnhancedDurability = bucket.UseEnhancedDurability
                };
                //Configuration properties (including elements) can not be null, but we can check if it was originally presnt in xml and skip it.
                //By skipping the bucket specific connection pool settings we allow inheritance from clien-wide connection pool settings.
                if (bucket.ConnectionPool.ElementInformation.IsPresent)
                {
                    bucketConfiguration.PoolConfiguration = new PoolConfiguration
                    {
                        MaxSize = bucket.ConnectionPool.MaxSize,
                        MinSize = bucket.ConnectionPool.MinSize,
                        WaitTimeout = bucket.ConnectionPool.WaitTimeout,
                        ShutdownTimeout = bucket.ConnectionPool.ShutdownTimeout,
                        UseSsl = bucket.ConnectionPool.UseSsl,
                        BufferSize = bucket.ConnectionPool.BufferSize,
                        BufferAllocator = (p) => new BufferAllocator(p.MaxSize*p.BufferSize, p.BufferSize),
                        ConnectTimeout = bucket.ConnectionPool.ConnectTimeout,
                        SendTimeout = bucket.ConnectionPool.SendTimeout,
                        EnableTcpKeepAlives =
                            keepAlivesChanged ? EnableTcpKeepAlives : bucket.ConnectionPool.EnableTcpKeepAlives,
                        TcpKeepAliveInterval =
                            keepAlivesChanged ? TcpKeepAliveInterval : bucket.ConnectionPool.TcpKeepAliveInterval,
                        TcpKeepAliveTime = keepAlivesChanged ? TcpKeepAliveTime : bucket.ConnectionPool.TcpKeepAliveTime,
                        CloseAttemptInterval = bucket.ConnectionPool.CloseAttemptInterval,
                        MaxCloseAttempts = bucket.ConnectionPool.MaxCloseAttempts,
                        UseEnhancedDurability = bucket.UseEnhancedDurability,
                        ClientConfiguration = this
                    };
                }
                else
                {
                    bucketConfiguration.PoolConfiguration = PoolConfiguration;
                }
                BucketConfigs.Add(bucket.Name, bucketConfiguration);
            }

            //Set back to default
            _operationLifespanChanged = false;
            _poolConfigurationChanged = false;
        }
        public ClientConfiguration()
        {
            //For operation timing
            Timer = TimingFactory.GetTimer(Log);

            QueryRequestTimeout = 75000;
            UseSsl = false;
            SslPort = 11207;
            ApiPort = 8092;
            DirectPort = 11210;
            MgmtPort = 8091;
            HttpsMgmtPort = 18091;
            HttpsApiPort = 18092;
            ObserveInterval = 10; //ms
            ObserveTimeout = 500; //ms
            MaxViewRetries = 2;
            ViewHardTimeout = 30000; //ms
            HeartbeatConfigInterval = 10000; //ms
            EnableConfigHeartBeat = true;
            SerializationSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            DeserializationSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
            ViewRequestTimeout = 75000; //ms

            //service point settings
            DefaultConnectionLimit = 5; //connections
            Expect100Continue = false;
            MaxServicePointIdleTime = 100;

            EnableOperationTiming = false;
            BufferSize = 1024 * 16;
            DefaultOperationLifespan = 2500;//ms
            EnableTcpKeepAlives = true;
            QueryFailedThreshold = 2;

            TcpKeepAliveTime = 2*60*60*1000;
            TcpKeepAliveInterval = 1000;

            NodeAvailableCheckInterval = 1000;//ms
            IOErrorCheckInterval = 500;
            IOErrorThreshold = 10;

            //the default serializer
            Serializer = SerializerFactory.GetSerializer();

            //the default byte converter
            Converter = ConverterFactory.GetConverter();

            //the default transcoder
            Transcoder = TranscoderFactory.GetTranscoder(this);

            //the default ioservice
            IOServiceCreator = IOServiceFactory.GetFactory();

            //the default connection pool creator
            ConnectionPoolCreator = ConnectionPoolFactory.GetFactory();

            //The default sasl mechanism creator
            CreateSaslMechanism = SaslFactory.GetFactory();

            PoolConfiguration = new PoolConfiguration(this)
            {
                BufferSize = BufferSize,
                BufferAllocator = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize)
            };

            BucketConfigs = new Dictionary<string, BucketConfiguration>
            {
                {DefaultBucket, new BucketConfiguration
                {
                    PoolConfiguration = PoolConfiguration,
                }}
            };
            Servers = new List<Uri> { _defaultServer };

            //Set back to default
            _operationLifespanChanged = false;
            _serversChanged = false;
            _poolConfigurationChanged = false;
        }
 public void TestFixtureSetUp()
 {
     var ipEndpoint = UriExtensions.GetEndPoint(_address);
     var connectionPoolConfig = new PoolConfiguration();
     _connectionPool = new ConnectionPool<Connection>(connectionPoolConfig, ipEndpoint);
 }
 public DefaultConnectionPool(PoolConfiguration configuration, IPEndPoint endPoint) 
     : this(configuration, endPoint, DefaultConnectionFactory.GetDefault())
 {
 }
        public ClientConfiguration()
        {
            //For operation timing
            Timer = TimingFactory.GetTimer(Log);

            QueryRequestTimeout = 75000;
            UseSsl                  = false;
            SslPort                 = 11207;
            ApiPort                 = 8092;
            DirectPort              = 11210;
            MgmtPort                = 8091;
            HttpsMgmtPort           = 18091;
            HttpsApiPort            = 18092;
            ObserveInterval         = 10;    //ms
            ObserveTimeout          = 500;   //ms
            MaxViewRetries          = 2;
            ViewHardTimeout         = 30000; //ms
            HeartbeatConfigInterval = 10000; //ms
            EnableConfigHeartBeat   = true;
            SerializationSettings   = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            DeserializationSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            ViewRequestTimeout       = 75000; //ms
            DefaultConnectionLimit   = 5;     //connections
            Expect100Continue        = false;
            EnableOperationTiming    = false;
            BufferSize               = 1024 * 16;
            DefaultOperationLifespan = 2500;//ms
            EnableTcpKeepAlives      = true;
            QueryFailedThreshold     = 2;

            TcpKeepAliveTime     = 2 * 60 * 60 * 1000;
            TcpKeepAliveInterval = 1000;

            NodeAvailableCheckInterval = 1000;//ms
            IOErrorCheckInterval       = 500;
            IOErrorThreshold           = 10;

            //the default serializer
            Serializer = SerializerFactory.GetSerializer();

            //the default byte converter
            Converter = ConverterFactory.GetConverter();

            //the default transcoder
            Transcoder = TranscoderFactory.GetTranscoder(this);

            PoolConfiguration = new PoolConfiguration(this)
            {
                BufferSize      = BufferSize,
                BufferAllocator = (p) => new BufferAllocator(p.MaxSize * p.BufferSize, p.BufferSize)
            };

            BucketConfigs = new Dictionary <string, BucketConfiguration>
            {
                { DefaultBucket, new BucketConfiguration
                  {
                      PoolConfiguration = PoolConfiguration,
                  } }
            };
            Servers = new List <Uri> {
                _defaultServer
            };

            //Set back to default
            _operationLifespanChanged = false;
            _serversChanged           = false;
            _poolConfigurationChanged = false;
        }
        internal void Initialize()
        {
            if (PoolConfiguration == null)
            {
                PoolConfiguration = new PoolConfiguration(this);
            }
            if (PoolConfiguration.ClientConfiguration == null)
            {
                PoolConfiguration.ClientConfiguration = this;
            }

            if (_serversChanged)
            {
                for (var i = 0; i < _servers.Count(); i++)
                {
                    if (_servers[i].OriginalString.EndsWith("/pools"))
                    {
                        /*noop*/
                    }
                    else
                    {
                        var value = _servers[i].ToString();
                        value = string.Concat(value, value.EndsWith("/") ? "pools" : "/pools");
                        var uri = new Uri(value);
                        uri.ConfigureServicePoint(this);
                        _servers[i] = uri;
                    }
                }
            }

            //Update the bucket configs
            foreach (var keyValue in BucketConfigs)
            {
                var bucketConfiguration = keyValue.Value;
                if (string.IsNullOrEmpty(bucketConfiguration.BucketName))
                {
                    if (string.IsNullOrWhiteSpace(keyValue.Key))
                    {
                        throw new ArgumentException("bucketConfiguration.BucketName is null or empty.");
                    }
                    bucketConfiguration.BucketName = keyValue.Key;
                }
                if (bucketConfiguration.PoolConfiguration == null || _poolConfigurationChanged)
                {
                    bucketConfiguration.PoolConfiguration = PoolConfiguration;
                }
                if (bucketConfiguration.Servers == null || HasServersChanged())
                {
                    bucketConfiguration.Servers = Servers.Select(x => x).ToList();
                }
                if (bucketConfiguration.Servers.Count == 0)
                {
                    bucketConfiguration.Servers.AddRange(Servers.Select(x => x).ToList());
                }
                if (bucketConfiguration.Port == (int)DefaultPorts.Proxy)
                {
                    var message = string.Format("Proxy port {0} is not supported by the .NET client.",
                        bucketConfiguration.Port);
                    throw new NotSupportedException(message);
                }
                if (bucketConfiguration.UseSsl)
                {
                    bucketConfiguration.PoolConfiguration.UseSsl = true;
                }
                if (UseSsl)
                {
                    //Setting ssl to true at parent level overrides child level ssl settings
                    bucketConfiguration.UseSsl = true;
                    bucketConfiguration.Port = SslPort;
                    bucketConfiguration.PoolConfiguration.UseSsl = true;
                }
                if (_useSslChanged)
                {
                    for (var i = 0; i < _servers.Count(); i++)
                    {
                        var useSsl = UseSsl || bucketConfiguration.UseSsl;
                        //Rewrite the URI's for bootstrapping to use SSL.
                        if (useSsl)
                        {
                            var oldUri = _servers[i];
                            var newUri = new Uri(string.Concat("https://", _servers[i].Host,
                                ":", HttpsMgmtPort, oldUri.PathAndQuery));
                            newUri.ConfigureServicePoint(this);
                            _servers[i] = newUri;
                        }
                    }
                }
                //operation lifespan: if it has changed at bucket level, use bucket level, else use global level
                if (_operationLifespanChanged)
                {
                    bucketConfiguration.UpdateOperationLifespanDefault(_operationLifespan);
                }
            }
        }