/// <summary> /// Initializes a new instance of the <see cref="ConnectionOpenedEvent" /> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="connectionSettings">The connection settings.</param> /// <param name="duration">The duration of time it took to open the connection.</param> /// <param name="operationId">The operation identifier.</param> public ConnectionOpenedEvent(ConnectionId connectionId, ConnectionSettings connectionSettings, TimeSpan duration, long? operationId) { _connectionId = connectionId; _connectionSettings = connectionSettings; _duration = duration; _operationId = operationId; }
public void Equals_should_return_expected_result( int port1, int localValue1, int serverValue1, int port2, int localValue2, int serverValue2, bool expectedEqualsResult, bool expectedStructurallyEqualsResult) { var clusterId = new ClusterId(); var serverId1 = new ServerId(clusterId, new DnsEndPoint("localhost", port1)); var serverId2 = new ServerId(clusterId, new DnsEndPoint("localhost", port2)); var subject1 = new ConnectionId(serverId1, localValue1).WithServerValue(serverValue1); var subject2 = new ConnectionId(serverId2, localValue2).WithServerValue(serverValue2); // note: Equals ignores the server values and StructurallyEquals compares all fields var equalsResult1 = subject1.Equals(subject2); var equalsResult2 = subject2.Equals(subject1); var structurallyEqualsResult1 = subject1.StructurallyEquals(subject2); var structurallyEqualsResult2 = subject2.StructurallyEquals(subject1); var hashCode1 = subject1.GetHashCode(); var hashCode2 = subject2.GetHashCode(); equalsResult1.Should().Be(expectedEqualsResult); equalsResult2.Should().Be(expectedEqualsResult); structurallyEqualsResult1.Should().Be(expectedStructurallyEqualsResult); structurallyEqualsResult2.Should().Be(expectedStructurallyEqualsResult); (hashCode1 == hashCode2).Should().Be(expectedEqualsResult); }
public void TestFixtureSetup() { _connectionId = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2); _innerException = new Exception("inner"); _writeConcernError = new WriteConcernError(1, "writeConcernError", new BsonDocument("details", "writeConcernError")); _writeError = new WriteError(ServerErrorCategory.Uncategorized, 1, "writeError", new BsonDocument("details", "writeError")); }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionReceivingMessageFailedEvent" /> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="responseTo">The id of the message we were receiving a response to.</param> /// <param name="exception">The exception.</param> /// <param name="operationId">The operation identifier.</param> public ConnectionReceivingMessageFailedEvent(ConnectionId connectionId, int responseTo, Exception exception, long? operationId) { _connectionId = connectionId; _responseTo = responseTo; _exception = exception; _operationId = operationId; }
// constructors public BinaryConnection(ServerId serverId, EndPoint endPoint, ConnectionSettings settings, IStreamFactory streamFactory, IConnectionInitializer connectionInitializer, IEventSubscriber eventSubscriber) { Ensure.IsNotNull(serverId, nameof(serverId)); _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint)); _settings = Ensure.IsNotNull(settings, nameof(settings)); _streamFactory = Ensure.IsNotNull(streamFactory, nameof(streamFactory)); _connectionInitializer = Ensure.IsNotNull(connectionInitializer, nameof(connectionInitializer)); Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber)); _backgroundTaskCancellationTokenSource = new CancellationTokenSource(); _backgroundTaskCancellationToken = _backgroundTaskCancellationTokenSource.Token; _connectionId = new ConnectionId(serverId); _receiveCoordinator = new ReceiveCoordinator(); _sendLock = new SemaphoreSlim(1); _state = new InterlockedInt32(State.Initial); _commandEventHelper = new CommandEventHelper(eventSubscriber); eventSubscriber.TryGetEventHandler(out _failedEventHandler); eventSubscriber.TryGetEventHandler(out _closingEventHandler); eventSubscriber.TryGetEventHandler(out _closedEventHandler); eventSubscriber.TryGetEventHandler(out _openingEventHandler); eventSubscriber.TryGetEventHandler(out _openedEventHandler); eventSubscriber.TryGetEventHandler(out _failedOpeningEventHandler); eventSubscriber.TryGetEventHandler(out _receivingMessageEventHandler); eventSubscriber.TryGetEventHandler(out _receivedMessageEventHandler); eventSubscriber.TryGetEventHandler(out _failedReceivingMessageEventHandler); eventSubscriber.TryGetEventHandler(out _sendingMessagesEventHandler); eventSubscriber.TryGetEventHandler(out _sentMessagesEventHandler); eventSubscriber.TryGetEventHandler(out _failedSendingMessagesEvent); }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionOpeningFailedEvent" /> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="connectionSettings">The connection settings.</param> /// <param name="exception">The exception.</param> /// <param name="operationId">The operation identifier.</param> public ConnectionOpeningFailedEvent(ConnectionId connectionId, ConnectionSettings connectionSettings, Exception exception, long? operationId) { _connectionId = connectionId; _connectionSettings = connectionSettings; _exception = exception; _operationId = operationId; }
/// <summary> /// Maps the specified response to a custom exception (if possible). /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="response">The response.</param> /// <returns> /// The custom exception (or null if the response could not be mapped to a custom exception). /// </returns> public static Exception Map(ConnectionId connectionId, BsonDocument response) { BsonValue code; if (response.TryGetValue("code", out code) && code.IsNumeric) { switch (code.ToInt32()) { case 50: case 13475: case 16986: case 16712: return new MongoExecutionTimeoutException(connectionId, message: "Operation exceeded time limit."); } } // the server sometimes sends a response that is missing the "code" field but does have an "errmsg" field BsonValue errmsg; if (response.TryGetValue("errmsg", out errmsg) && errmsg.IsString) { if (errmsg.AsString.Contains("exceeded time limit") || errmsg.AsString.Contains("execution terminated")) { return new MongoExecutionTimeoutException(connectionId, message: "Operation exceeded time limit."); } } return null; }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionSendingMessagesFailedEvent" /> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="requestIds">The request ids.</param> /// <param name="exception">The exception.</param> /// <param name="operationId">The operation identifier.</param> public ConnectionSendingMessagesFailedEvent(ConnectionId connectionId, IReadOnlyList<int> requestIds, Exception exception, long? operationId) { _connectionId = connectionId; _requestIds = requestIds; _exception = exception; _operationId = operationId; }
public void LocalValues_of_2_ids_should_not_be_the_same_when_automically_constructed() { var subject = new ConnectionId(__serverId); var subject2 = new ConnectionId(__serverId); subject.LocalValue.Should().NotBe(subject2.LocalValue); }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionSentMessagesEvent" /> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="requestIds">The request ids.</param> /// <param name="length">The length.</param> /// <param name="networkDuration">The duration of time spent on the network.</param> /// <param name="serializationDuration">The duration of time spent serializing the messages.</param> public ConnectionSentMessagesEvent(ConnectionId connectionId, IReadOnlyList<int> requestIds, int length, TimeSpan networkDuration, TimeSpan serializationDuration) { _connectionId = connectionId; _requestIds = requestIds; _length = length; _networkDuration = networkDuration; _serializationDuration = serializationDuration; }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionReceivedMessageEvent" /> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="responseTo">The id of the message we received a response to.</param> /// <param name="length">The length of the received message.</param> /// <param name="networkDuration">The duration of network time it took to receive the message.</param> /// <param name="deserializationDuration">The duration of deserialization time it took to receive the message.</param> public ConnectionReceivedMessageEvent(ConnectionId connectionId, int responseTo, int length, TimeSpan networkDuration, TimeSpan deserializationDuration) { _connectionId = connectionId; _responseTo = responseTo; _length = length; _networkDuration = networkDuration; _deserializationDuration = deserializationDuration; }
// static methods private static string FormatMessage(ConnectionId connectionId, long cursorId) { return string.Format( "Cursor {0} not found on server {1} using connection {2}.", cursorId, EndPointHelper.ToString(connectionId.ServerId.EndPoint), connectionId.ServerValue); }
public static string Format(ConnectionId id) { if (id.ServerValue.HasValue) { return id.LocalValue.ToString() + "-" + id.ServerValue.Value.ToString(); } return id.LocalValue.ToString(); }
/// <summary> /// Initializes a new instance of the <see cref="CommandSucceededEvent"/> struct. /// </summary> /// <param name="commandName">Name of the command.</param> /// <param name="reply">The reply.</param> /// <param name="operationId">The operation identifier.</param> /// <param name="requestId">The request identifier.</param> /// <param name="connectionId">The connection identifier.</param> /// <param name="duration">The duration.</param> public CommandSucceededEvent(string commandName, BsonDocument reply, long? operationId, int requestId, ConnectionId connectionId, TimeSpan duration) { _commandName = Ensure.IsNotNullOrEmpty(commandName, "commandName"); _reply = Ensure.IsNotNull(reply, "reply"); _connectionId = Ensure.IsNotNull(connectionId, "connectionId"); _operationId = operationId; _requestId = requestId; _duration = duration; }
/// <summary> /// Initializes a new instance of the <see cref="CommandStartedEvent" /> class. /// </summary> /// <param name="commandName">Name of the command.</param> /// <param name="command">The command.</param> /// <param name="databaseNamespace">The database namespace.</param> /// <param name="operationId">The operation identifier.</param> /// <param name="requestId">The request identifier.</param> /// <param name="connectionId">The connection identifier.</param> public CommandStartedEvent(string commandName, BsonDocument command, DatabaseNamespace databaseNamespace, long? operationId, int requestId, ConnectionId connectionId) { _commandName = Ensure.IsNotNullOrEmpty(commandName, "commandName"); _command = Ensure.IsNotNull(command, "command"); _databaseNamespace = Ensure.IsNotNull(databaseNamespace, "databaseNamespace"); _connectionId = Ensure.IsNotNull(connectionId, "connectionId"); _operationId = operationId; _requestId = requestId; }
internal TcpConnection(ConnectionId connectionId, uint sequenceNumber, Action<TcpConnection>removeCallback, string snifferType) { ConnectionId = connectionId; Source = connectionId.Source; Destination = connectionId.Destination; InitialSequenceNumber = sequenceNumber; RemoveCallback = () => removeCallback(this); SnifferType = snifferType; }
public virtual bool Equals(ConnectionId that) { if(!Equals(this.Value, that.Value)) { return false; } return true; }
/// <summary> /// Initializes a new instance of the <see cref="CommandFailedEvent" /> struct. /// </summary> /// <param name="commandName">Name of the command.</param> /// <param name="exception">The exception.</param> /// <param name="operationId">The operation identifier.</param> /// <param name="requestId">The request identifier.</param> /// <param name="connectionId">The connection identifier.</param> /// <param name="duration">The duration.</param> public CommandFailedEvent(string commandName, Exception exception, long? operationId, int requestId, ConnectionId connectionId, TimeSpan duration) { _commandName = Ensure.IsNotNullOrEmpty(commandName, "commandName"); _exception = Ensure.IsNotNull(exception, "exception"); _connectionId = Ensure.IsNotNull(connectionId, "connectionId"); _operationId = operationId; _requestId = requestId; _duration = duration; }
/// <summary> /// Initializes a new instance of the <see cref="MongoBulkWriteException" /> class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="writeErrors">The write errors.</param> /// <param name="writeConcernError">The write concern error.</param> public MongoBulkWriteException( ConnectionId connectionId, IEnumerable<BulkWriteError> writeErrors, WriteConcernError writeConcernError) : base(connectionId, message: FormatMessage(writeErrors, writeConcernError)) { _writeErrors = writeErrors.ToList(); _writeConcernError = writeConcernError; }
private void Receive(IpPacket ipPacket) { var protocol = ipPacket.Protocol; if (protocol != IPProtocolType.TCP) { return; } if (ipPacket.PayloadPacket == null) { return; } var tcpPacket = new TcpPacket(new ByteArraySegment(ipPacket.PayloadPacket.BytesHighPerformance)); var isFirstPacket = tcpPacket.Syn; var sourceIp = new IPAddress(ipPacket.SourceAddress.GetAddressBytes()).ToString(); var destinationIp = new IPAddress(ipPacket.DestinationAddress.GetAddressBytes()).ToString(); var connectionId = new ConnectionId(sourceIp, tcpPacket.SourcePort, destinationIp, tcpPacket.DestinationPort); lock (_lock) { TcpConnection connection; bool isInterestingConnection; if (isFirstPacket) { connection = new TcpConnection(connectionId, tcpPacket.SequenceNumber); OnNewConnection(connection); isInterestingConnection = connection.HasSubscribers; if (!isInterestingConnection) { return; } _connections[connectionId] = connection; Debug.Assert(ipPacket.PayloadPacket.PayloadData.Length == 0); } else { isInterestingConnection = _connections.TryGetValue(connectionId, out connection); if (!isInterestingConnection) { return; } if (!string.IsNullOrEmpty(TcpLogFile)) { File.AppendAllText(TcpLogFile, string.Format("{0} {1}+{4} | {2} {3}+{4} ACK {5} ({6})\r\n", connection.CurrentSequenceNumber, tcpPacket.SequenceNumber, connection.BytesReceived, connection.SequenceNumberToBytesReceived(tcpPacket.SequenceNumber), ipPacket.PayloadLength, tcpPacket.AcknowledgmentNumber, connection.BufferedPacketDescription)); } connection.HandleTcpReceived(tcpPacket.SequenceNumber, new ByteArraySegment(ipPacket.PayloadPacket.PayloadData)); } } }
/// <summary> /// Initializes a new instance of the <see cref="MongoWriteException" /> class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="writeError">The write error.</param> /// <param name="writeConcernError">The write concern error.</param> /// <param name="innerException">The inner exception.</param> public MongoWriteException( ConnectionId connectionId, WriteError writeError, WriteConcernError writeConcernError, Exception innerException) : base(connectionId, FormatMessage(writeError, writeConcernError), innerException) { _writeError = writeError; _writeConcernError = writeConcernError; }
public MongoBulkWriteOperationExceptionTests() { _connectionId = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2).WithServerValue(3); _processedRequests = new List<WriteRequest>(); _upserts = new List<BulkWriteOperationUpsert>(); _result = new BulkWriteOperationResult.Acknowledged(1, 2, 3, 4, 5, _processedRequests, _upserts); _writeErrors = new List<BulkWriteOperationError>(); _writeConcernError = new BulkWriteConcernError(1, "message", new BsonDocument("x", 1)); _unprocessedRequests = new List<WriteRequest>(); }
public static void ThrowIfHasWriteConcernError(ConnectionId connectionId, BsonDocument result) { BsonValue value; if (result.TryGetValue("writeConcernError", out value)) { var message = (string)value.AsBsonDocument.GetValue("errmsg", null); var writeConcernResult = new WriteConcernResult(result); throw new MongoWriteConcernException(connectionId, message, writeConcernResult); } }
public void OneTimeSetUp() { _connectionId = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2); var processedRequests = new[] { new InsertOneModel<BsonDocument>(new BsonDocument("b", 1)) }; var upserts = new BulkWriteUpsert[0]; _bulkWriteResult = new BulkWriteResult<BsonDocument>.Acknowledged(1, 1, 0, 0, 0, processedRequests, upserts); _writeConcernError = new WriteConcernError(11, "funny", new BsonDocument("c", 1)); _writeErrors = new[] { new BulkWriteError(10, ServerErrorCategory.Uncategorized, 1, "blah", new BsonDocument("a", 1)) }; _unprocessedRequests = new[] { new InsertOneModel<BsonDocument>(new BsonDocument("a", 1)) }; }
public EventsResult events(ConnectionId connectionId) { try { if (!verifyUser(connectionId.connectionId)) return new EventsResult(); List<UserEvents> myEvents1 = new List<UserEvents>(); List<UserEvents> attendingEvents1 = new List<UserEvents>(); List<string> s1, s2; int userId = (from c in _entity.connections where c.connection_id == connectionId.connectionId select c.user_id). FirstOrDefault(); var e11 = (from e in _entity.collaborators where e.user_id == userId select e.event_id).ToList(); foreach (var id1 in e11) { var currEvent = (from e in _entity.events where e.id == id1 select e).FirstOrDefault(); myEvents1.Add(new UserEvents() { eventId = currEvent.id, createdBy = currEvent.user.name, date = currEvent.date.HasValue ? currEvent.date.Value.ToLongDateString() : "", name = currEvent.name, time = currEvent.time, venue = currEvent.venue, isOwner = currEvent.user_id == userId ? 1 : 0, code = currEvent.code }); } var e12 = (from e in _entity.user_attending where e.user_id == userId select e.event_id).ToList(); foreach (var id1 in e12) { var currEvent = (from e in _entity.events where e.id == id1 select e).FirstOrDefault(); myEvents1.Add(new UserEvents() { eventId = currEvent.id, createdBy = currEvent.user.name, date = currEvent.date.HasValue ? currEvent.date.Value.ToLongDateString() : "", name = currEvent.name, time = currEvent.time, venue = currEvent.venue, isOwner = currEvent.user_id == userId ? 1 : 0, code = currEvent.code }); } return new EventsResult() { myEvents = myEvents1, attendingEvents = attendingEvents1 }; } catch (Exception) { return new EventsResult(); } }
public void ToStringTest() { { var connectionId = new ConnectionId() { Value1 = 1, Value2 = 2, Value3 = 3, }; Assert.AreEqual("0000000000000001000000000000000200000003", connectionId.ToString()); } { var connectionId = new ConnectionId() { Value1 = -1, Value2 = -1, Value3 = -1, }; Assert.AreEqual("ffffffffffffffffffffffffffffffffffffffff", connectionId.ToString()); } }
// constructors /// <summary> /// Initializes a new instance of the <see cref="MongoBulkWriteOperationException" /> class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="result">The result.</param> /// <param name="writeErrors">The write errors.</param> /// <param name="writeConcernError">The write concern error.</param> /// <param name="unprocessedRequests">The unprocessed requests.</param> public MongoBulkWriteOperationException( ConnectionId connectionId, BulkWriteOperationResult result, IReadOnlyList<BulkWriteOperationError> writeErrors, BulkWriteConcernError writeConcernError, IReadOnlyList<WriteRequest> unprocessedRequests) : base(connectionId, FormatMessage(writeErrors, writeConcernError)) { _result = result; _writeErrors = writeErrors; _writeConcernError = writeConcernError; _unprocessedRequests = unprocessedRequests; }
public void Equals_should_return_correct_results() { var serverId1 = __serverId; var serverId2 = new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27018)); var localValue1 = 10; var localValue2 = 11; var subject1 = new ConnectionId(serverId1, localValue1); var subject2 = new ConnectionId(serverId1, localValue1); var subject3 = new ConnectionId(serverId1, localValue2); var subject4 = new ConnectionId(serverId2, localValue1); subject1.Equals(subject2).Should().BeTrue(); subject1.Equals(subject3).Should().BeFalse(); subject1.Equals(subject4).Should().BeFalse(); }
public void Equals_should_return_correct_results() { var connectionId1 = new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27018)), 10); var connectionId2 = new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27018)), 10); var isMasterResult1 = new IsMasterResult(new BsonDocument("x", 1)); var isMasterResult2 = new IsMasterResult(new BsonDocument("x", 2)); var buildInfoResult1 = new BuildInfoResult(new BsonDocument("version", "2.6.3")); var buildInfoResult2 = new BuildInfoResult(new BsonDocument("version", "2.4.10")); var subject1 = new ConnectionDescription(connectionId1, isMasterResult1, buildInfoResult1); var subject2 = new ConnectionDescription(connectionId1, isMasterResult1, buildInfoResult1); var subject3 = new ConnectionDescription(connectionId1, isMasterResult1, buildInfoResult2); var subject4 = new ConnectionDescription(connectionId1, isMasterResult2, buildInfoResult1); var subject5 = new ConnectionDescription(connectionId2, isMasterResult1, buildInfoResult1); subject1.Equals(subject2).Should().BeTrue(); subject1.Equals(subject3).Should().BeFalse(); subject1.Equals(subject4).Should().BeFalse(); subject1.Equals(subject5).Should().BeFalse(); }
// public methods public Exception ToWriteConcernException(ConnectionId connectionId, MongoBulkWriteOperationException bulkWriteException) { var writeConcernResult = ToWriteConcernResult(bulkWriteException.Result, bulkWriteException); var exception = ExceptionMapper.Map(connectionId, writeConcernResult.Response); if (exception == null) { exception = ExceptionMapper.Map(connectionId, writeConcernResult); } if (exception == null) { exception = new MongoWriteConcernException(connectionId, bulkWriteException.Message, writeConcernResult); } var writeConcernException = exception as MongoWriteConcernException; if (writeConcernException != null) { writeConcernException.Data["results"] = new List<WriteConcernResult>(new[] { writeConcernResult }); } return exception; // usually a WriteConcernException unless ExceptionMapper chose a different type }
// constructors /// <summary> /// Initializes a new instance of the MongoGridFSException class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="message">The error message.</param> public MongoGridFSException(ConnectionId connectionId, string message) : base(connectionId, message: message) { }
public void SendMessage(ConnectionId connectionId, byte[] data, bool isReliable) { SendMessage(connectionId, data, 0, data.Length, isReliable); }
public StreamSocketOutput(ConnectionId connectionId, Stream outputStream, MemoryPool memory) { _connectionId = connectionId; _outputStream = outputStream; _memory = memory; }
public override string ToString() { return(ConnectionId.ToString()); }
// constructors public SaslConversation(ConnectionId connectionId) { _connectionId = connectionId; _itemsNeedingDisposal = new List <IDisposable>(); }
public void OnConnectionEstablished(ConnectionId newPeerConnectionId, IPEndPoint endpoint) { //CreateWhisp(newPeerConnectionId); }
/// <summary> /// Initializes a new instance of the <see cref="MongoAuthenticationException"/> class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="message">The error message.</param> /// <param name="innerException">The inner exception.</param> public MongoAuthenticationException(ConnectionId connectionId, string message, Exception innerException) : base(connectionId, message, innerException) { }
// constructors /// <summary> /// Initializes a new instance of the <see cref="MongoQueryException"/> class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="message">The message.</param> /// <param name="query">The query.</param> /// <param name="queryResult">The query result.</param> public MongoQueryException(ConnectionId connectionId, string message, BsonDocument query, BsonDocument queryResult) : base(connectionId, message, null) { _query = query; _queryResult = queryResult; }
// constructors /// <summary> /// Initializes a new instance of the WriteConcernException class. /// </summary> /// <param name="message">The error message.</param> /// <param name="writeConcernResult">The command result.</param> public MongoWriteConcernException(ConnectionId connectionId, string message, WriteConcernResult writeConcernResult) : base(connectionId, message, null, writeConcernResult.Response) { _writeConcernResult = Ensure.IsNotNull(writeConcernResult, "writeConcernResult"); }
// constructors /// <summary> /// Initializes a new instance of the <see cref="MongoMessageNotSentException"/> class. /// </summary> /// <param name="connectionId">The connection identifier.</param> public MongoMessageNotSentException(ConnectionId connectionId) : base(connectionId, "Message not sent.") { }
protected bool Equals(TcpClientConnection other) { return(Equals(Ip, other.Ip) && ConnectionId.Equals(other.ConnectionId)); }
/// <summary> /// Disconnects the given connection id. /// </summary> /// <param name="id">Id to disconnect</param> public void Disconnect(ConnectionId id) { UnityWebRtcNetworkDisconnect(mReference, id.id); }
/// <summary> /// Initializes a new instance of the <see cref="MongoExecutionTimeoutException"/> class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="message">The error message.</param> /// <param name="innerException">The inner exception.</param> public MongoExecutionTimeoutException(ConnectionId connectionId, string message, Exception innerException) : base(connectionId, message, innerException) { }
/// <summary> /// Handler of call events. /// /// Can be customized in via subclasses. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void Call_CallEvent(object sender, CallEventArgs e) { switch (e.Type) { case CallEventType.CallAccepted: //Outgoing call was successful or an incoming call arrived Append("Connection established"); mRemoteUserId = ((CallAcceptedEventArgs)e).ConnectionId; Debug.Log("New connection with id: " + mRemoteUserId + " audio:" + mCall.HasAudioTrack(mRemoteUserId) + " video:" + mCall.HasVideoTrack(mRemoteUserId)); break; case CallEventType.CallEnded: //Call was ended / one of the users hung up -> reset the app Append("Call ended"); InternalResetCall(); break; case CallEventType.ListeningFailed: //listening for incoming connections failed //this usually means a user is using the string / room name already to wait for incoming calls //try to connect to this user //(note might also mean the server is down or the name is invalid in which case call will fail as well) mCall.Call(mUseAddress); break; case CallEventType.ConnectionFailed: { Byn.Media.ErrorEventArgs args = e as Byn.Media.ErrorEventArgs; Append("Connection failed error: " + args.ErrorMessage); InternalResetCall(); } break; case CallEventType.ConfigurationFailed: { Byn.Media.ErrorEventArgs args = e as Byn.Media.ErrorEventArgs; Append("Configuration failed error: " + args.ErrorMessage); InternalResetCall(); } break; case CallEventType.FrameUpdate: { //new frame received from webrtc (either from local camera or network) if (e is FrameUpdateEventArgs) { UpdateFrame((FrameUpdateEventArgs)e); } break; } case CallEventType.Message: { //text message received MessageEventArgs args = e as MessageEventArgs; Append(args.Content); break; } case CallEventType.WaitForIncomingCall: { //the chat app will wait for another app to connect via the same string WaitForIncomingCallEventArgs args = e as WaitForIncomingCallEventArgs; Append("Waiting for incoming call address: " + args.Address); break; } } }
private void RegisterPlayer(ConnectionId connectionId, ApprovalSecret approvalSecret, Action <ApprovalSecret> approve, Action <ApprovalSecret> deny) { _coroutineScheduler.Run(RegisterPlayerInternal(connectionId, approvalSecret, approve, deny)); }
// constructors /// <summary> /// Initializes a new instance of the <see cref="MongoNodeIsRecoveringException"/> class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="result">The result.</param> public MongoNodeIsRecoveringException(ConnectionId connectionId, BsonDocument result) : base(connectionId, "Server returned node is recovering error.") { _result = Ensure.IsNotNull(result, "result"); }
public void HandleChannelException_should_update_topology_as_expected_on_network_error_or_timeout( string errorType, bool shouldUpdateTopology) { var serverId = new ServerId(_clusterId, _endPoint); var connectionId = new ConnectionId(serverId); Exception innerMostException; switch (errorType) { case "MongoConnectionExceptionWithSocketTimeout": innerMostException = new SocketException((int)SocketError.TimedOut); break; case nameof(MongoConnectionException): innerMostException = new SocketException((int)SocketError.NetworkUnreachable); break; default: throw new ArgumentException("Unknown error type."); } var operationUsingChannelException = new MongoConnectionException(connectionId, "Oops", new IOException("Cry", innerMostException)); var mockConnection = new Mock <IConnectionHandle>(); var isMasterResult = new IsMasterResult(new BsonDocument { { "compressors", new BsonArray() } }); // the server version doesn't matter when we're not testing MongoNotPrimaryExceptions, but is needed when // Server calls ShouldClearConnectionPoolForException var buildInfoResult = new BuildInfoResult(new BsonDocument { { "version", "4.4.0" } }); mockConnection.SetupGet(c => c.Description) .Returns(new ConnectionDescription(new ConnectionId(serverId, 0), isMasterResult, buildInfoResult)); var mockConnectionPool = new Mock <IConnectionPool>(); mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny <CancellationToken>())).Returns(mockConnection.Object); mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny <CancellationToken>())).ReturnsAsync(mockConnection.Object); var mockConnectionPoolFactory = new Mock <IConnectionPoolFactory>(); mockConnectionPoolFactory .Setup(f => f.CreateConnectionPool(It.IsAny <ServerId>(), _endPoint)) .Returns(mockConnectionPool.Object); var mockMonitorServerInitialDescription = new ServerDescription(serverId, _endPoint).With(reasonChanged: "Initial D", type: ServerType.Unknown); var mockServerMonitor = new Mock <IServerMonitor>(); mockServerMonitor.SetupGet(m => m.Description).Returns(mockMonitorServerInitialDescription); mockServerMonitor.SetupGet(m => m.Lock).Returns(new object()); var mockServerMonitorFactory = new Mock <IServerMonitorFactory>(); mockServerMonitorFactory.Setup(f => f.Create(It.IsAny <ServerId>(), _endPoint)).Returns(mockServerMonitor.Object); var subject = new Server(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, mockConnectionPoolFactory.Object, mockServerMonitorFactory.Object, _capturedEvents, _serverApi); subject.Initialize(); var heartbeatDescription = mockMonitorServerInitialDescription.With(reasonChanged: "Heartbeat", type: ServerType.Standalone); mockServerMonitor.Setup(m => m.Description).Returns(heartbeatDescription); mockServerMonitor.Raise( m => m.DescriptionChanged += null, new ServerDescriptionChangedEventArgs(mockMonitorServerInitialDescription, heartbeatDescription)); subject.Description.Should().Be(heartbeatDescription); subject.HandleChannelException(mockConnection.Object, operationUsingChannelException); if (shouldUpdateTopology) { subject.Description.Type.Should().Be(ServerType.Unknown); subject.Description.ReasonChanged.Should().Contain("ChannelException"); } else { subject.Description.Should().Be(heartbeatDescription); } }
private TCommandResult ProcessReply(ConnectionId connectionId, ReplyMessage <RawBsonDocument> reply) { if (reply.NumberReturned == 0) { throw new MongoCommandException(connectionId, "Command returned no documents.", _command); } if (reply.NumberReturned > 1) { throw new MongoCommandException(connectionId, "Command returned multiple documents.", _command); } if (reply.QueryFailure) { var failureDocument = reply.QueryFailureDocument; throw ExceptionMapper.Map(connectionId, failureDocument) ?? new MongoCommandException(connectionId, "Command failed.", _command, failureDocument); } using (var rawDocument = reply.Documents[0]) { if (!rawDocument.GetValue("ok", false).ToBoolean()) { var materializedDocument = new BsonDocument(rawDocument); var commandName = _command.GetElement(0).Name; if (commandName == "$query") { commandName = _command["$query"].AsBsonDocument.GetElement(0).Name; } var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, materializedDocument, "errmsg"); if (notPrimaryOrNodeIsRecoveringException != null) { throw notPrimaryOrNodeIsRecoveringException; } string message; BsonValue errmsgBsonValue; if (materializedDocument.TryGetValue("errmsg", out errmsgBsonValue) && errmsgBsonValue.IsString) { var errmsg = errmsgBsonValue.ToString(); message = string.Format("Command {0} failed: {1}.", commandName, errmsg); } else { message = string.Format("Command {0} failed.", commandName); } var mappedException = ExceptionMapper.Map(connectionId, materializedDocument); if (mappedException != null) { throw mappedException; } throw new MongoCommandException(connectionId, message, _command, materializedDocument); } using (var stream = new ByteBufferStream(rawDocument.Slice, ownsByteBuffer: false)) { var encoderFactory = new BinaryMessageEncoderFactory(stream, _messageEncoderSettings); var encoder = (ReplyMessageBinaryEncoder <TCommandResult>)encoderFactory.GetReplyMessageEncoder <TCommandResult>(_resultSerializer); using (var reader = encoder.CreateBinaryReader()) { var context = BsonDeserializationContext.CreateRoot(reader); return(_resultSerializer.Deserialize(context)); } } } }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionOpeningEvent"/> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="connectionSettings">The connection settings.</param> public ConnectionOpeningEvent(ConnectionId connectionId, ConnectionSettings connectionSettings) { _connectionId = connectionId; _connectionSettings = connectionSettings; }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionErrorOpeningEvent"/> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="connectionSettings">The connection settings.</param> /// <param name="exception">The exception.</param> public ConnectionErrorOpeningEvent(ConnectionId connectionId, ConnectionSettings connectionSettings, Exception exception) { _connectionId = connectionId; _connectionSettings = connectionSettings; _exception = exception; }
private TCommandResult ProcessResponse(ConnectionId connectionId, CommandMessage responseMessage) { using (new CommandMessageDisposer(responseMessage)) { var rawDocument = responseMessage.Sections.OfType <Type0CommandMessageSection <RawBsonDocument> >().Single().Document; var binaryReaderSettings = new BsonBinaryReaderSettings(); if (_messageEncoderSettings != null) { binaryReaderSettings.Encoding = _messageEncoderSettings.GetOrDefault <UTF8Encoding>(MessageEncoderSettingsName.ReadEncoding, Utf8Encodings.Strict); #pragma warning disable 618 if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2) { binaryReaderSettings.GuidRepresentation = _messageEncoderSettings.GetOrDefault <GuidRepresentation>(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy); } #pragma warning restore 618 } ; BsonValue clusterTime; if (rawDocument.TryGetValue("$clusterTime", out clusterTime)) { // note: we are assuming that _session is an instance of ClusterClockAdvancingClusterTime // and that calling _session.AdvanceClusterTime will have the side effect of advancing the cluster's ClusterTime also var materializedClusterTime = ((RawBsonDocument)clusterTime).Materialize(binaryReaderSettings); _session.AdvanceClusterTime(materializedClusterTime); } BsonValue operationTime; if (rawDocument.TryGetValue("operationTime", out operationTime)) { _session.AdvanceOperationTime(operationTime.AsBsonTimestamp); } if (rawDocument.GetValue("ok", false).ToBoolean()) { if (rawDocument.TryGetValue("recoveryToken", out var rawRecoveryToken)) { var recoveryToken = ((RawBsonDocument)rawRecoveryToken).Materialize(binaryReaderSettings); _session.CurrentTransaction.RecoveryToken = recoveryToken; } } else { var materializedDocument = rawDocument.Materialize(binaryReaderSettings); var commandName = _command.GetElement(0).Name; if (commandName == "$query") { commandName = _command["$query"].AsBsonDocument.GetElement(0).Name; } var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, _command, materializedDocument, "errmsg"); if (notPrimaryOrNodeIsRecoveringException != null) { throw notPrimaryOrNodeIsRecoveringException; } var mappedException = ExceptionMapper.Map(connectionId, materializedDocument); if (mappedException != null) { throw mappedException; } string message; BsonValue errmsgBsonValue; if (materializedDocument.TryGetValue("errmsg", out errmsgBsonValue) && errmsgBsonValue.IsString) { var errmsg = errmsgBsonValue.ToString(); message = string.Format("Command {0} failed: {1}.", commandName, errmsg); } else { message = string.Format("Command {0} failed.", commandName); } var exception = new MongoCommandException(connectionId, message, _command, materializedDocument); // https://jira.mongodb.org/browse/CSHARP-2678 if (IsRetryableWriteExceptionAndDeploymentDoesNotSupportRetryableWrites(exception)) { throw WrapNotSupportedRetryableWriteException(exception); } else { throw exception; } } if (rawDocument.Contains("writeConcernError")) { var materializedDocument = rawDocument.Materialize(binaryReaderSettings); var writeConcernError = materializedDocument["writeConcernError"].AsBsonDocument; var message = writeConcernError.AsBsonDocument.GetValue("errmsg", null)?.AsString; var writeConcernResult = new WriteConcernResult(materializedDocument); throw new MongoWriteConcernException(connectionId, message, writeConcernResult); } using (var stream = new ByteBufferStream(rawDocument.Slice, ownsBuffer: false)) { using (var reader = new BsonBinaryReader(stream, binaryReaderSettings)) { var context = BsonDeserializationContext.CreateRoot(reader); return(_resultSerializer.Deserialize(context)); } } } }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionClosingEvent" /> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="operationId">The operation identifier.</param> public ConnectionClosingEvent(ConnectionId connectionId, long?operationId) { _connectionId = connectionId; _operationId = operationId; }
/// <summary> /// Initializes a new instance of the <see cref="CommandSucceededEvent"/> struct. /// </summary> /// <param name="commandName">Name of the command.</param> /// <param name="reply">The reply.</param> /// <param name="operationId">The operation identifier.</param> /// <param name="requestId">The request identifier.</param> /// <param name="connectionId">The connection identifier.</param> /// <param name="duration">The duration.</param> public CommandSucceededEvent(string commandName, BsonDocument reply, long?operationId, int requestId, ConnectionId connectionId, TimeSpan duration) { _commandName = Ensure.IsNotNullOrEmpty(commandName, "commandName"); _reply = Ensure.IsNotNull(reply, "reply"); _connectionId = Ensure.IsNotNull(connectionId, "connectionId"); _operationId = operationId; _requestId = requestId; _duration = duration; _timestamp = DateTime.UtcNow; }
/// <summary> /// Initializes a new instance of the <see cref="MongoDuplicateKeyException" /> class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="message">The error message.</param> /// <param name="commandResult">The command result.</param> public MongoDuplicateKeyException(ConnectionId connectionId, string message, WriteConcernResult commandResult) : base(connectionId, message, commandResult) { }
/// <summary> /// Initializes a new instance of the MongoGridFSException class. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="message">The error message.</param> /// <param name="innerException">The inner exception.</param> public MongoGridFSException(ConnectionId connectionId, string message, Exception innerException) : base(connectionId, message, innerException) { }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionBeforeClosingEvent"/> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> public ConnectionBeforeClosingEvent(ConnectionId connectionId) { _connectionId = connectionId; }
private void OnClientDisconnected(ConnectionId connectionId) { _state = GameState.Disconnected; }
private void ApplyApplicationError(BsonDocument applicationError) { var expectedKeys = new[] { "address", "generation", // optional "maxWireVersion", "when", "type", "response" // optional }; JsonDrivenHelper.EnsureAllFieldsAreValid(applicationError, expectedKeys); var address = applicationError["address"].AsString; var endPoint = EndPointHelper.Parse(address); var server = (Server)_serverFactory.GetServer(endPoint); var connectionId = new ConnectionId(server.ServerId); var type = applicationError["type"].AsString; var maxWireVersion = applicationError["maxWireVersion"].AsInt32; Exception simulatedException = null; switch (type) { case "command": var response = applicationError["response"].AsBsonDocument; var command = new BsonDocument("Link", "start!"); simulatedException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, command, response, "errmsg"); // can return null break; case "network": { var innerException = CoreExceptionHelper.CreateException("IOExceptionWithNetworkUnreachableSocketException"); simulatedException = new MongoConnectionException(connectionId, "Ignorance, yet knowledge.", innerException); break; } case "timeout": { var innerException = CoreExceptionHelper.CreateException("IOExceptionWithTimedOutSocketException"); simulatedException = new MongoConnectionException(connectionId, "Chaos, yet harmony.", innerException); break; } default: throw new ArgumentException($"Unsupported value of {type} for type"); } var mockConnection = new Mock <IConnectionHandle>(); var helloResult = new HelloResult( new BsonDocument { { "compressors", new BsonArray() }, { "maxWireVersion", maxWireVersion } }); mockConnection .SetupGet(c => c.Description) .Returns(new ConnectionDescription(connectionId, helloResult)); int generation = 0; if (applicationError.TryGetValue("generation", out var generationBsonValue)) { generation = generationBsonValue.AsInt32; if (simulatedException is MongoConnectionException mongoConnectionException) { mongoConnectionException.Generation = generation; } } mockConnection.SetupGet(c => c.Generation).Returns(generation); mockConnection .SetupGet(c => c.Generation) .Returns(generation); if (simulatedException != null) { var when = applicationError["when"].AsString; switch (when) { case "beforeHandshakeCompletes": server.HandleBeforeHandshakeCompletesException(simulatedException); break; case "afterHandshakeCompletes": server.HandleChannelException(mockConnection.Object, simulatedException); break; default: throw new ArgumentException($"Unsupported value of {when} for when."); } } }
/// <summary> /// Sends a byte array /// </summary> /// <param name="conId">Connection id the message should be delivered to.</param> /// <param name="data">Content/Buffer that contains the content</param> /// <param name="offset">Start index of the content in data</param> /// <param name="length">Length of the content in data</param> /// <param name="reliable">True to use the ordered, reliable transfer, false for unordered and unreliable</param> public void SendData(ConnectionId conId, byte[] data, int offset, int length, bool reliable) { UnityWebRtcNetworkSendData(mReference, conId.id, data, offset, length, reliable); }
protected override void ProcessIncomingMessageFromOtherThread(MessageReader reader, IPEndPoint peerAddress, ConnectionId connectionId) { base.ProcessIncomingMessageFromOtherThread(reader, peerAddress, connectionId); }