Esempio n. 1
0
        public void CanAddReturnsTrue_IfActorIsNotYetAdded()
        {
            var actorHandlersMap = new ActorHandlerMap();
            var actor            = new EchoActor();

            Assert.True(actorHandlersMap.CanAdd(actor));
        }
Esempio n. 2
0
        public void Can_use_unbounded_priority_mailbox()
        {
            var actor = (IInternalActorRef)Sys.ActorOf(EchoActor.Props(this).WithMailbox("string-prio-mailbox"), "echo");

            //pause mailbox until all messages have been told
            actor.SendSystemMessage(new Suspend());

            actor.Tell(true);
            for (var i = 0; i < 30; i++)
            {
                actor.Tell(1);
            }
            actor.Tell("a");
            actor.Tell(2.0);
            for (var i = 0; i < 30; i++)
            {
                actor.Tell(1);
            }
            actor.SendSystemMessage(new Resume(null));

            //resume mailbox, this prevents the mailbox from running to early
            //priority mailbox is best effort only

            ExpectMsg("a");
            ExpectMsg(true);
            for (var i = 0; i < 60; i++)
            {
                ExpectMsg(1);
            }
            ExpectMsg(2.0);

            ExpectNoMsg(TimeSpan.FromSeconds(0.3));
        }
        public void CurrentSynchronizationContextDispatcher_should_start_without_error_Fix2172()
        {
            var uiActor = Sys.ActorOf(EchoActor.Props(this), "some-ui-actor");

            uiActor.Tell("ping");
            ExpectMsg("ping");
        }
Esempio n. 4
0
        public void ProxyShardingSpec_Shard_region_should_be_found()
        {
            var shardRegion = clusterSharding.Start("myType", EchoActor.Props(this), shardingSettings, messageExtractor);

            shardRegion.Path.Should().NotBeNull();
            shardRegion.Path.ToString().Should().EndWith("myType");
        }
        public void Many_persistent_actors_must_be_able_to_recover_without_overloading()
        {
            Enumerable.Range(1, 100).ForEach(n =>
            {
                Sys.ActorOf(TestPersistentActor.Props($"a{n}", null)).Tell(new Cmd("A"));
                ExpectMsg($"a{n}-A-1");
            });

            // This would starve (block) all threads without max-concurrent-recoveries
            var latch = new TestLatch();

            Enumerable.Range(1, 100).ForEach(n =>
            {
                Sys.ActorOf(TestPersistentActor.Props($"a{n}", latch)).Tell(new Cmd("B"));
            });

            // This should be able to progress even though above is blocking, 2 remaining non-blocked threads
            Enumerable.Range(1, 10).ForEach(n =>
            {
                Sys.ActorOf(EchoActor.Props(this)).Tell(n);
                ExpectMsg(n);
            });

            latch.CountDown();
            ReceiveN(100).ShouldAllBeEquivalentTo(Enumerable.Range(1, 100).Select(n => $"a{n}-B-2"));
        }
Esempio n. 6
0
        public void AddingActorsHandlingTheSameMessageTwice_ThowsDuplicatedKeyException()
        {
            var actorHandlersMap = new ActorHandlerMap();
            var actor            = new EchoActor();

            actorHandlersMap.Add(actor);
            Assert.Throws <DuplicatedKeyException>(() => { actorHandlersMap.Add(actor); });
        }
Esempio n. 7
0
        public async void CouldReceiveEcho()
        {
            var actor = new EchoActor();

            actor.Start();
            var result = await actor.PostAndGetResult("Ractor");

            Assert.AreEqual("Ractor", result);
        }
Esempio n. 8
0
        public void GettingHandlerForNonRegisteredMessageIdentifier_ThrowsKeyNotFoundException()
        {
            var actorHandlersMap = new ActorHandlerMap();
            var actor            = new EchoActor();

            actorHandlersMap.Add(actor);

            Assert.Throws <KeyNotFoundException>(() => actorHandlersMap.Get(new MessageIdentifier(KinoMessages.Exception)));
        }
