public void Equals_should_return_false_when_any_field_is_not_equal( [Values("mode", "tagSets")] string notEqualFieldName) { var mode = ReadPreferenceMode.Secondary; var tagSets = new[] { new TagSet(new[] { new Tag("name", "value1") }) }; var subject1 = new ReadPreference(mode, tagSets); switch (notEqualFieldName) { case "mode": mode = ReadPreferenceMode.SecondaryPreferred; break; case "tagSets": tagSets = new[] { new TagSet(new[] { new Tag("name", "value2") }) }; break; default: throw new ArgumentException("notEqualFieldName"); } var subject2 = new ReadPreference(mode, tagSets); var result1 = subject1.Equals(subject2); var result2 = subject1.Equals((object)subject2); var hashCode1 = subject1.GetHashCode(); var hashCode2 = subject2.GetHashCode(); result1.Should().BeFalse(); result2.Should().BeFalse(); hashCode1.Should().NotBe(hashCode2); }
/// <summary> /// Creates a new instance of MongoDatabaseSettings. /// </summary> /// <param name="databaseName">The name of the database.</param> /// <param name="credentials">The credentials to access the database.</param> /// <param name="guidRepresentation">The representation for Guids.</param> /// <param name="readPreference">The read preference.</param> /// <param name="writeConcern">The write concern to use.</param> public MongoDatabaseSettings( string databaseName, MongoCredentials credentials, GuidRepresentation guidRepresentation, ReadPreference readPreference, WriteConcern writeConcern) { if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (databaseName == "admin" && credentials != null && !credentials.Admin) { throw new ArgumentOutOfRangeException("credentials", "Credentials for the admin database must have the admin flag set to true."); } if (readPreference == null) { throw new ArgumentNullException("readPreference"); } if (writeConcern == null) { throw new ArgumentNullException("writeConcern"); } _databaseName = databaseName; _credentials = credentials; _guidRepresentation = guidRepresentation; _readPreference = readPreference; _writeConcern = writeConcern; }
/// <summary> /// Initializes a new instance of the <see cref="GridFSBucketOptions"/> class. /// </summary> /// <param name="other">The other <see cref="GridFSBucketOptions.Immutable"/> from which to copy the values.</param> public GridFSBucketOptions(GridFSBucketOptions.Immutable other) { _bucketName = other.BucketName; _chunkSizeBytes = other.ChunkSizeBytes; _readPreference = other.ReadPreference; _writeConcern = other.WriteConcern; }
public static BsonDocument CreateReadPreferenceDocument(ServerType serverType, ReadPreference readPreference) { if (serverType != ServerType.ShardRouter || readPreference == null) { return null; } BsonArray tagSets = null; if (readPreference.TagSets != null && readPreference.TagSets.Count > 0) { tagSets = new BsonArray(readPreference.TagSets.Select(ts => new BsonDocument(ts.Tags.Select(t => new BsonElement(t.Name, t.Value))))); } // simple ReadPreferences of Primary and SecondaryPreferred are encoded in the slaveOk bit if (readPreference.ReadPreferenceMode == ReadPreferenceMode.Primary || readPreference.ReadPreferenceMode == ReadPreferenceMode.SecondaryPreferred) { if (tagSets == null && !readPreference.MaxStaleness.HasValue) { return null; } } var modeString = readPreference.ReadPreferenceMode.ToString(); modeString = Char.ToLowerInvariant(modeString[0]) + modeString.Substring(1); return new BsonDocument { { "mode", modeString }, { "tags", tagSets, tagSets != null }, { "maxStalenessSeconds", () => (int)readPreference.MaxStaleness.Value.TotalSeconds, readPreference.MaxStaleness.HasValue } }; }
public void TestCopyConstructor() { var other = new ReadPreference(ReadPreferenceMode.Nearest); var subject = new ReadPreference(other); Assert.AreEqual(subject, other); }
// constructors /// <summary> /// Creates a new instance of MongoUrlBuilder. /// </summary> public MongoUrlBuilder() { _connectionMode = ConnectionMode.Automatic; _connectTimeout = MongoDefaults.ConnectTimeout; _databaseName = null; _defaultCredentials = null; _fsync = null; _guidRepresentation = MongoDefaults.GuidRepresentation; _ipv6 = false; _journal = null; _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime; _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime; _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize; _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize; _readPreference = null; _replicaSetName = null; _secondaryAcceptableLatency = MongoDefaults.SecondaryAcceptableLatency; _servers = null; _slaveOk = null; _socketTimeout = MongoDefaults.SocketTimeout; _useSsl = false; _verifySslCertificate = true; _w = null; _waitQueueMultiple = MongoDefaults.WaitQueueMultiple; _waitQueueSize = MongoDefaults.WaitQueueSize; _waitQueueTimeout = MongoDefaults.WaitQueueTimeout; _wTimeout = null; }
public static BsonDocument CreateReadPreferenceDocument(ServerType serverType, ReadPreference readPreference) { if (readPreference == null) { return null; } if (serverType != ServerType.ShardRouter) { return null; } BsonArray tagSets = null; if (readPreference.TagSets != null && readPreference.TagSets.Any()) { tagSets = new BsonArray(readPreference.TagSets.Select(ts => new BsonDocument(ts.Tags.Select(t => new BsonElement(t.Name, t.Value))))); } else if (readPreference.ReadPreferenceMode == ReadPreferenceMode.Primary || readPreference.ReadPreferenceMode == ReadPreferenceMode.SecondaryPreferred) { return null; } var readPreferenceString = readPreference.ReadPreferenceMode.ToString(); readPreferenceString = Char.ToLowerInvariant(readPreferenceString[0]) + readPreferenceString.Substring(1); return new BsonDocument { { "mode", readPreferenceString }, { "tags", tagSets, tagSets != null } }; }
// constructors /// <summary> /// Creates a new instance of MongoServerSettings. Usually you would use a connection string instead. /// </summary> public MongoServerSettings() { _connectionMode = ConnectionMode.Automatic; _connectTimeout = MongoDefaults.ConnectTimeout; _credentialsStore = new MongoCredentialsStore(); _defaultCredentials = null; _guidRepresentation = MongoDefaults.GuidRepresentation; _ipv6 = false; _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime; _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime; _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize; _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize; _readPreference = ReadPreference.Primary; _replicaSetName = null; _secondaryAcceptableLatency = MongoDefaults.SecondaryAcceptableLatency; _servers = new List<MongoServerAddress> { new MongoServerAddress("localhost") }; _socketTimeout = MongoDefaults.SocketTimeout; _useSsl = false; _verifySslCertificate = true; _waitQueueSize = MongoDefaults.ComputedWaitQueueSize; _waitQueueTimeout = MongoDefaults.WaitQueueTimeout; #pragma warning disable 612, 618 _writeConcern = MongoDefaults.SafeMode.WriteConcern; #pragma warning restore }
// constructors /// <summary> /// Creates a new instance of MongoUrlBuilder. /// </summary> public MongoUrlBuilder() { _authenticationMechanism = MongoDefaults.AuthenticationMechanism; _authenticationSource = null; _connectionMode = ConnectionMode.Automatic; _connectTimeout = MongoDefaults.ConnectTimeout; _databaseName = null; _fsync = null; _guidRepresentation = MongoDefaults.GuidRepresentation; _ipv6 = false; _journal = null; _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime; _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime; _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize; _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize; _password = null; _readPreference = null; _replicaSetName = null; _servers = null; _slaveOk = null; _socketTimeout = MongoDefaults.SocketTimeout; _username = null; _useSsl = false; _verifySslCertificate = true; _w = null; _waitQueueMultiple = MongoDefaults.WaitQueueMultiple; _waitQueueSize = MongoDefaults.WaitQueueSize; _waitQueueTimeout = MongoDefaults.WaitQueueTimeout; _wTimeout = null; }
public void constructor_should_initialize_instance_when_tagSets_is_null() { var result = new ReadPreference(ReadPreferenceMode.Secondary, null); result.ReadPreferenceMode.Should().Be(ReadPreferenceMode.Secondary); result.TagSets.Should().BeEmpty(); }
/// <summary> /// Creates a new instance of MongoDatabaseSettings. /// </summary> /// <param name="databaseName">The name of the database.</param> /// <param name="credentials">The credentials to access the database.</param> /// <param name="guidRepresentation">The representation for Guids.</param> /// <param name="safeMode">The safe mode to use.</param> /// <param name="slaveOk">Whether queries should be sent to secondary servers.</param> public MongoDatabaseSettings(string databaseName, MongoCredentials credentials, GuidRepresentation guidRepresentation, SafeMode safeMode, ReadPreference readPreference) { this.databaseName = databaseName; this.credentials = credentials; this.guidRepresentation = guidRepresentation; this.safeMode = safeMode; this.readPreference = readPreference; }
public void constructor_with_mode_should_initialize_instance() { var mode = ReadPreferenceMode.Secondary; // use a value that is not the default var result = new ReadPreference(mode: mode); result.ReadPreferenceMode.Should().Be(mode); result.TagSets.Should().BeEmpty(); }
/// <summary> /// Initializes a new instance of the <see cref="GridFSBucketOptions"/> class. /// </summary> /// <param name="other">The other <see cref="ImmutableGridFSBucketOptions"/> from which to copy the values.</param> public GridFSBucketOptions(ImmutableGridFSBucketOptions other) { Ensure.IsNotNull(other, nameof(other)); _bucketName = other.BucketName; _chunkSizeBytes = other.ChunkSizeBytes; _readConcern = other.ReadConcern; _readPreference = other.ReadPreference; _writeConcern = other.WriteConcern; }
/// <summary> /// Returns a client settings object representing a connection /// to the current MongoDB replica set. You should cache these connection /// settings and re-obtain them only if there is a connection exception. /// </summary> /// <param name="readPreference">The required read preference.</param> /// <param name="mongoWorkerRoleName">Name of the mongo worker role.</param> /// <param name="replicaSetName">Name of the mongo replica set.</param> /// <returns> /// A MongoClientSettings object representing a replica set connection. /// </returns> /// <example> /// <code> /// var client = ConnectionUtilities.GetMongoClientSettings(ReadPreference.SecondaryPreferred); /// var server = client.GetServer(); /// </code> /// </example> public static MongoClientSettings GetMongoClientSettings(ReadPreference readPreference, string mongoWorkerRoleName, string replicaSetName) { return new MongoClientSettings { ReadPreference = readPreference, ReplicaSetName = replicaSetName, Servers = GetServerAddresses(mongoWorkerRoleName, replicaSetName) }; }
// constructors /// <summary> /// Creates a new instance of MongoDatabaseSettings. /// </summary> /// <param name="server">The server to inherit settings from.</param> /// <param name="databaseName">The name of the database.</param> public MongoDatabaseSettings(MongoServer server, string databaseName) { var serverSettings = server.Settings; this.databaseName = databaseName; this.credentials = serverSettings.DefaultCredentials; this.guidRepresentation = serverSettings.GuidRepresentation; this.safeMode = serverSettings.SafeMode; this.readPreference = serverSettings.ReadPreference; }
public void constructor_with_tagSets_should_initialize_instance() { var mode = ReadPreferenceMode.Secondary; // can't use tagSets with mode Primary var tagSets = new[] { new TagSet(new[] { new Tag("name", "value") }) }; var result = new ReadPreference(mode: mode, tagSets: tagSets); result.ReadPreferenceMode.Should().Be(mode); result.TagSets.Should().NotBeSameAs(tagSets); result.TagSets.Should().Equal(tagSets); }
/// <summary> /// Chooses the server instance based on the read preference. /// </summary> /// <param name="readPreference">The read preference.</param> /// <returns>A MongoServerInstance.</returns> public MongoServerInstance ChooseServerInstance(ReadPreference readPreference) { lock (_lock) { if (_instances.Count == 0) { return null; } return readPreference.ChooseServerInstance(_instances); } }
// constructors /// <summary> /// Initializes a new instance of the <see cref="ReadPreferenceServerSelector"/> class. /// </summary> /// <param name="readPreference">The read preference.</param> public ReadPreferenceServerSelector(ReadPreference readPreference) { _readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference)); if (readPreference.MaxStaleness == Timeout.InfiniteTimeSpan) { _maxStaleness = null; } else { _maxStaleness = readPreference.MaxStaleness; } }
public void TestEquals() { ReadPreference primary = ReadPreference.Primary; ReadPreference secondary = ReadPreference.Secondary; ReadPreference voidTag = new ReadPreference(new HashSet<string>()); ReadPreference someTags = new ReadPreference(new HashSet<string>()); someTags.Tags.Add("new york"); someTags.Tags.Add("rack 1"); ReadPreference someTagsBis = new ReadPreference(new HashSet<string>()); someTagsBis.Tags.Add("rack 1"); someTagsBis.Tags.Add("new york"); ReadPreference someTagsAgain = new ReadPreference(new HashSet<string>()); someTagsAgain.Tags.Add("palo alto"); someTagsAgain.Tags.Add("rack 1"); //Equals to self Assert.AreEqual(true, primary.Equals(primary)); Assert.AreEqual(true, secondary.Equals(secondary)); Assert.AreEqual(true, voidTag.Equals(voidTag)); Assert.AreEqual(true, someTags.Equals(someTags)); Assert.AreEqual(true, someTagsAgain.Equals(someTagsAgain)); //Basic stuff are not equal Assert.AreEqual(false, primary.Equals(secondary)); Assert.AreEqual(false, secondary.Equals(primary)); Assert.AreEqual(false, primary.Equals(voidTag)); Assert.AreEqual(false, voidTag.Equals(primary)); Assert.AreEqual(false, primary.Equals(secondary)); Assert.AreEqual(false, secondary.Equals(primary)); Assert.AreEqual(false, primary.Equals(someTags)); Assert.AreEqual(false, someTags.Equals(primary)); Assert.AreEqual(false, primary.Equals(someTagsAgain)); Assert.AreEqual(false, someTagsAgain.Equals(primary)); Assert.AreEqual(false, someTags.Equals(secondary)); Assert.AreEqual(false, secondary.Equals(someTags)); Assert.AreEqual(true, someTags.Equals(someTagsBis)); Assert.AreEqual(true, someTagsBis.Equals(someTags)); //two object equals constructed separately are equals Assert.AreEqual(true, someTags.Equals(someTagsBis)); Assert.AreEqual(true, someTagsBis.Equals(someTags)); //default tagged is not tagged but defaulted to secondary ok Assert.AreEqual(true, voidTag.Equals(secondary)); Assert.AreEqual(true, secondary.Equals(voidTag)); Assert.AreEqual(false, someTagsAgain.Equals(secondary)); Assert.AreEqual(false, secondary.Equals(someTagsAgain)); }
protected IMongoQuery WrapQuery(IMongoQuery query, BsonDocument options, ReadPreference readPreference, bool forShardRouter) { BsonDocument formattedReadPreference = null; if (forShardRouter && readPreference != null && readPreference.ReadPreferenceMode != ReadPreferenceMode.Primary) { BsonArray tagSetsArray = null; if (readPreference.TagSets != null) { tagSetsArray = new BsonArray(); foreach (var tagSet in readPreference.TagSets) { var tagSetDocument = new BsonDocument(); foreach (var tag in tagSet) { tagSetDocument.Add(tag.Name, tag.Value); } tagSetsArray.Add(tagSetDocument); } } if (tagSetsArray != null || readPreference.ReadPreferenceMode != ReadPreferenceMode.SecondaryPreferred) { formattedReadPreference = new BsonDocument { { "mode", MongoUtils.ToCamelCase(readPreference.ReadPreferenceMode.ToString()) }, { "tags", tagSetsArray, tagSetsArray != null } // optional }; } } if (options == null && formattedReadPreference == null) { return query; } else { var queryDocument = (query == null) ? (BsonValue)new BsonDocument() : BsonDocumentWrapper.Create(query); var wrappedQuery = new QueryDocument { { "$query", queryDocument }, { "$readPreference", formattedReadPreference, formattedReadPreference != null }, // only if sending query to a mongos }; if (options != null) { wrappedQuery.Merge(options); } return wrappedQuery; } }
public void Equals_should_be_correct() { var a = ReadPreference.Primary; var b = ReadPreference.Primary; var c = ReadPreference.Secondary; var d = new ReadPreference(ReadPreferenceMode.Secondary, new[] { new TagSet(new[] { new Tag("dc", "ny"), new Tag("dc", "ca") }) }); var e = new ReadPreference(ReadPreferenceMode.Secondary, new[] { new TagSet(new[] { new Tag("dc", "ny"), new Tag("dc", "ca") }) }); var f = new ReadPreference(ReadPreferenceMode.Secondary, new[] { new TagSet(new[] { new Tag("dc", "ny"), new Tag("dc", "ac") }) }); var g = new ReadPreference(ReadPreferenceMode.Primary, new[] { new TagSet(new[] { new Tag("dc", "ny"), new Tag("dc", "ac") }) }); a.Should().Be(b); b.Should().NotBe(c); c.Should().NotBe(d); d.Should().Be(e); e.Should().NotBe(f); f.Should().NotBe(g); }
// constructors /// <summary> /// Creates a new instance of MongoDatabaseSettings. /// </summary> /// <param name="server">The server to inherit settings from.</param> /// <param name="databaseName">The name of the database.</param> public MongoDatabaseSettings(MongoServer server, string databaseName) { if (server == null) { throw new ArgumentNullException("server"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } var serverSettings = server.Settings; _databaseName = databaseName; _credentials = serverSettings.GetCredentials(databaseName); _guidRepresentation = serverSettings.GuidRepresentation; _readPreference = serverSettings.ReadPreference; _writeConcern = serverSettings.WriteConcern; }
// constructors /// <summary> /// Creates a new instance of MongoServerSettings. Usually you would use a connection string instead. /// </summary> public MongoServerSettings() { connectionMode = ConnectionMode.Direct; connectTimeout = MongoDefaults.ConnectTimeout; defaultCredentials = null; guidRepresentation = MongoDefaults.GuidRepresentation; ipv6 = false; maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime; maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime; maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize; minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize; replicaSetName = null; safeMode = MongoDefaults.SafeMode; servers = null; //slaveOk = false; readPreference = ReadPreference.Primary; socketTimeout = MongoDefaults.SocketTimeout; waitQueueSize = MongoDefaults.ComputedWaitQueueSize; waitQueueTimeout = MongoDefaults.WaitQueueTimeout; }
// protected methods protected override MongoServerInstance ChooseServerInstance(ConnectedInstanceCollection connectedInstances, ReadPreference readPreference) { var secondaryAcceptableLatency = Settings.SecondaryAcceptableLatency; switch (readPreference.ReadPreferenceMode) { case ReadPreferenceMode.Primary: return connectedInstances.GetPrimary(); case ReadPreferenceMode.PrimaryPreferred: var primary = connectedInstances.GetPrimary(); if (primary != null) { return primary; } else { return GetMatchingInstance(connectedInstances.GetSecondaries(), readPreference, secondaryAcceptableLatency); } case ReadPreferenceMode.Secondary: return GetMatchingInstance(connectedInstances.GetSecondaries(), readPreference, secondaryAcceptableLatency); case ReadPreferenceMode.SecondaryPreferred: var secondary = GetMatchingInstance(connectedInstances.GetSecondaries(), readPreference, secondaryAcceptableLatency); if (secondary != null) { return secondary; } else { return connectedInstances.GetPrimary(); } case ReadPreferenceMode.Nearest: return GetMatchingInstance(connectedInstances.GetPrimaryAndSecondaries(), readPreference, secondaryAcceptableLatency); default: throw new MongoInternalException("Invalid ReadPreferenceMode."); } }
// constructors /// <summary> /// Creates a new instance of MongoServerSettings. Usually you would use a connection string instead. /// </summary> public MongoServerSettings() { _connectionMode = ConnectionMode.Direct; _connectTimeout = MongoDefaults.ConnectTimeout; _credentialsStore = new MongoCredentialsStore(); _defaultCredentials = null; _guidRepresentation = MongoDefaults.GuidRepresentation; _ipv6 = false; _maxConnectionIdleTime = MongoDefaults.MaxConnectionIdleTime; _maxConnectionLifeTime = MongoDefaults.MaxConnectionLifeTime; _maxConnectionPoolSize = MongoDefaults.MaxConnectionPoolSize; _minConnectionPoolSize = MongoDefaults.MinConnectionPoolSize; _readPreference = ReadPreference.Primary; _replicaSetName = null; _safeMode = MongoDefaults.SafeMode; _servers = new List<MongoServerAddress> { new MongoServerAddress("localhost") }; _serversReadOnly = new ReadOnlyCollection<MongoServerAddress>(_servers); _socketTimeout = MongoDefaults.SocketTimeout; _waitQueueSize = MongoDefaults.ComputedWaitQueueSize; _waitQueueTimeout = MongoDefaults.WaitQueueTimeout; }
public void TestGetHashCodeIsSameWhenEverythingIsTheSame() { var tagSets1 = new List<ReplicaSetTagSet>() { new ReplicaSetTagSet { new ReplicaSetTag("dc", "ny") } }; var readPreference1 = new ReadPreference(ReadPreferenceMode.Nearest, tagSets1); var tagSets2 = new List<ReplicaSetTagSet>() { new ReplicaSetTagSet { new ReplicaSetTag("dc", "ny") } }; var readPreference2 = new ReadPreference(ReadPreferenceMode.Nearest, tagSets2); Assert.AreEqual(readPreference1.GetHashCode(), readPreference2.GetHashCode()); }
public void TestEquality() { var tagSets1 = new List<ReplicaSetTagSet>() { new ReplicaSetTagSet { new ReplicaSetTag("dc", "ny") } }; var readPreference1 = new ReadPreference(ReadPreferenceMode.Nearest, tagSets1); var tagSets2 = new List<ReplicaSetTagSet>() { new ReplicaSetTagSet { new ReplicaSetTag("dc", "ny") } }; var readPreference2 = new ReadPreference(ReadPreferenceMode.Nearest, tagSets2); Assert.AreEqual(readPreference1, readPreference2); }
// constructors /// <summary> /// Initializes a new instance of the MongoCollectionSettings class. /// </summary> /// <param name="database">The database that contains the collection (some collection settings will be inherited from the database settings).</param> /// <param name="collectionName">The name of the collection.</param> /// <param name="defaultDocumentType">The default document type for the collection.</param> protected MongoCollectionSettings(MongoDatabase database, string collectionName, Type defaultDocumentType) { if (database == null) { throw new ArgumentNullException("database"); } if (collectionName == null) { throw new ArgumentNullException("collectionName"); } if (defaultDocumentType == null) { throw new ArgumentNullException("defaultDocumentType"); } var databaseSettings = database.Settings; _collectionName = collectionName; _assignIdOnInsert = MongoDefaults.AssignIdOnInsert; _defaultDocumentType = defaultDocumentType; _guidRepresentation = databaseSettings.GuidRepresentation; _readPreference = databaseSettings.ReadPreference; _writeConcern = databaseSettings.WriteConcern; }
// protected methods /// <summary> /// Chooses the server instance. /// </summary> /// <param name="connectedInstances">The connected instances.</param> /// <param name="readPreference">The read preference.</param> /// <returns>A MongoServerInstance.</returns> protected override MongoServerInstance ChooseServerInstance(ConnectedInstanceCollection connectedInstances, ReadPreference readPreference) { var instancesWithPingTime = connectedInstances.GetAllInstances(); if (instancesWithPingTime.Count == 0) { return null; } else if (instancesWithPingTime.Count == 1) { return instancesWithPingTime[0].Instance; } else { var minPingTime = instancesWithPingTime[0].CachedAveragePingTime; var maxPingTime = minPingTime + readPreference.SecondaryAcceptableLatency; var n = instancesWithPingTime.Count(i => i.CachedAveragePingTime <= maxPingTime); lock (_randomLock) { var index = _random.Next(n); return instancesWithPingTime[index].Instance; // return random instance } } }
// protected methods /// <summary> /// Chooses the server instance. /// </summary> /// <param name="connectedInstances">The connected instances.</param> /// <param name="readPreference">The read preference.</param> /// <returns>A MongoServerInstance.</returns> protected abstract MongoServerInstance ChooseServerInstance(ConnectedInstanceCollection connectedInstances, ReadPreference readPreference);
private async Task <IReadOnlyList <BsonDocument> > ExecuteUsingCommandAsync(IChannelSourceHandle channelSource, ReadPreference readPreference, CancellationToken cancellationToken) { var databaseNamespace = _collectionNamespace.DatabaseNamespace; var command = new BsonDocument("listIndexes", _collectionNamespace.CollectionName); var operation = new ReadCommandOperation <BsonDocument>(databaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings); BsonDocument result; try { result = await operation.ExecuteAsync(channelSource, readPreference, cancellationToken).ConfigureAwait(false); } catch (MongoCommandException ex) { if (ex.Code == 26) { return(new List <BsonDocument>()); } throw; } return(result["indexes"].AsBsonArray.Cast <BsonDocument>().ToList()); }
public virtual TResult RunCommand <TResult>(Command <TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = new CancellationToken()) => throw new NotImplementedException();
public virtual Task <TResult> RunCommandAsync <TResult>(IClientSessionHandle session, Command <TResult> command, ReadPreference readPreference = null, CancellationToken cancellationToken = new CancellationToken()) => throw new NotImplementedException();
// constructors public ConnectionReadBinding(IServer server, IConnectionHandle connection, ReadPreference readPreference) { _server = Ensure.IsNotNull(server, "server"); _connection = Ensure.IsNotNull(connection, "connection"); _readPreference = Ensure.IsNotNull(readPreference, "readPreference"); }
private QueryWireProtocol <TDocument> CreateProtocol(BsonDocument wrappedQuery, ReadPreference readPreference) { var slaveOk = readPreference != null && readPreference.ReadPreferenceMode != ReadPreferenceMode.Primary; var firstBatchSize = CalculateFirstBatchSize(); return(new QueryWireProtocol <TDocument>( _collectionNamespace, wrappedQuery, _projection, NoOpElementNameValidator.Instance, _skip ?? 0, firstBatchSize, slaveOk, _partial, _noCursorTimeout, _tailable, _awaitData, _resultSerializer, _messageEncoderSettings)); }
/// <summary> /// Create a read binding handle. /// </summary> /// <param name="cluster">The cluster,</param> /// <param name="session">The session.</param> /// <param name="readPreference">The read preference.</param> /// <returns>An effective read binging.</returns> public static IReadBindingHandle CreateReadBinding(ICluster cluster, ICoreSessionHandle session, ReadPreference readPreference) { IReadBinding readBinding; if (session.IsInTransaction && IsChannelPinned(session.CurrentTransaction) && session.CurrentTransaction.State != CoreTransactionState.Starting) { readBinding = new ChannelReadWriteBinding( session.CurrentTransaction.PinnedServer, session.CurrentTransaction.PinnedChannel.Fork(), session); } else { if (IsInLoadBalancedMode(cluster.Description) && IsChannelPinned(session.CurrentTransaction)) { // unpin if the next operation is not under transaction session.CurrentTransaction.UnpinAll(); } readBinding = new ReadPreferenceBinding(cluster, readPreference, session); } return(new ReadBindingHandle(readBinding)); }
public void TestAll() { var readPreference = new ReadPreference(ReadPreferenceMode.Secondary, new[] { new TagSet(new[] { new Tag("dc", "1") }) }, TimeSpan.FromSeconds(11)); var authMechanismProperties = new Dictionary <string, string> { { "SERVICE_NAME", "other" }, { "CANONICALIZE_HOST_NAME", "true" } }; var built = new MongoUrlBuilder() { ApplicationName = "app", AuthenticationMechanism = "GSSAPI", AuthenticationMechanismProperties = authMechanismProperties, AuthenticationSource = "db", ConnectionMode = ConnectionMode.ReplicaSet, ConnectTimeout = TimeSpan.FromSeconds(1), DatabaseName = "database", FSync = true, GuidRepresentation = GuidRepresentation.PythonLegacy, HeartbeatInterval = TimeSpan.FromSeconds(11), HeartbeatTimeout = TimeSpan.FromSeconds(12), IPv6 = true, Journal = true, MaxConnectionIdleTime = TimeSpan.FromSeconds(2), MaxConnectionLifeTime = TimeSpan.FromSeconds(3), MaxConnectionPoolSize = 4, MinConnectionPoolSize = 5, Password = "******", ReadConcernLevel = ReadConcernLevel.Majority, ReadPreference = readPreference, ReplicaSetName = "name", RetryWrites = true, LocalThreshold = TimeSpan.FromSeconds(6), Server = new MongoServerAddress("host"), ServerSelectionTimeout = TimeSpan.FromSeconds(10), SocketTimeout = TimeSpan.FromSeconds(7), Username = "******", UseSsl = true, VerifySslCertificate = false, W = 2, WaitQueueSize = 123, WaitQueueTimeout = TimeSpan.FromSeconds(8), WTimeout = TimeSpan.FromSeconds(9) }; var connectionString = "mongodb://*****:*****@host/database?" + string.Join(";", new[] { "authMechanism=GSSAPI", "authMechanismProperties=SERVICE_NAME:other,CANONICALIZE_HOST_NAME:true", "authSource=db", "appname=app", "ipv6=true", "ssl=true", // UseSsl "sslVerifyCertificate=false", // VerifySslCertificate "connect=replicaSet", "replicaSet=name", "readConcernLevel=majority", "readPreference=secondary;readPreferenceTags=dc:1;maxStaleness=11s", "fsync=true", "journal=true", "w=2", "wtimeout=9s", "connectTimeout=1s", "heartbeatInterval=11s", "heartbeatTimeout=12s", "maxIdleTime=2s", "maxLifeTime=3s", "maxPoolSize=4", "minPoolSize=5", "localThreshold=6s", "serverSelectionTimeout=10s", "socketTimeout=7s", "waitQueueSize=123", "waitQueueTimeout=8s", "uuidRepresentation=pythonLegacy", "retryWrites=true" }); foreach (var url in EnumerateBuiltAndParsedUrls(built, connectionString)) { Assert.Equal("app", url.ApplicationName); Assert.Equal("GSSAPI", url.AuthenticationMechanism); Assert.Equal(authMechanismProperties, url.AuthenticationMechanismProperties); Assert.Equal("db", url.AuthenticationSource); Assert.Equal(123, url.ComputedWaitQueueSize); Assert.Equal(ConnectionMode.ReplicaSet, url.ConnectionMode); Assert.Equal(TimeSpan.FromSeconds(1), url.ConnectTimeout); Assert.Equal("database", url.DatabaseName); Assert.Equal(true, url.FSync); Assert.Equal(GuidRepresentation.PythonLegacy, url.GuidRepresentation); Assert.Equal(TimeSpan.FromSeconds(11), url.HeartbeatInterval); Assert.Equal(TimeSpan.FromSeconds(12), url.HeartbeatTimeout); Assert.Equal(true, url.IPv6); Assert.Equal(true, url.Journal); Assert.Equal(TimeSpan.FromSeconds(2), url.MaxConnectionIdleTime); Assert.Equal(TimeSpan.FromSeconds(3), url.MaxConnectionLifeTime); Assert.Equal(4, url.MaxConnectionPoolSize); Assert.Equal(5, url.MinConnectionPoolSize); Assert.Equal("password", url.Password); Assert.Equal(ReadConcernLevel.Majority, url.ReadConcernLevel); Assert.Equal(readPreference, url.ReadPreference); Assert.Equal("name", url.ReplicaSetName); Assert.Equal(true, url.RetryWrites); Assert.Equal(TimeSpan.FromSeconds(6), url.LocalThreshold); Assert.Equal(ConnectionStringScheme.MongoDB, url.Scheme); Assert.Equal(new MongoServerAddress("host", 27017), url.Server); Assert.Equal(TimeSpan.FromSeconds(10), url.ServerSelectionTimeout); Assert.Equal(TimeSpan.FromSeconds(7), url.SocketTimeout); Assert.Equal("username", url.Username); Assert.Equal(true, url.UseSsl); Assert.Equal(false, url.VerifySslCertificate); Assert.Equal(2, ((WriteConcern.WCount)url.W).Value); Assert.Equal(0.0, url.WaitQueueMultiple); Assert.Equal(123, url.WaitQueueSize); Assert.Equal(TimeSpan.FromSeconds(8), url.WaitQueueTimeout); Assert.Equal(TimeSpan.FromSeconds(9), url.WTimeout); Assert.Equal(connectionString, url.ToString()); } }
private static IReadBindingHandle CreateReadBinding(ReadPreference readPreference, ICoreSessionHandle session) { var binding = new ReadPreferenceBinding(__cluster.Value, readPreference, session.Fork()); return(new ReadBindingHandle(binding)); }
private ChannelReadBinding CreateSubject(IServer server = null, IChannelHandle channel = null, ReadPreference readPreference = null, ICoreSessionHandle session = null) { return(new ChannelReadBinding( server ?? new Mock <IServer>().Object, channel ?? new Mock <IChannelHandle>().Object, readPreference ?? ReadPreference.Primary, session ?? new Mock <ICoreSessionHandle>().Object)); }
// protected methods protected override MongoServerInstance ChooseServerInstance(ConnectedInstanceCollection connectedInstances, ReadPreference readPreference) { var secondaryAcceptableLatency = Settings.SecondaryAcceptableLatency; switch (readPreference.ReadPreferenceMode) { case ReadPreferenceMode.Primary: return(connectedInstances.GetPrimary()); case ReadPreferenceMode.PrimaryPreferred: var primary = connectedInstances.GetPrimary(); if (primary != null) { return(primary); } else { return(GetMatchingInstance(connectedInstances.GetSecondaries(), readPreference, secondaryAcceptableLatency)); } case ReadPreferenceMode.Secondary: return(GetMatchingInstance(connectedInstances.GetSecondaries(), readPreference, secondaryAcceptableLatency)); case ReadPreferenceMode.SecondaryPreferred: var secondary = GetMatchingInstance(connectedInstances.GetSecondaries(), readPreference, secondaryAcceptableLatency); if (secondary != null) { return(secondary); } else { return(connectedInstances.GetPrimary()); } case ReadPreferenceMode.Nearest: return(GetMatchingInstance(connectedInstances.GetPrimaryAndSecondaries(), readPreference, secondaryAcceptableLatency)); default: throw new MongoInternalException("Invalid ReadPreferenceMode."); } }
public IMongoCollection <T> WithReadPreference(ReadPreference readPreference) { return(collection.WithReadPreference(readPreference)); }
// constructors /// <summary> /// Initializes a new instance of the <see cref="SingleServerReadBinding" /> class. /// </summary> /// <param name="server">The server.</param> /// <param name="readPreference">The read preference.</param> /// <param name="session">The session.</param> public SingleServerReadBinding(IServer server, ReadPreference readPreference, ICoreSessionHandle session) { _server = Ensure.IsNotNull(server, nameof(server)); _readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference)); _session = Ensure.IsNotNull(session, nameof(session)); }
private Task <TCommandResult> ExecuteProtocolAsync(IChannelHandle channel, ICoreSessionHandle session, ReadPreference readPreference, CancellationToken cancellationToken) { var additionalOptions = GetEffectiveAdditionalOptions(); return(channel.CommandAsync( session, readPreference, _databaseNamespace, _command, null, // TODO: support commandPayloads _commandValidator, additionalOptions, null, // postWriteAction, CommandResponseHandling.Return, _resultSerializer, _messageEncoderSettings, cancellationToken)); }
// constructors /// <summary> /// Initializes a new instance of the <see cref="ReadPreferenceBinding"/> class. /// </summary> /// <param name="cluster">The cluster.</param> /// <param name="readPreference">The read preference.</param> public ReadPreferenceBinding(ICluster cluster, ReadPreference readPreference) { _cluster = Ensure.IsNotNull(cluster, nameof(cluster)); _readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference)); _serverSelector = new ReadPreferenceServerSelector(readPreference); }
private async Task <IAsyncCursor <BsonDocument> > ExecuteUsingCommandAsync(IChannelSourceHandle channelSource, ReadPreference readPreference, CancellationToken cancellationToken) { var databaseNamespace = _collectionNamespace.DatabaseNamespace; var command = new BsonDocument("listIndexes", _collectionNamespace.CollectionName); var operation = new ReadCommandOperation <BsonDocument>(databaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings); try { var response = await operation.ExecuteAsync(channelSource, readPreference, cancellationToken).ConfigureAwait(false); var cursorDocument = response["cursor"].AsBsonDocument; var cursor = new AsyncCursor <BsonDocument>( channelSource.Fork(), CollectionNamespace.FromFullName(cursorDocument["ns"].AsString), command, cursorDocument["firstBatch"].AsBsonArray.OfType <BsonDocument>().ToList(), cursorDocument["id"].ToInt64(), 0, 0, BsonDocumentSerializer.Instance, _messageEncoderSettings); return(cursor); } catch (MongoCommandException ex) { if (ex.Code == 26) { return(new SingleBatchAsyncCursor <BsonDocument>(new List <BsonDocument>())); } throw; } }
protected virtual void SetReadPreference(ReadPreference value) { _database = _database.WithReadPreference(value); }
private async Task <IAsyncCursor <BsonDocument> > ExecuteUsingQueryAsync(IChannelSourceHandle channelSource, ReadPreference readPreference, CancellationToken cancellationToken) { var indexes = new List <BsonDocument>(); var systemIndexesCollection = _collectionNamespace.DatabaseNamespace.SystemIndexesCollection; var filter = new BsonDocument("ns", _collectionNamespace.FullName); var operation = new FindOperation <BsonDocument>(systemIndexesCollection, BsonDocumentSerializer.Instance, _messageEncoderSettings) { Filter = filter }; return(await operation.ExecuteAsync(channelSource, readPreference, cancellationToken).ConfigureAwait(false)); }
public IMongoClient WithReadPreference(ReadPreference readPreference) { return(this); }
private IClientSessionHandle CreateSession(BsonDocument entity, Dictionary <string, DisposableMongoClient> clients) { IMongoClient client = null; ClientSessionOptions options = null; foreach (var element in entity) { switch (element.Name) { case "id": // handled on higher level break; case "client": var clientId = element.Value.AsString; client = clients[clientId]; break; case "sessionOptions": options = new ClientSessionOptions(); foreach (var option in element.Value.AsBsonDocument) { switch (option.Name) { case "causalConsistency": options.CausalConsistency = option.Value.ToBoolean(); break; case "defaultTransactionOptions": ReadConcern readConcern = null; ReadPreference readPreference = null; WriteConcern writeConcern = null; foreach (var transactionOption in option.Value.AsBsonDocument) { switch (transactionOption.Name) { case "readConcern": readConcern = ReadConcern.FromBsonDocument(transactionOption.Value.AsBsonDocument); break; case "readPreference": readPreference = ReadPreference.FromBsonDocument(transactionOption.Value.AsBsonDocument); break; case "writeConcern": writeConcern = WriteConcern.FromBsonDocument(transactionOption.Value.AsBsonDocument); break; default: throw new FormatException($"Invalid session transaction option: '{transactionOption.Name}'."); } } options.DefaultTransactionOptions = new TransactionOptions(readConcern, readPreference, writeConcern); break; default: throw new FormatException($"Unrecognized session option: '{option.Name}'."); } } break; default: throw new FormatException($"Unrecognized database entity field: '{element.Name}'."); } } var session = client.StartSession(options); return(session); }
/// <summary> /// Concatenate strings into a formatted speech-ready string. /// </summary> /// <param name="parentString">Itroduction string.</param> /// <param name="selectionStrings">List item strings.</param> /// <param name="readOrder">Read order of list items.</param> /// <param name="maxSize">The max read size.</param> /// <returns>Formatted speech-ready string.</returns> private static string ListToSpeechReadyString(string parentString, List <string> selectionStrings, ReadPreference readOrder, int maxSize) { var result = $"{parentString} " ?? string.Empty; List <string> itemDetails = new List <string>(); int readSize = Math.Min(selectionStrings.Count, maxSize); if (readSize == 1) { itemDetails.Add(selectionStrings[0]); } else { for (var i = 0; i < readSize; i++) { var readFormat = string.Empty; if (i == 0) { if (readOrder.Equals(ReadPreference.Chronological)) { readFormat = CommonStrings.LatestItem; } else { readFormat = CommonStrings.FirstItem; } } else { if (i == readSize - 1) { readFormat = CommonStrings.LastItem; } else { if (i == 1) { readFormat = CommonStrings.SecondItem; } else if (i == 2) { readFormat = CommonStrings.ThirdItem; } else if (i == 3) { readFormat = CommonStrings.FourthItem; } } } var selectionDetail = string.Format(readFormat, selectionStrings[i]); itemDetails.Add(selectionDetail); } } result += itemDetails.ToSpeechString(CommonStrings.And); return(result); }
public virtual IMongoDatabase WithReadPreference(ReadPreference readPreference) => throw new NotImplementedException();
// private methods /// <summary> /// Gets a randomly selected matching instance. /// </summary> /// <param name="instancesWithPingTime">A list of instances from which to find a matching instance.</param> /// <param name="readPreference">The read preference that must be matched.</param> /// <param name="secondaryAcceptableLatency">The maximum acceptable secondary latency.</param> /// <returns>A randomly selected matching instance.</returns> private MongoServerInstance GetMatchingInstance(List <ConnectedInstanceCollection.InstanceWithPingTime> instancesWithPingTime, ReadPreference readPreference, TimeSpan secondaryAcceptableLatency) { var tagSets = readPreference.TagSets ?? new ReplicaSetTagSet[] { new ReplicaSetTagSet() }; foreach (var tagSet in tagSets) { var matchingInstances = new List <MongoServerInstance>(); var maxPingTime = TimeSpan.MaxValue; foreach (var instanceWithPingTime in instancesWithPingTime) { if (instanceWithPingTime.CachedAveragePingTime > maxPingTime) { break; // the rest will exceed maxPingTime also } var instance = instanceWithPingTime.Instance; if (tagSet.MatchesInstance(instance)) { matchingInstances.Add(instance); if (maxPingTime == TimeSpan.MaxValue) { maxPingTime = instanceWithPingTime.CachedAveragePingTime + secondaryAcceptableLatency; } } } // stop looking at tagSets if this one yielded any matching instances if (matchingInstances.Count == 1) { return(matchingInstances[0]); } else if (matchingInstances.Count != 0) { lock (_randomLock) { var index = _random.Next(matchingInstances.Count); return(matchingInstances[index]); // randomly selected matching instance } } } return(null); }
public virtual IMongoCollection <TVal> WithReadPreference(ReadPreference readPreference) => throw new NotImplementedException();
public IMongoCollection <InformationEntry> WithReadPreference(ReadPreference readPreference) { throw new System.NotImplementedException(); }
// constructors /// <summary> /// Initializes a new instance of the <see cref="ChannelSourceReadWriteBinding" /> class. /// </summary> /// <param name="channelSource">The channel source.</param> /// <param name="readPreference">The read preference.</param> /// <param name="session">The session.</param> public ChannelSourceReadWriteBinding(IChannelSourceHandle channelSource, ReadPreference readPreference, ICoreSessionHandle session) { _channelSource = Ensure.IsNotNull(channelSource, nameof(channelSource)); _readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference)); _session = Ensure.IsNotNull(session, nameof(session)); }
private async Task <IReadOnlyList <BsonDocument> > ExecuteUsingQueryAsync(IChannelSourceHandle channelSource, ReadPreference readPreference, CancellationToken cancellationToken) { var indexes = new List <BsonDocument>(); var systemIndexesCollection = _collectionNamespace.DatabaseNamespace.SystemIndexesCollection; var filter = new BsonDocument("ns", _collectionNamespace.FullName); var operation = new FindOperation <BsonDocument>(systemIndexesCollection, BsonDocumentSerializer.Instance, _messageEncoderSettings) { Filter = filter }; var cursor = await operation.ExecuteAsync(channelSource, readPreference, cancellationToken).ConfigureAwait(false); while (await cursor.MoveNextAsync(cancellationToken).ConfigureAwait(false)) { var batch = cursor.Current; foreach (var index in batch) { indexes.Add(index); } } return(indexes); }
// static methods public static TResult Execute <TResult>(this IReadOperation <TResult> operation, IConnectionSourceHandle connectionSource, ReadPreference readPreference, TimeSpan timeout = default(TimeSpan), CancellationToken cancellationToken = default(CancellationToken)) { return(operation.ExecuteAsync(connectionSource, readPreference, timeout, cancellationToken).GetAwaiter().GetResult()); }
public TResult RunCommand <TResult>(string command, ReadPreference readpreference) { return(_database.RunCommand <TResult>(command, readpreference)); }
private void ThrowConnectionException(ReadPreference readPreference) { List<Exception> exceptions; lock (_lock) { exceptions = _instances.Select(x => x.ConnectException).Where(x => x != null).ToList(); } var firstException = exceptions.FirstOrDefault(); string message; if (firstException == null) { message = string.Format("Unable to connect to a member of the replica set matching the read preference {0}", readPreference); } else { message = string.Format("Unable to connect to a member of the replica set matching the read preference {0}: {1}.", readPreference, firstException.Message); } var connectionException = new MongoConnectionException(message, firstException); connectionException.Data.Add("InnerExceptions", exceptions); // useful when there is more than one throw connectionException; }
public IMongoClient WithReadPreference(ReadPreference readPreference) { return(wrapped.WithReadPreference(readPreference)); }