public void Setup() { InnerTransport = new TestTransport(Self.EndPoint); var configuration = new Mock <IBusConfiguration>(); configuration.Setup(x => x.IsPersistent).Returns(IsPersistent); configuration.Setup(x => x.StartReplayTimeout).Returns(TimeSpan.FromMinutes(60)); PeerDirectory = new Mock <IPeerDirectory>(); PeerDirectory.Setup(dir => dir.GetPeersHandlingMessage(It.IsAny <StartMessageReplayCommand>())).Returns(new[] { PersistencePeer }); PeerDirectory.Setup(dir => dir.GetPeersHandlingMessage(It.IsAny <PersistMessageCommand>())).Returns(new[] { PersistencePeer }); PeerDirectory.Setup(dir => dir.GetPeersHandlingMessage(It.IsAny <MessageHandled>())).Returns(new[] { PersistencePeer }); PeerDirectory.Setup(dir => dir.IsPersistent(AnotherPersistentPeer.Id)).Returns(true); PeerDirectory.Setup(dir => dir.IsPersistent(AnotherNonPersistentPeer.Id)).Returns(false); Transport = new PersistentTransport(configuration.Object, InnerTransport, PeerDirectory.Object); Transport.Configure(Self.Id, "test"); MessagesForwardedToBus = new ConcurrentQueue <TransportMessage>(); Transport.MessageReceived += MessagesForwardedToBus.Enqueue; Transport.OnRegistered(); var startMessageReplayMessage = InnerTransport.Messages.FirstOrDefault(x => x.TransportMessage.MessageTypeId == MessageUtil.TypeId <StartMessageReplayCommand>()); if (startMessageReplayMessage != null) { StartMessageReplayCommand = (StartMessageReplayCommand)startMessageReplayMessage.TransportMessage.ToMessage(); StartMessageReplayCommandTargets = startMessageReplayMessage.Targets; } InnerTransport.Messages.Clear(); }
public void TestTransport_must_associate_successfully_with_another_TestTransport() { //arrange var registry = new AssociationRegistry(); var transportA = new TestTransport(addressA, registry); var transportB = new TestTransport(addressB, registry); //act //must complete returned promises to receive events var localConnectionFuture = transportA.Listen(); localConnectionFuture.Wait(DefaultTimeout); localConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var remoteConnectionFuture = transportB.Listen(); remoteConnectionFuture.Wait(DefaultTimeout); remoteConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var ready = registry.TransportsReady(addressA, addressB); Assert.True(ready); transportA.Associate(addressB); ExpectMsgPf <AssociationHandle>(DefaultTimeout, "Expect InboundAssociation from A", m => m.AsInstanceOf <InboundAssociation>().Association); //assert var associateAttempt = (registry.LogSnapshot().Single(x => x is AssociateAttempt)).AsInstanceOf <AssociateAttempt>(); Assert.Equal(addressA, associateAttempt.LocalAddress); Assert.Equal(addressB, associateAttempt.RemoteAddress); }
public Collaborators(AssociationRegistry registry, TestTransport transport, TestAssociationHandle handle, TestFailureDetector failureDetector) { FailureDetector = failureDetector; Handle = handle; Transport = transport; Registry = registry; }
public void TestTransport_must_associate_successfully_with_another_TestTransport() { //arrange var registry = new AssociationRegistry(); var transportA = new TestTransport(addressA, registry); var transportB = new TestTransport(addressB, registry); //act //must complete returned promises to receive events var localConnectionFuture = transportA.Listen(); localConnectionFuture.Wait(DefaultTimeout); localConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var remoteConnectionFuture = transportB.Listen(); remoteConnectionFuture.Wait(DefaultTimeout); remoteConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var ready = registry.TransportsReady(addressA, addressB); Assert.True(ready); transportA.Associate(addressB); expectMsgPF<AssociationHandle>(DefaultTimeout, "Expect InboundAssociation from A", m => m.AsInstanceOf<InboundAssociation>().Association); //assert var associateAttempt = (registry.LogSnapshot().Single(x => x is AssociateAttempt)).AsInstanceOf<AssociateAttempt>(); Assert.Equal(addressA, associateAttempt.LocalAddress); Assert.Equal(addressB, associateAttempt.RemoteAddress); }
public void Setup() { _transportMessageSerializer = new TransportMessageSerializer(); _configurationMock = new Mock <IPersistenceConfiguration>(); _configurationMock.Setup(conf => conf.SafetyPhaseDuration).Returns(500.Milliseconds()); _configurationMock.SetupGet(x => x.ReplayBatchSize).Returns(_replayBatchSize); _configurationMock.SetupGet(x => x.ReplayUnackedMessageCountThatReleasesNextBatch).Returns(200); _selfPeer = new Peer(new PeerId("Abc.Testing.Self"), "tcp://abctest:888"); _targetPeer = new Peer(new PeerId("Abc.Testing.Target"), "tcp://abcother:123"); _anotherPeer = new Peer(new PeerId("Abc.Testing.Another"), "tcp://abcanother:123"); _bus = new TestBus(); _transport = new TestTransport(_selfPeer, "test"); _messageMatcherMock = new Mock <IInMemoryMessageMatcher>(); _replayId = Guid.NewGuid(); _insertedMessages = new List <byte[]>(); var readerMock = new Mock <IMessageReader>(); _storageMock = new Mock <IStorage>(); _storageMock.Setup(x => x.CreateMessageReader(It.IsAny <PeerId>())).Returns(readerMock.Object); readerMock.Setup(x => x.GetUnackedMessages()).Returns(_insertedMessages); var speedReporter = new Mock <IReporter>(); _replayer = new MessageReplayer(_configurationMock.Object, _storageMock.Object, _bus, _transport, _messageMatcherMock.Object, _targetPeer, _replayId, speedReporter.Object, new MessageSerializer()); _messageMatcherMock.Setup(x => x.EnqueueWaitHandle(It.IsAny <EventWaitHandle>())).Callback <EventWaitHandle>(x => x.Set()); }
public Collaborators GetCollaborators() { var registry = new AssociationRegistry(); var transport = new TestTransport(localAddress, registry); var handle = new TestAssociationHandle(localAddress, remoteAddress, transport, true); transport.WriteBehavior.PushConstant(true); return new Collaborators(registry, transport, handle, new TestFailureDetector()); }
public void Setup() { _transport = new TestTransport(); _container = new Container(); _bus = new BusFactory(_container) .WithHandlers(typeof(EventPublisherEventHandler)) .CreateAndStartInMemoryBus(new TestPeerDirectory(), _transport); }
public Collaborators GetCollaborators() { var registry = new AssociationRegistry(); var transport = new TestTransport(localAddress, registry); var handle = new TestAssociationHandle(localAddress, remoteAddress, transport, true); transport.WriteBehavior.PushConstant(true); return(new Collaborators(registry, transport, handle, new TestFailureDetector())); }
public void SipTcpTransport_TransmitMultiple() { // Create two transport instances and send 10K messages from one to // the other and verify that they got through. TestTransport transport1 = new TestTransport(); TestTransport transport2 = new TestTransport(); SipRequest sentMsg; SipRequest recvMsg; try { transport1.Start(new NetworkBinding("127.0.0.1:5311")); transport2.Start(new NetworkBinding("127.0.0.1:5312")); for (int i = 0; i < 2500; i++) { sentMsg = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); sentMsg.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport1.LocalEndpoint)); sentMsg.AddHeader("Count", i.ToString()); sentMsg.Contents = GetContents(i); transport1.Send(transport2.LocalEndpoint, sentMsg); recvMsg = (SipRequest)transport2.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(sentMsg[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); Assert.AreEqual(i.ToString(), recvMsg["Count"].FullText); CollectionAssert.AreEqual(sentMsg.Contents, recvMsg.Contents); Assert.AreEqual(transport1.LocalEndpoint.Address, recvMsg.RemoteEndpoint.Address); // Send a message the other way. sentMsg = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); sentMsg.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport1.LocalEndpoint)); sentMsg.Contents = GetContents(i); transport2.Send(transport1.LocalEndpoint, sentMsg); recvMsg = (SipRequest)transport1.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(sentMsg[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); CollectionAssert.AreEqual(sentMsg.Contents, recvMsg.Contents); Assert.AreEqual(transport2.LocalEndpoint.Address, recvMsg.RemoteEndpoint.Address); } } finally { transport1.Stop(); transport2.Stop(); } }
public void Setup() { _transport = new TestTransport(); _container = new Container(); _peerDirectory = new TestPeerDirectory(); _bus = new BusFactory(_container) .WithHandlers(typeof(EventPublisherEventHandler), typeof(CommandHandleThatReplyAndThrow)) .CreateAndStartInMemoryBus(_peerDirectory, _transport); }
public void SipTcpTransport_TransmitSingle() { // Create two transport instances and send a message from one to // the other and verify that it got through. TestTransport transport1 = new TestTransport(); TestTransport transport2 = new TestTransport(); SipRequest sentMsg; SipRequest recvMsg; try { transport1.Start(new NetworkBinding("127.0.0.1:5311")); transport2.Start(new NetworkBinding("127.0.0.1:5312")); Assert.IsTrue(transport1.IsStreaming); Assert.AreEqual(SipTransportType.TCP, transport1.TransportType); sentMsg = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); sentMsg.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport1.LocalEndpoint)); transport1.Send(transport2.LocalEndpoint, sentMsg); recvMsg = (SipRequest)transport2.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(sentMsg[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); Assert.AreEqual(transport1.LocalEndpoint.Address, recvMsg.RemoteEndpoint.Address); // Send a message the other way, this one with some content data sentMsg = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); sentMsg.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport1.LocalEndpoint)); sentMsg.Contents = new byte[] { 0, 1, 2, 3, 4 }; transport2.Send(transport1.LocalEndpoint, sentMsg); recvMsg = (SipRequest)transport1.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(sentMsg[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4 }, recvMsg.Contents); Assert.AreEqual(transport2.LocalEndpoint.Address, recvMsg.RemoteEndpoint.Address); } finally { transport1.Stop(); transport2.Stop(); } }
public Task StartAsyncTransferFormatOverridesOptions() { var transport = new TestTransport(); return(WithConnectionAsync( CreateConnection(transport: transport, transferFormat: TransferFormat.Binary), async(connection) => { await connection.StartAsync(TransferFormat.Text).DefaultTimeout(); Assert.Equal(TransferFormat.Text, transport.Format); })); }
public void SipTcpTransport_MultipleChunks() { // Transmit a message to a transport in several chunks to make // sure it can be reassembled properly. TestTransport transport = new TestTransport(); EnhancedSocket sock = null; SipRequest msg; SipRequest recvMsg; byte[] buf; try { transport.Start(new NetworkBinding("127.0.0.1:5311")); sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect("127.0.0.1", 5311); sock.NoDelay = true; msg = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); msg.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint)); msg.AddHeader("Count", "0"); msg.Contents = GetContents(25); buf = msg.ToArray(); for (int i = 0; i < buf.Length; i++) { sock.Send(buf, i, 1, SocketFlags.None); Thread.Sleep(1); } recvMsg = (SipRequest)transport.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(msg[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); Assert.AreEqual("0", recvMsg["Count"].FullText); CollectionAssert.AreEqual(msg.Contents, recvMsg.Contents); } finally { if (sock != null) { sock.Close(); } transport.Stop(); } }
public virtual void Setup() { _configuration = new Mock <IBusConfiguration>(); _transport = new TestTransport(_self.EndPoint); _directoryMock = new Mock <IPeerDirectory>(); _messageDispatcherMock = new Mock <IMessageDispatcher>(); _messageSerializer = new TestMessageSerializer(); _bus = new Bus(_transport, _directoryMock.Object, _messageSerializer, _messageDispatcherMock.Object, new DefaultMessageSendingStrategy(), new DefaultStoppingStrategy(), Mock.Of <IBindingKeyPredicateBuilder>(), _configuration.Object); _bus.Configure(_self.Id, _environment); _invokers = new List <IMessageHandlerInvoker>(); _messageDispatcherMock.Setup(x => x.GetMessageHanlerInvokers()).Returns(_invokers); _directoryMock.Setup(x => x.GetPeersHandlingMessage(It.IsAny <IMessage>())).Returns(new Peer[0]); }
public Task TransportIsShutDownAfterDispose() { var transport = new TestTransport(); return(WithConnectionAsync( CreateConnection(transport: transport), async(connection) => { await connection.StartAsync().DefaultTimeout(); await connection.DisposeAsync().DefaultTimeout(); // This will throw OperationCanceledException if it's forcibly terminated // which we don't want await transport.Receiving.DefaultTimeout(); })); }
public void TestTransport_must_return_an_Address_and_TaskCompletionSource_on_Listen() { //arrange var registry = new AssociationRegistry(); var transportA = new TestTransport(addressA, registry); //act var result = transportA.Listen(); result.Wait(DefaultTimeout); //assert Assert.Equal(addressA, result.Result.Item1); Assert.NotNull(result.Result.Item2); var snapshot = registry.LogSnapshot(); Assert.Equal(1, snapshot.Count); Assert.IsType<ListenAttempt>(snapshot[0]); Assert.Equal(addressA, ((ListenAttempt)snapshot[0]).BoundAddress); }
public void TestTransport_fail_to_association_with_nonexisting_Address() { //arrange var registry = new AssociationRegistry(); var transportA = new TestTransport(addressA, registry); //act var result = transportA.Listen(); result.Wait(DefaultTimeout); result.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); //assert intercept<InvalidAssociationException>(() => { var associateTask = transportA.Associate(nonExistantAddress); associateTask.Wait(DefaultTimeout); var fireException = associateTask.Result; }); }
public void Setup() { _innerTransport = new TestTransport("tcp://abctest:888"); var peerDirectoryMock = new Mock <IPeerDirectory>(); _allPeers = new List <PeerDescriptor> { new PeerDescriptor(new PeerId("Abc.Testing.1"), "endpoint1", true, true, true, SystemDateTime.UtcNow), new PeerDescriptor(new PeerId("Abc.Testing.2"), "endpoint2", false, true, true, SystemDateTime.UtcNow), }; peerDirectoryMock.Setup(dir => dir.GetPeerDescriptors()) .Returns(_allPeers); _configurationMock.SetupGet(conf => conf.QueuingTransportStopTimeout).Returns(100.Milliseconds()); _transport = new QueueingTransport(_innerTransport, peerDirectoryMock.Object, _configurationMock.Object); _targetPeer = new Peer(new PeerId("Abc.Testing.Target"), "tcp://abctest:999"); }
public void TestTransport_fail_to_association_with_nonexisting_Address() { //arrange var registry = new AssociationRegistry(); var transportA = new TestTransport(addressA, registry); //act var result = transportA.Listen(); result.Wait(DefaultTimeout); result.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); //assert XAssert.Throws <InvalidAssociationException>(() => { var associateTask = transportA.Associate(nonExistantAddress); associateTask.Wait(DefaultTimeout); var fireException = associateTask.Result; }); }
public void should_send_message_to_peer() { var directory = new TestPeerDirectory(); var transport = new TestTransport(); var bus = new BusFactory().CreateAndStartInMemoryBus(directory, transport); var otherPeer = new Peer(new PeerId("Abc.Testing.Other.0"), "tcp://other-peer:1234"); directory.Peers[otherPeer.Id] = otherPeer.ToPeerDescriptor(false, typeof(CommandWithRemoteHandler)); bus.Send(new CommandWithRemoteHandler()); var sentMessage = transport.Messages.ExpectedSingle(); sentMessage.TransportMessage.MessageTypeId.GetMessageType().ShouldEqual(typeof(CommandWithRemoteHandler)); var target = sentMessage.Targets.ExpectedSingle(); target.Id.ShouldEqual(otherPeer.Id); }
public void Setup() { _transport = new TestTransport(_self.EndPoint); _directoryMock = new Mock <IPeerDirectory>(); _messageDispatcherMock = new Mock <IMessageDispatcher>(); _messageSerializer = new TestMessageSerializer(); _bus = new Bus(_transport, _directoryMock.Object, _messageSerializer, _messageDispatcherMock.Object, new DefaultStoppingStrategy()); _bus.Configure(_self.Id, "test"); _invokers = new List <IMessageHandlerInvoker>(); _messageDispatcherMock.Setup(x => x.GetMessageHanlerInvokers()).Returns(_invokers); _expectedDumpDirectory = PathUtil.InBaseDirectory(_deserializationFailureDumpsDirectoryName); if (System.IO.Directory.Exists(_expectedDumpDirectory)) { System.IO.Directory.Delete(_expectedDumpDirectory, true); } _directoryMock.Setup(x => x.GetPeersHandlingMessage(It.IsAny <IMessage>())).Returns(new Peer[0]); }
public void TestTransport_must_return_an_Address_and_TaskCompletionSource_on_Listen() { //arrange var registry = new AssociationRegistry(); var transportA = new TestTransport(addressA, registry); //act var result = transportA.Listen(); result.Wait(DefaultTimeout); //assert Assert.Equal(addressA, result.Result.Item1); Assert.NotNull(result.Result.Item2); var snapshot = registry.LogSnapshot(); Assert.Equal(1, snapshot.Count); Assert.IsType <ListenAttempt>(snapshot[0]); Assert.Equal(addressA, ((ListenAttempt)snapshot[0]).BoundAddress); }
public async Task TransportIsStoppedWhenConnectionIsDisposed() { var testHttpHandler = new TestHttpMessageHandler(); using (var httpClient = new HttpClient(testHttpHandler)) { var testTransport = new TestTransport(); await WithConnectionAsync( CreateConnection(transport : testTransport), async (connection) => { // Start the transport await connection.StartAsync().DefaultTimeout(); Assert.NotNull(testTransport.Receiving); Assert.False(testTransport.Receiving.IsCompleted); // Stop the connection, and we should stop the transport await connection.DisposeAsync().DefaultTimeout(); await testTransport.Receiving.DefaultTimeout(); }); } }
public void SipUdpTransport_TransmitSingle() { // Create two transport instances and send a message from one to // the other and verify that it got through. TestTransport transport1 = new TestTransport(); TestTransport transport2 = new TestTransport(); SipRequest sentMsg; SipRequest recvMsg; try { transport1.Start(new NetworkBinding("127.0.0.1:ANY")); transport2.Start(new NetworkBinding("127.0.0.1:ANY")); Assert.IsFalse(transport1.IsStreaming); Assert.AreEqual(SipTransportType.UDP, transport1.TransportType); sentMsg = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); sentMsg.AddHeader(SipHeader.Via, string.Format("SIP/2.0/UDP {0}", transport1.LocalEndpoint)); transport1.Send(transport2.LocalEndpoint, sentMsg); recvMsg = (SipRequest)transport2.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(sentMsg[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); Assert.AreEqual(transport1.LocalEndpoint.Address, recvMsg.RemoteEndpoint.Address); Assert.AreEqual(transport1.LocalEndpoint.Port, recvMsg.RemoteEndpoint.Port); } finally { transport1.Stop(); transport2.Stop(); } }
public void SipUdpTransport_External() { // Open a UDP transport on the standard SIP port, // receive three messages, write their contents to // the debug output and then terminate. Assert.Inconclusive("Comment this out to enable the test"); IPAddress address, subnet; TestTransport transport; SipMessage message; Helper.GetNetworkInfo(out address, out subnet); transport = new TestTransport(); transport.Start(new NetworkBinding(address, NetworkPort.SIP)); transport.Timeout = -1; try { for (int i = 0; i < 5; i++) { message = transport.Receive(); Debug.Write(message.ToString()); if (message.Contents.Length > 0) { Debug.Write(Helper.HexDump(message.Contents, 16, HexDumpOption.ShowAll)); } } } finally { transport.Stop(); } }
public void Properly_quarantine_stashed_inbound_connections() { var localAddress = new Address("akka.test", "system1", "localhost", 1); var rawLocalAddress = new Address("test", "system1", "localhost", 1); var remoteAddress = new Address("akka.test", "system2", "localhost", 2); var rawRemoteAddress = new Address("test", "system2", "localhost", 2); var remoteUID = 16; var config = ConfigurationFactory.ParseString(@" akka.remote.enabled-transports = [""akka.remote.test""] akka.remote.retry-gate-closed-for = 5s akka.remote.log-remote-lifecycle-events = on akka.remote.test { registry-key = JMeMndLLsw local-address = """ + $"test://{localAddress.System}@{localAddress.Host}:{localAddress.Port}" + @""" }").WithFallback(_remoteSystem.Settings.Config); var thisSystem = ActorSystem.Create("this-system", config); MuteSystem(thisSystem); try { // Set up a mock remote system using the test transport var registry = AssociationRegistry.Get("JMeMndLLsw"); var remoteTransport = new TestTransport(rawRemoteAddress, registry); var remoteTransportProbe = CreateTestProbe(); registry.RegisterTransport(remoteTransport, Task.FromResult <IAssociationEventListener> (new ActorAssociationEventListener(remoteTransportProbe))); // Hijack associations through the test transport AwaitCondition(() => registry.TransportsReady(rawLocalAddress, rawRemoteAddress)); var testTransport = registry.TransportFor(rawLocalAddress).Item1; testTransport.WriteBehavior.PushConstant(true); // Force an outbound associate on the real system (which we will hijack) // we send no handshake packet, so this remains a pending connection var dummySelection = thisSystem.ActorSelection(ActorPath.Parse(remoteAddress + "/user/noonethere")); dummySelection.Tell("ping", Sys.DeadLetters); var remoteHandle = remoteTransportProbe.ExpectMsg <InboundAssociation>(TimeSpan.FromMinutes(4)); remoteHandle.Association.ReadHandlerSource.TrySetResult((IHandleEventListener)(new ActionHandleEventListener(ev => {}))); // Now we initiate an emulated inbound connection to the real system var inboundHandleProbe = CreateTestProbe(); var inboundHandleTask = remoteTransport.Associate(rawLocalAddress); inboundHandleTask.Wait(TimeSpan.FromSeconds(3)); var inboundHandle = inboundHandleTask.Result; inboundHandle.ReadHandlerSource.SetResult(new ActorHandleEventListener(inboundHandleProbe)); AwaitAssert(() => { registry.GetRemoteReadHandlerFor(inboundHandle.AsInstanceOf <TestAssociationHandle>()).Should().NotBeNull(); }); var pduCodec = new AkkaPduProtobuffCodec(Sys); var handshakePacket = pduCodec.ConstructAssociate(new HandshakeInfo(rawRemoteAddress, remoteUID)); // Finish the inbound handshake so now it is handed up to Remoting inboundHandle.Write(handshakePacket); // No disassociation now, the connection is still stashed inboundHandleProbe.ExpectNoMsg(1000); // Quarantine unrelated connection RARP.For(thisSystem).Provider.Quarantine(remoteAddress, -1); inboundHandleProbe.ExpectNoMsg(1000); // Quarantine the connection RARP.For(thisSystem).Provider.Quarantine(remoteAddress, remoteUID); // Even though the connection is stashed it will be disassociated inboundHandleProbe.ExpectMsg <Disassociated>(); } finally { Shutdown(thisSystem); } }
/// <summary> /// TBD /// </summary> /// <param name="localAddress">TBD</param> /// <param name="remoteAddress">TBD</param> /// <param name="transport">TBD</param> /// <param name="inbound">TBD</param> public TestAssociationHandle(Address localAddress, Address remoteAddress, TestTransport transport, bool inbound) : base(localAddress, remoteAddress) { Inbound = inbound; _transport = transport; }
public void TestTransport_should_emulate_sending_PDUs() { //arrange var registry = new AssociationRegistry(); var transportA = new TestTransport(addressA, registry); var transportB = new TestTransport(addressB, registry); //act //must complete returned promises to receive events var localConnectionFuture = transportA.Listen(); localConnectionFuture.Wait(DefaultTimeout); localConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var remoteConnectionFuture = transportB.Listen(); remoteConnectionFuture.Wait(DefaultTimeout); remoteConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var ready = registry.TransportsReady(addressA, addressB); Assert.True(ready); var associate = transportA.Associate(addressB); var handleB = expectMsgPF<AssociationHandle>(DefaultTimeout, "Expect InboundAssociation from A", o => { var handle = o as InboundAssociation; if (handle != null && handle.Association.RemoteAddress.Equals(addressA)) return handle.Association; return null; }); handleB.ReadHandlerSource.SetResult(new ActorHandleEventListener(Self)); associate.Wait(DefaultTimeout); var handleA = associate.Result; //Initialize handles handleA.ReadHandlerSource.SetResult(new ActorHandleEventListener(Self)); var akkaPDU = ByteString.CopyFromUtf8("AkkaPDU"); var exists = registry.ExistsAssociation(addressA, addressB); Assert.True(exists); handleA.Write(akkaPDU); //assert expectMsgPF(DefaultTimeout, "Expect InboundPayload from A", o => { var payload = o as InboundPayload; if (payload != null && payload.Payload.Equals(akkaPDU)) return akkaPDU; return null; }); var writeAttempt = (registry.LogSnapshot().Single(x => x is WriteAttempt)).AsInstanceOf<WriteAttempt>(); Assert.True(writeAttempt.Sender.Equals(addressA) && writeAttempt.Recipient.Equals(addressB) && writeAttempt.Payload.Equals(akkaPDU)); }
public void Stash_inbound_connections_until_UID_is_known_for_pending_outbound() { var localAddress = new Address("akka.test", "system1", "localhost", 1); var rawLocalAddress = new Address("test", "system1", "localhost", 1); var remoteAddress = new Address("akka.test", "system2", "localhost", 2); var rawRemoteAddress = new Address("test", "system2", "localhost", 2); var config = ConfigurationFactory.ParseString(@" akka.remote.enabled-transports = [""akka.remote.test""] akka.remote.retry-gate-closed-for = 5s akka.remote.log-remote-lifecycle-events = on akka.loglevel = DEBUG akka.remote.test { registry-key = TRKAzR local-address = """ + $"test://{localAddress.System}@{localAddress.Host}:{localAddress.Port}" + @""" }").WithFallback(_remoteSystem.Settings.Config); var thisSystem = ActorSystem.Create("this-system", config); MuteSystem(thisSystem); try { // Set up a mock remote system using the test transport var registry = AssociationRegistry.Get("TRKAzR"); var remoteTransport = new TestTransport(rawRemoteAddress, registry); var remoteTransportProbe = CreateTestProbe(); registry.RegisterTransport(remoteTransport, Task.FromResult <IAssociationEventListener> (new ActorAssociationEventListener(remoteTransportProbe))); // Hijack associations through the test transport AwaitCondition(() => registry.TransportsReady(rawLocalAddress, rawRemoteAddress)); var testTransport = registry.TransportFor(rawLocalAddress).Item1; testTransport.WriteBehavior.PushConstant(true); // Force an outbound associate on the real system (which we will hijack) // we send no handshake packet, so this remains a pending connection var dummySelection = thisSystem.ActorSelection(ActorPath.Parse(remoteAddress + "/user/noonethere")); dummySelection.Tell("ping", Sys.DeadLetters); var remoteHandle = remoteTransportProbe.ExpectMsg <InboundAssociation>(TimeSpan.FromMinutes(4)); remoteHandle.Association.ReadHandlerSource.TrySetResult((IHandleEventListener)(new ActionHandleEventListener(ev => { }))); // Now we initiate an emulated inbound connection to the real system var inboundHandleProbe = CreateTestProbe(); var inboundHandleTask = remoteTransport.Associate(rawLocalAddress); inboundHandleTask.Wait(TimeSpan.FromSeconds(3)); var inboundHandle = inboundHandleTask.Result; inboundHandle.ReadHandlerSource.SetResult(new ActorHandleEventListener(inboundHandleProbe)); AwaitAssert(() => { registry.GetRemoteReadHandlerFor(inboundHandle.AsInstanceOf <TestAssociationHandle>()).Should().NotBeNull(); }); var pduCodec = new AkkaPduProtobuffCodec(Sys); var handshakePacket = pduCodec.ConstructAssociate(new HandshakeInfo(rawRemoteAddress, 0)); var brokenPacket = pduCodec.ConstructPayload(ByteString.CopyFrom(0, 1, 2, 3, 4, 5, 6)); // Finish the inbound handshake so now it is handed up to Remoting inboundHandle.Write(handshakePacket); // Now bork the connection with a malformed packet that can only signal an error if the Endpoint is already registered // but not while it is stashed inboundHandle.Write(brokenPacket); // No disassociation now - the connection is still stashed inboundHandleProbe.ExpectNoMsg(1000); // Finish the handshake for the outbound connection - this will unstash the inbound pending connection. remoteHandle.Association.Write(handshakePacket); inboundHandleProbe.ExpectMsg <Disassociated>(TimeSpan.FromMinutes(5)); } finally { Shutdown(thisSystem); } }
public void SipTcpTransport_MultipleBuffered() { // Render two messages into a single buffer and transmit them // to a TCP transport in a single send. This will result in // the two messages being processed out of the headerBuf which // is what we want to test here. TestTransport transport = new TestTransport(); EnhancedSocket sock = null; SipRequest msg1, msg2; SipRequest recvMsg; byte[] buf; int cb; try { transport.Start(new NetworkBinding("127.0.0.1:5311")); sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect("127.0.0.1", 5311); msg1 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); msg1.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint)); msg1.AddHeader("Count", "0"); msg1.Contents = GetContents(0); msg2 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); msg2.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint)); msg2.AddHeader("Count", "1"); msg2.Contents = GetContents(0); buf = Helper.Concat(msg1.ToArray(), msg2.ToArray()); cb = sock.Send(buf); Assert.AreEqual(buf.Length, cb); recvMsg = (SipRequest)transport.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(msg1[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); Assert.AreEqual("0", recvMsg["Count"].FullText); CollectionAssert.AreEqual(msg1.Contents, recvMsg.Contents); recvMsg = (SipRequest)transport.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(msg2[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); Assert.AreEqual("1", recvMsg["Count"].FullText); CollectionAssert.AreEqual(msg2.Contents, recvMsg.Contents); // Try it again, this time with some data. msg1 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); msg1.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint)); msg1.AddHeader("Count", "0"); msg1.Contents = GetContents(10); msg2 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); msg2.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint)); msg2.AddHeader("Count", "1"); msg2.Contents = GetContents(20); buf = Helper.Concat(msg1.ToArray(), msg2.ToArray()); cb = sock.Send(buf); Assert.AreEqual(buf.Length, cb); recvMsg = (SipRequest)transport.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(msg1[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); Assert.AreEqual("0", recvMsg["Count"].FullText); CollectionAssert.AreEqual(msg1.Contents, recvMsg.Contents); recvMsg = (SipRequest)transport.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(msg2[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); Assert.AreEqual("1", recvMsg["Count"].FullText); CollectionAssert.AreEqual(msg2.Contents, recvMsg.Contents); // Try it one more time, this time adding a leading CRLF msg1 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); msg1.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint)); msg1.AddHeader("Count", "0"); msg1.Contents = GetContents(10); msg2 = new SipRequest(SipMethod.Register, "sip:[email protected]", SipHelper.SIP20); msg2.AddHeader(SipHeader.Via, string.Format("SIP/2.0/TCP {0}", transport.LocalEndpoint)); msg2.AddHeader("Count", "1"); msg2.Contents = GetContents(20); buf = Helper.Concat(new byte[] { 0x0D, 0x0A }, msg1.ToArray(), new byte[] { 0x0D, 0x0A }, msg2.ToArray()); cb = sock.Send(buf); Assert.AreEqual(buf.Length, cb); recvMsg = (SipRequest)transport.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(msg1[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); Assert.AreEqual("0", recvMsg["Count"].FullText); CollectionAssert.AreEqual(msg1.Contents, recvMsg.Contents); recvMsg = (SipRequest)transport.Receive(); Assert.AreEqual(SipMethod.Register, recvMsg.Method); Assert.AreEqual("sip:[email protected]", recvMsg.Uri); Assert.AreEqual(SipHelper.SIP20, recvMsg.SipVersion); Assert.AreEqual(msg2[SipHeader.Via].FullText, recvMsg[SipHeader.Via].FullText); Assert.AreEqual("1", recvMsg["Count"].FullText); CollectionAssert.AreEqual(msg2.Contents, recvMsg.Contents); } finally { if (sock != null) { sock.Close(); } transport.Stop(); } }
public void TestTransport_should_emulate_disassociation() { //arrange var registry = new AssociationRegistry(); var transportA = new TestTransport(addressA, registry); var transportB = new TestTransport(addressB, registry); //act //must complete returned promises to receive events var localConnectionFuture = transportA.Listen(); localConnectionFuture.Wait(DefaultTimeout); localConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var remoteConnectionFuture = transportB.Listen(); remoteConnectionFuture.Wait(DefaultTimeout); remoteConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var ready = registry.TransportsReady(addressA, addressB); Assert.True(ready); var associate = transportA.Associate(addressB); var handleB = expectMsgPF<AssociationHandle>(DefaultTimeout, "Expect InboundAssociation from A", o => { var handle = o as InboundAssociation; if (handle != null && handle.Association.RemoteAddress.Equals(addressA)) return handle.Association; return null; }); handleB.ReadHandlerSource.SetResult(new ActorHandleEventListener(Self)); associate.Wait(DefaultTimeout); var handleA = associate.Result; //Initialize handles handleA.ReadHandlerSource.SetResult(new ActorHandleEventListener(Self)); var exists = registry.ExistsAssociation(addressA, addressB); Assert.True(exists); handleA.Disassociate(); var msg = expectMsgPF(DefaultTimeout, "Expected Disassociated", o => o.AsInstanceOf<Disassociated>()); //assert Assert.NotNull(msg); exists = registry.ExistsAssociation(addressA, addressB); Assert.True(!exists, "Association should no longer exist"); var disassociateAttempt = registry.LogSnapshot().Single(x => x is DisassociateAttempt).AsInstanceOf<DisassociateAttempt>(); Assert.True(disassociateAttempt.Requestor.Equals(addressA) && disassociateAttempt.Remote.Equals(addressB)); }
public void TestTransport_should_emulate_sending_PDUs() { //arrange var registry = new AssociationRegistry(); var transportA = new TestTransport(addressA, registry); var transportB = new TestTransport(addressB, registry); //act //must complete returned promises to receive events var localConnectionFuture = transportA.Listen(); localConnectionFuture.Wait(DefaultTimeout); localConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var remoteConnectionFuture = transportB.Listen(); remoteConnectionFuture.Wait(DefaultTimeout); remoteConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var ready = registry.TransportsReady(addressA, addressB); Assert.True(ready); var associate = transportA.Associate(addressB); var handleB = ExpectMsgPf <AssociationHandle>(DefaultTimeout, "Expect InboundAssociation from A", o => { var handle = o as InboundAssociation; if (handle != null && handle.Association.RemoteAddress.Equals(addressA)) { return(handle.Association); } return(null); }); handleB.ReadHandlerSource.SetResult(new ActorHandleEventListener(Self)); associate.Wait(DefaultTimeout); var handleA = associate.Result; //Initialize handles handleA.ReadHandlerSource.SetResult(new ActorHandleEventListener(Self)); var akkaPDU = ByteString.CopyFromUtf8("AkkaPDU"); var exists = registry.ExistsAssociation(addressA, addressB); Assert.True(exists); handleA.Write(akkaPDU); //assert ExpectMsgPf(DefaultTimeout, "Expect InboundPayload from A", o => { var payload = o as InboundPayload; if (payload != null && payload.Payload.Equals(akkaPDU)) { return(akkaPDU); } return(null); }); var writeAttempt = (registry.LogSnapshot().Single(x => x is WriteAttempt)).AsInstanceOf <WriteAttempt>(); Assert.True(writeAttempt.Sender.Equals(addressA) && writeAttempt.Recipient.Equals(addressB) && writeAttempt.Payload.Equals(akkaPDU)); }
protected abstract Akka.Remote.Transport.Transport FreshTransport(TestTransport testTransport);
public void TestTransport_should_emulate_disassociation() { //arrange var registry = new AssociationRegistry(); var transportA = new TestTransport(addressA, registry); var transportB = new TestTransport(addressB, registry); //act //must complete returned promises to receive events var localConnectionFuture = transportA.Listen(); localConnectionFuture.Wait(DefaultTimeout); localConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var remoteConnectionFuture = transportB.Listen(); remoteConnectionFuture.Wait(DefaultTimeout); remoteConnectionFuture.Result.Item2.SetResult(new ActorAssociationEventListener(Self)); var ready = registry.TransportsReady(addressA, addressB); Assert.True(ready); var associate = transportA.Associate(addressB); var handleB = ExpectMsgPf <AssociationHandle>(DefaultTimeout, "Expect InboundAssociation from A", o => { var handle = o as InboundAssociation; if (handle != null && handle.Association.RemoteAddress.Equals(addressA)) { return(handle.Association); } return(null); }); handleB.ReadHandlerSource.SetResult(new ActorHandleEventListener(Self)); associate.Wait(DefaultTimeout); var handleA = associate.Result; //Initialize handles handleA.ReadHandlerSource.SetResult(new ActorHandleEventListener(Self)); var exists = registry.ExistsAssociation(addressA, addressB); Assert.True(exists); handleA.Disassociate(); var msg = ExpectMsgPf(DefaultTimeout, "Expected Disassociated", o => o.AsInstanceOf <Disassociated>()); //assert Assert.NotNull(msg); exists = registry.ExistsAssociation(addressA, addressB); Assert.True(!exists, "Association should no longer exist"); var disassociateAttempt = registry.LogSnapshot().Single(x => x is DisassociateAttempt).AsInstanceOf <DisassociateAttempt>(); Assert.True(disassociateAttempt.Requestor.Equals(addressA) && disassociateAttempt.Remote.Equals(addressB)); }