Esempio n. 9
0
        public void CanAddReturnsFalse_IfActorAlreadyAdded()
        {
            var actorHandlersMap = new ActorHandlerMap();
            var actor            = new EchoActor();

            actorHandlersMap.Add(actor);

            Assert.False(actorHandlersMap.CanAdd(actor));
        }
Esempio n. 10
0
        public void ProxyShardingSpec_Shard_coordinator_should_be_found()
        {
            var shardRegion = clusterSharding.Start("myType", EchoActor.Props(this), shardingSettings, messageExtractor);

            IActorRef shardCoordinator = Sys.ActorSelection("akka://test/system/sharding/myTypeCoordinator")
                                         .ResolveOne(TimeSpan.FromSeconds(5)).Result;

            shardCoordinator.Path.Should().NotBeNull();
            shardCoordinator.Path.ToString().Should().EndWith("Coordinator");
        }
        public void GetShardTypeNames_must_contain_started_shards_when_started_2_shards()
        {
            Cluster.Get(Sys).Join(Cluster.Get(Sys).SelfAddress);
            var settings = ClusterShardingSettings.Create(Sys);

            ClusterSharding.Get(Sys).Start("type1", EchoActor.Props(this), settings, ExtractEntityId, ExtractShardId);
            ClusterSharding.Get(Sys).Start("type2", EchoActor.Props(this), settings, ExtractEntityId, ExtractShardId);

            ClusterSharding.Get(Sys).ShardTypeNames.ShouldBeEquivalentTo(new string[] { "type1", "type2" });
        }
Esempio n. 12
0
        public async Task Should_Ask_Clustered_Pool_Router_and_forward_ask_to_routee()
        {
            var router = Sys.ActorOf(EchoActor.Props(this, true).WithRouter(FromConfig.Instance), "router1");

            Assert.IsType <RoutedActorRef>(router);

            var result = await router.Ask <string>("foo");

            ExpectMsg <string>().ShouldBe(result);
        }
Esempio n. 13
0
 public void EchoActorTest()
 {
     TestLauncherActor.Test(() =>
     {
         var actor = new EchoTest();
         EchoActor.Echo(actor, "Test Echo");
         IFuture <string> future = new Future <string>();
         actor.SendMessage(future);
         Assert.AreEqual("Test Echo", future.ResultAsync().Result);
     });
 }
 private void ClusterClient_must_bring_second_node_into_cluster()
 {
     Join(_config.Second, _config.First);
     RunOn(() =>
     {
         var service = Sys.ActorOf(EchoActor.Props(this), "testService");
         ClusterClientReceptionist.Get(Sys).RegisterService(service);
         AwaitMembersUp(2);
     }, _config.Second);
     EnterBarrier("second-up");
 }
Esempio n. 15
0
        public void Bootstrap(RouteCollection routeCollection)
        {
            TraceLogProvider.Configure(LogLevel.Debug);

            ModelBinder modelBinder = new FastModelBinder();

            RouteBuilder routeBuilder = new ActorRouteBuilder("actors/", modelBinder, routeCollection.Add);

            var actor = new EchoActor(new ThreadPoolActionQueue());

            routeBuilder.BuildRoute(() => actor, x => x.EchoChannel);
        }
Esempio n. 16
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            var hoconConfig = HoconConfig();

            Console.WriteLine(hoconConfig);

            var config = ConfigurationFactory.ParseString(hoconConfig);

            _system = ActorSystem.Create("EchoConsoleApp", config);
            _system.ActorOf(EchoActor.Props(), "EchoActor");

            return(Task.CompletedTask);
        }
Esempio n. 17
0
        public void IfActorHostCanHostAllActorsBeingAssigned_ThisActorHostInstanceIsUsed()
        {
            var echoActor = new EchoActor();
            var nullActor = new NullActor();

            actorHost.Setup(m => m.CanAssignActor(nullActor)).Returns(true);
            actorHost.Setup(m => m.CanAssignActor(echoActor)).Returns(true);
            //
            actorHostManager.AssignActor(echoActor);
            actorHostManager.AssignActor(nullActor);
            //
            actorHostFactory.Verify(m => m.Create(), Times.Once);
        }
 private void ClusterClient_must_startup_cluster_with_single_node()
 {
     Within(TimeSpan.FromSeconds(30), () =>
     {
         Join(_config.First, _config.First);
         RunOn(() =>
         {
             var service = Sys.ActorOf(EchoActor.Props(this), "testService");
             ClusterClientReceptionist.Get(Sys).RegisterService(service);
             AwaitMembersUp(1);
         }, _config.First);
         EnterBarrier("cluster-started");
     });
 }
Esempio n. 19
0
        public void The_transport_must_stay_alive_after_a_transient_exception_from_the_serializer()
        {
            system2.ActorOf(EchoActor.Props(), "echo");

            var selection = Sys.ActorSelection(new RootActorPath(system2Address) / "user" / "echo");

            selection.Tell("ping", this.TestActor);
            ExpectMsg("ping");

            // none of these should tear down the connection
            selection.Tell(ManifestIllegal.Instance, this.TestActor);
            selection.Tell(ManifestNotSerializable.Instance, this.TestActor);
            selection.Tell(ToBinaryIllegal.Instance, this.TestActor);
            selection.Tell(ToBinaryNotSerializable.Instance, this.TestActor);
            selection.Tell(NotDeserializable.Instance, this.TestActor);
            selection.Tell(IllegalOnDeserialize.Instance, this.TestActor);

            // make sure we still have a connection
            selection.Tell("ping", this.TestActor);
            ExpectMsg("ping");
        }
Esempio n. 20
0
        public void Priority_mailbox_keeps_ordering_with_many_priority_values()
        {
            var actor = (IInternalActorRef)Sys.ActorOf(EchoActor.Props(this).WithMailbox("int-prio-mailbox"), "echo");

            //pause mailbox until all messages have been told
            actor.SendSystemMessage(new Suspend());

            AwaitCondition(() => (((ActorRefWithCell)actor).Underlying is ActorCell) && ((ActorRefWithCell)actor).Underlying.AsInstanceOf <ActorCell>().Mailbox.IsSuspended());
            // creates 50 messages with values spanning from Int32.MinValue to Int32.MaxValue
            var values    = new int[50];
            var increment = (int)(UInt32.MaxValue / values.Length);

            for (var i = 0; i < values.Length; i++)
            {
                values[i] = Int32.MinValue + increment * i;
            }

            // tell the actor in reverse order
            foreach (var value in values.Reverse())
            {
                actor.Tell(value);
                actor.Tell(value);
                actor.Tell(value);
            }

            //resume mailbox, this prevents the mailbox from running to early
            actor.SendSystemMessage(new Resume(null));

            // expect the messages in the correct order
            foreach (var value in values)
            {
                ExpectMsg(value);
                ExpectMsg(value);
                ExpectMsg(value);
            }

            ExpectNoMsg(TimeSpan.FromSeconds(0.3));
        }
Esempio n. 21
0
        public void PriorityMailboxKeepsOrderingWithManyPriorityValues()
        {
            var actor = Sys.ActorOf(EchoActor.Props(this).WithMailbox("int-prio-mailbox"), "echo");

            //pause mailbox until all messages have been told
            actor.Tell(Suspend.Instance);

            AwaitCondition(() => ((LocalActorRef)actor).Cell.Mailbox.IsSuspended);
            // creates 50 messages with values spanning from Int32.MinValue to Int32.MaxValue
            var values    = new int[50];
            var increment = (int)(UInt32.MaxValue / values.Length);

            for (var i = 0; i < values.Length; i++)
            {
                values[i] = Int32.MinValue + increment * i;
            }

            // tell the actor in reverse order
            foreach (var value in values.Reverse())
            {
                actor.Tell(value);
                actor.Tell(value);
                actor.Tell(value);
            }

            //resume mailbox, this prevents the mailbox from running to early
            actor.Tell(new Resume(null));

            // expect the messages in the correct order
            foreach (var value in values)
            {
                ExpectMsg(value);
                ExpectMsg(value);
                ExpectMsg(value);
            }

            ExpectNoMsg(TimeSpan.FromSeconds(0.3));
        }
Esempio n. 22
0
        public void Can_use_unbounded_priority_mailbox()
        {
            var actor = (IInternalActorRef)Sys.ActorOf(EchoActor.Props(this).WithMailbox("string-prio-mailbox"), "echo");

            //pause mailbox until all messages have been told
            actor.SendSystemMessage(new Suspend());

            // wait until we can confirm that the mailbox is suspended before we begin sending messages
            AwaitCondition(() => (((ActorRefWithCell)actor).Underlying is ActorCell) && ((ActorRefWithCell)actor).Underlying.AsInstanceOf <ActorCell>().Mailbox.IsSuspended());

            actor.Tell(true);
            for (var i = 0; i < 30; i++)
            {
                actor.Tell(1);
            }
            actor.Tell("a");
            actor.Tell(2.0);
            for (var i = 0; i < 30; i++)
            {
                actor.Tell(1);
            }
            actor.SendSystemMessage(new Resume(null));

            //resume mailbox, this prevents the mailbox from running to early
            //priority mailbox is best effort only

            ExpectMsg("a");
            ExpectMsg(true);
            for (var i = 0; i < 60; i++)
            {
                ExpectMsg(1);
            }
            ExpectMsg(2.0);

            ExpectNoMsg(TimeSpan.FromSeconds(0.3));
        }
        // ReSharper restore NotAccessedField.Local

        public ActorSelectionSpec()
            : base("akka.test.default-timeout = 5 s")
        {
            _echoActor          = Sys.ActorOf(EchoActor.Props(this), "echo");
            _selectionTestActor = CreateTestActor("test");
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            string lName = "";
            string lPort = "";

            if (args.Length > 0)
            {
                lName = Array.Find(args, t => t.StartsWith("-n:", StringComparison.InvariantCulture));
                lPort = Array.Find(args, t => t.StartsWith("-p:", StringComparison.InvariantCulture));
            }
            if (!string.IsNullOrEmpty(lName))
            {
                lName = lName.Replace("-n:", "");
            }
            else
            {
                lName = "ARnActorServer";
            }

            if (!String.IsNullOrEmpty(lPort))
            {
                lPort = lPort.Replace("-p:", "");
            }
            else
            {
                lPort = "80";
            }

            // ActorServer.Start(lName, int.Parse(lPort), new HostRelayActor());
            ActorServer.Start(new ActorConfigManager());
            IActor fMain = new ActorMain();

            // new actActionReceiver().ConsoleWrite("Welcome in an action world");

            //var Input = new SDRInput("Machine") ;
            //var Region = new HTMRegion(Input);

            string s = string.Empty;

            do
            {
                s = Console.ReadLine();
                if (!string.IsNullOrEmpty(s))
                {
                    switch (s)
                    {
                    case "Many": { fMillion = new actMillion(); break; }

                    case "SendMany": { fMillion.Send(); break; }

                    case "quit": break;

                    case "Col":
                    {
                        var fLauncher = new TestLauncherActor();
                        fLauncher.SendAction(() =>
                            {
                                var collect = new CollectionActor <string>();
                                for (int i = 0; i < 100; i++)
                                {
                                    collect.Add($"Test {i}");
                                }

                                if (collect.Count() != 100)
                                {
                                    throw new Exception("failed");
                                }
                                // try to enum
                                var enumerable = collect.ToList();
                                if (enumerable.Count != 100)
                                {
                                    throw new ActorException("failed");
                                }
                                // try a query
                                var query = from col in collect
                                            where col.Contains('1')
                                            select col;
                                if (query.Count() != 19)
                                {
                                    throw new ActorException("failed");
                                }
                                fLauncher.Finish();
                            });
                        fLauncher.Wait();
                        break;
                    }

                    case "Ring":
                    {
                        new RingActor(10000, 10000);         // 30 sec
                        break;
                    }

                    case "Rings":
                    {
                        Console.Write("Enter ring size : ");
                        var rs = Console.ReadLine();
                        Console.Write("Enter cycle : ");
                        var cy = Console.ReadLine();
                        int.TryParse(rs, out int r);
                        int.TryParse(cy, out int y);
                        new RingActor(y, r);         // 30 sec
                        break;
                    }

                    case "Clients":
                    {
                        var    start   = DateTime.UtcNow.Ticks;
                        IActor aServer = new EchoServerActor();
                        for (int i = 0; i < 1000; i++)
                        {
                            EchoClientActor aClient = new EchoClientActor();        // new actEchoClient(aServer);
                                                                                    // DirectoryRequest.SendRegister("client + " + i.ToString(), aClient);
                            aClient.Connect("EchoServer");
                            aClient.SendMessage($"client-{i}");
                            // aClient.Disconnect();
                        }
                        var end = DateTime.UtcNow.Ticks;
                        Console.WriteLine("All client allocated {0}", (double)(end - start) / 10000.0);
                        break;
                    }

                    case "Download":
                    {
                        Console.WriteLine("trying Download");
                        IActor down = new ActorDownloadTest();
                        break;
                    }

                    //case "Brain":
                    //    {
                    //        Console.Write("Enter word : ");
                    //        var s2 = Console.ReadLine();
                    //        Input.SetData(s2);
                    //        Region.Run();
                    //        Region.Print();
                    //        break;
                    //    }
                    //case "Learn":
                    //    {
                    //        Input.SetData("Hello world ! ") ;
                    //        for (int i = 0; i < 100; i++)
                    //        {
                    //            Region.Run();
                    //            Region.Print();
                    //        }
                    //        break;
                    //    }
                    case "Pricing":
                    {
                        new ActorScheduler();
                        break;
                    }

                    case "ParserTest":
                    {
                        EchoActor.Echo(new ParserTest(), "");
                        break;
                    }

                    default:
                    {
                        EchoActor.Echo(new ActorAdminServer(), s);
                        break;
                    }
                    }
                }
            } while (s != "quit");
        }
Esempio n. 25
0
        public void Remoting_must_not_leak_actors()
        {
            var actorRef = Sys.ActorOf(EchoActor.Props(this, true), "echo");
            var echoPath = new RootActorPath(RARP.For(Sys).Provider.DefaultAddress) / "user" / "echo";

            var targets = new[] { "/system/endpointManager", "/system/transports" }.Select(x =>
            {
                Sys.ActorSelection(x).Tell(new Identify(0));
                return(ExpectMsg <ActorIdentity>().Subject);
            }).ToList();

            var initialActors = targets.SelectMany(CollectLiveActors).ToImmutableHashSet();

            // Clean shutdown case
            for (var i = 1; i <= 3; i++)
            {
                var remoteSystem = ActorSystem.Create("remote",
                                                      ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 0")
                                                      .WithFallback(Sys.Settings.Config));

                try
                {
                    var probe = CreateTestProbe(remoteSystem);
                    remoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref);
                    probe.ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null);
                }
                finally
                {
                    remoteSystem.Terminate();
                }

                remoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue();
            }

            // Quarantine an old incarnation case
            for (var i = 1; i <= 3; i++)
            {
                // always use the same address
                var remoteSystem = ActorSystem.Create("remote",
                                                      ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 2553")
                                                      .WithFallback(Sys.Settings.Config));

                try
                {
                    var remoteAddress = RARP.For(remoteSystem).Provider.DefaultAddress;
                    remoteSystem.ActorOf(Props.Create(() => new StoppableActor()), "stoppable");

                    // the message from remote to local will cause inbound connection established
                    var probe = CreateTestProbe(remoteSystem);
                    remoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref);
                    probe.ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null);

                    var beforeQuarantineActors = targets.SelectMany(CollectLiveActors).ToImmutableHashSet();

                    // it must not quarantine the current connection
                    RARP.For(Sys)
                    .Provider.Transport.Quarantine(remoteAddress, AddressUidExtension.Uid(remoteSystem) + 1);

                    // the message from local to remote should reuse passive inbound connection
                    Sys.ActorSelection(new RootActorPath(remoteAddress) / "user" / "stoppable").Tell(new Identify(1));
                    ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null);

                    var afterQuarantineActors = targets.SelectMany(CollectLiveActors).ToImmutableHashSet();

                    AssertActors(beforeQuarantineActors, afterQuarantineActors);
                }
                finally
                {
                    remoteSystem.Terminate();
                }
                remoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue();
            }

            // Missing SHUTDOWN case
            for (var i = 1; i <= 3; i++)
            {
                var remoteSystem = ActorSystem.Create("remote",
                                                      ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 0")
                                                      .WithFallback(Sys.Settings.Config));
                var remoteAddress = RARP.For(remoteSystem).Provider.DefaultAddress;

                try
                {
                    var probe = CreateTestProbe(remoteSystem);
                    remoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref);
                    probe.ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null);

                    // This will make sure that no SHUTDOWN message gets through
                    RARP.For(Sys).Provider.Transport.ManagementCommand(new ForceDisassociate(remoteAddress))
                    .Wait(TimeSpan.FromSeconds(3)).ShouldBeTrue();
                }
                finally
                {
                    remoteSystem.Terminate();
                }

                EventFilter.Warning(contains: "Association with remote system").ExpectOne(() =>
                {
                    remoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue();
                });
            }

            // Remote idle for too long case
            var idleRemoteSystem = ActorSystem.Create("remote",
                                                      ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 0")
                                                      .WithFallback(Sys.Settings.Config));
            var idleRemoteAddress = RARP.For(idleRemoteSystem).Provider.DefaultAddress;

            idleRemoteSystem.ActorOf(Props.Create <StoppableActor>(), "stoppable");

            try
            {
                var probe = CreateTestProbe(idleRemoteSystem);

                idleRemoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref);
                probe.ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null);

                // Watch a remote actor - this results in system message traffic
                Sys.ActorSelection(new RootActorPath(idleRemoteAddress) / "user" / "stoppable").Tell(new Identify(1));
                var remoteActor = ExpectMsg <ActorIdentity>().Subject;
                Watch(remoteActor);
                remoteActor.Tell("stop");
                ExpectTerminated(remoteActor);
                // All system messages have been acked now on this side

                // This will make sure that no SHUTDOWN message gets through
                RARP.For(Sys).Provider.Transport.ManagementCommand(new ForceDisassociate(idleRemoteAddress))
                .Wait(TimeSpan.FromSeconds(3)).ShouldBeTrue();
            }
            finally
            {
                idleRemoteSystem.Terminate();
            }

            EventFilter.Warning(contains: "Association with remote system").ExpectOne(() =>
            {
                idleRemoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue();
            });

            /*
             * Wait for the ReliableDeliverySupervisor to receive its "TooLongIdle" message,
             * which will throw a HopelessAssociation wrapped around a TimeoutException.
             */
            EventFilter.Exception <TimeoutException>().ExpectOne(() => { });

            AwaitAssert(() =>
            {
                AssertActors(initialActors, targets.SelectMany(CollectLiveActors).ToImmutableHashSet());
            }, 5.Seconds());
        }