public void A_UnfoldResourceAsyncSource_must_close_resource_when_stream_is_abruptly_termianted()
        {
            var closeLatch   = new TestLatch(1);
            var materializer = ActorMaterializer.Create(Sys);
            var p            = Source.UnfoldResourceAsync(_open, Read, reader =>
            {
                closeLatch.CountDown();
                return(Task.FromResult(0));
            }).RunWith(Sink.AsPublisher <string>(false), materializer);
            var c = this.CreateManualSubscriberProbe <string>();

            p.Subscribe(c);
            materializer.Shutdown();
            closeLatch.Ready(TimeSpan.FromSeconds(10));
        }
Example #2
0
        public void Random_pool_must_deliver_a_broadcast_message_using_the_Tell()
        {
            const int routeeCount = 6;
            var       helloLatch  = new TestLatch(routeeCount);
            var       stopLatch   = new TestLatch(routeeCount);

            var actor = Sys.ActorOf(new RandomPool(routeeCount)
                                    .Props(Props.Create(() => new RandomBroadcastActor(helloLatch, stopLatch))), "random-broadcast");

            actor.Tell(new Broadcast("hello"));
            helloLatch.Ready(5.Seconds());

            Sys.Stop(actor);
            stopLatch.Ready(5.Seconds());
        }
Example #3
0
        public void DefaultResizer_must_be_possible_to_define_programmatically()
        {
            var latch   = new TestLatch(3);
            var resizer = new DefaultResizer(2, 3);
            var router  = Sys.ActorOf(Props.Create <ResizerTestActor>().WithRouter(new RoundRobinPool(0, resizer)));

            router.Tell(latch);
            router.Tell(latch);
            router.Tell(latch);

            latch.Ready(TestKitSettings.DefaultTimeout);

            //messagesPerResize is 10 so there is no risk of additional resize
            (RouteeSize(router)).ShouldBe(2);
        }
Example #4
0
        public void BTActor_SequenceReceiveSequenceReceive()
        {
            var pipe = new List<string>();
            var latch = new TestLatch();

            var bt = Sys.ActorOf(Props.Create(() => new SequenceReceiveSequenceReceive(pipe, latch)));

            bt.Tell("1");
            bt.Tell("3");
            bt.Tell("4");

            latch.Ready();

            Assert.Equal(new[] { "1", "2", "3", "4" }, pipe);
        }
        public async Task Scatter_gather_router_must_return_response_even_if_one_of_the_actors_has_stopped()
        {
            var shutdownLatch = new TestLatch(1);
            var actor1        = Sys.ActorOf(Props.Create(() => new StopActor(1)));
            var actor2        = Sys.ActorOf(Props.Create(() => new StopActor(14)));
            var paths         = new [] { actor1, actor2 };
            var routedActor   = Sys.ActorOf(new ScatterGatherFirstCompletedGroup(paths, TimeSpan.FromSeconds(3)).Props());

            routedActor.Tell(new Broadcast(new Stop(1)));
            shutdownLatch.Open();

            var res = await routedActor.Ask <int>(0, TimeSpan.FromSeconds(10));

            res.ShouldBe(14);
        }
Example #6
0
 public ShortTimeoutLongTask(TestLatch latch, AtomicCounter counter)
 {
     StartWith(
         Loop(
             ReceiveAny(s => s.Equals("RUN"),
                 After(
                     Timeout(TimeSpan.FromMilliseconds(100),
                         Delay(5.Seconds(), Execute(_ => counter.GetAndIncrement())),
                         Execute(_ =>
                         {
                             counter.GetAndDecrement();
                             Sender.Tell("TIMEOUT");
                         })),
                     Execute(_ => latch.CountDown())))), null);
 }
Example #7
0
        public void BTActor_BecomePingPong()
        {
            var pipe = new List<string>();
            var latch = new TestLatch(5);

            var bt = Sys.ActorOf(Props.Create(() => new BecomePingPong(pipe, latch)));

            bt.Tell("RUN", TestActor);
            bt.Tell("PING", TestActor);

            latch.Ready();

            ExpectMsg("DONE");

            Assert.Equal(new[] { "PING", "PONG", "PING", "PONG" }, pipe);
        }
Example #8
0
        public void PersistentActor_should_preserve_order_of_incoming_messages()
        {
            var pref = ActorOf(Props.Create(() => new StressOrdering(Name)));

            pref.Tell(new Cmd("a"));
            var latch = new TestLatch(1);

            pref.Tell(new LatchCmd(latch, "b"));
            pref.Tell("c");
            ExpectMsg("a");
            ExpectMsg("b");
            pref.Tell("d");
            latch.CountDown();
            ExpectMsg("c");
            ExpectMsg("d");
        }
Example #9
0
            public SlowlyFailingActor(TestLatch latch)
            {
                _latch = latch;

                Receive <string>(str => str.Equals("THROW"), msg =>
                {
                    Sender.Tell("THROWN");
                    throw new NormalException();
                    return;
                });

                Receive <string>(str => str.Equals("PING"), msg =>
                {
                    Sender.Tell("PONG");
                });
            }
        public void An_actor_with_receive_timeout_must_be_able_to_turn_on_timeout_in_NotInfluenceReceiveTimeout_message_handler()
        {
            var timeoutLatch = new TestLatch();

            Action <IActorDsl> actor = d =>
            {
                d.Receive <TransparentTick>((_, c) => c.SetReceiveTimeout(500.Milliseconds()));
                d.Receive <ReceiveTimeout>((_, __) => timeoutLatch.Open());
            };
            var timeoutActor = Sys.ActorOf(Props.Create(() => new Act(actor)));

            timeoutActor.Tell(new TransparentTick());

            timeoutLatch.Ready(TestKitSettings.DefaultTimeout);
            Sys.Stop(timeoutActor);
        }
Example #11
0
        public void DefaultResizer_must_be_possible_to_define_programmatically()
        {
            var latch   = new TestLatch(3);
            var resizer = new DefaultResizer(lower: 2, upper: 3);

            var router = Sys.ActorOf(new RoundRobinPool(0, resizer).Props(Props.Create <ResizerTestActor>()));

            router.Tell(latch);
            router.Tell(latch);
            router.Tell(latch);

            latch.Ready(RemainingOrDefault);

            // MessagesPerResize is 10 so there is no risk of additional resize
            RouteeSize(router).Should().Be(2);
        }
Example #12
0
        public void Conflate_must_restart_when_seed_throws_and_a_RestartDescider_is_used()
        {
            var sourceProbe   = this.CreatePublisherProbe <int>();
            var sinkProbe     = this.CreateManualSubscriberProbe <int>();
            var exceptionlath = new TestLatch();

            var graph = Source.FromPublisher(sourceProbe).ConflateWithSeed(i =>
            {
                if (i % 2 == 0)
                {
                    exceptionlath.Open();
                    throw new TestException("I hate even seed numbers");
                }
                return(i);
            }, (sum, i) => sum + i)
                        .WithAttributes(ActorAttributes.CreateSupervisionStrategy(Deciders.RestartingDecider))
                        .To(Sink.FromSubscriber(sinkProbe))
                        .WithAttributes(Attributes.CreateInputBuffer(1, 1));

            RunnableGraph.FromGraph(graph).Run(Materializer);

            var sub     = sourceProbe.ExpectSubscription();
            var sinkSub = sinkProbe.ExpectSubscription();

            // push the first value
            sub.ExpectRequest(1);
            sub.SendNext(1);

            // and consume it, so that the next element
            // will trigger seed
            sinkSub.Request(1);
            sinkProbe.ExpectNext(1);

            sub.ExpectRequest(1);
            sub.SendNext(2);

            // make sure the seed exception happened
            // before going any further
            exceptionlath.Ready(TimeSpan.FromSeconds(3));

            sub.ExpectRequest(1);
            sub.SendNext(3);

            // now we should have lost the 2 and the accumulated state
            sinkSub.Request(1);
            sinkProbe.ExpectNext(3);
        }
        public void An_actor_with_receive_timeout_must_be_able_to_turn_off_timeout_in_NotInfluenceReceiveTimeout_message_handler()
        {
            var timeoutLatch = new TestLatch();

            Action <IActorDsl> actor = d =>
            {
                d.OnPreStart = c => c.SetReceiveTimeout(500.Milliseconds());
                d.Receive <TransparentTick>((_, c) => c.SetReceiveTimeout(null));
                d.Receive <ReceiveTimeout>((_, __) => timeoutLatch.Open());
            };
            var timeoutActor = Sys.ActorOf(Props.Create(() => new Act(actor)));

            timeoutActor.Tell(new TransparentTick());

            Intercept <TimeoutException>(() => timeoutLatch.Ready(1.Seconds()));
            Sys.Stop(timeoutActor);
        }
Example #14
0
        public void BTActor_ParallelLoopReceive()
        {
            var counter = new AtomicCounter(0);
            var latch = new TestLatch();

            var bt = Sys.ActorOf(Props.Create(() => new ParallelLoopReceive(latch)));

            bt.Tell("A", TestActor);
            bt.Tell("B", TestActor);
            ExpectMsg("1A2A");
            ExpectMsg("1B2B");

            bt.Tell("C");
            ExpectMsg("1C2C");
            bt.Tell("D");
            ExpectMsg("1D2D");
        }
Example #15
0
        public void BTActor_Short_Timeout_Long_Delay()
        {
            TestLatch latch = new TestLatch(2);
            AtomicCounter counter = new AtomicCounter(0);

            var bt = Sys.ActorOf(Props.Create(() => new ShortTimeoutLongTask(latch, counter)));

            bt.Tell("RUN", TestActor);
            ExpectMsg("TIMEOUT");
            bt.Tell("RUN", TestActor);
            ExpectMsg("TIMEOUT");

            latch.Ready();
            Assert.Equal(-2, counter.Current);

            ExpectNoMsg(100);
        }
Example #16
0
        public void BTActor_Long_Timeout_Short_Delay()
        {
            TestLatch latch = new TestLatch();
            AtomicCounter counter = new AtomicCounter(0);

            var bt = Sys.ActorOf(Props.Create(() => new LongTimeoutShortTask(latch, counter)));

            bt.Tell("RUN", TestActor);
            latch.Ready();
            latch.Reset();
            bt.Tell("RUN", TestActor);

            latch.Ready();
            Assert.Equal(2, counter.Current);

            ExpectNoMsg(200);
        }
Example #17
0
        public async Task Supervisor_with_Random_Group_router_should_handle_multiple_child_failure()
        {
            const int connectionCount = 10;
            var       doneLatch       = new TestLatch(connectionCount);

            var replies = new Dictionary <string, int>();

            for (int i = 1; i <= connectionCount; i++)
            {
                replies["target-" + i] = 0;
            }

            var paths = Enumerable.Range(1, connectionCount).Select(n =>
            {
                var routee = Sys.ActorOf(Props.Create(() => new SimpleActor()), "target-" + n);
                return(routee.Path.ToStringWithoutAddress());
            });

            var groupProps = Props.Empty
                             .WithRouter(new RandomGroup(paths))
                             .WithSupervisorStrategy(new OneForOneStrategy(Decider.From(Directive.Escalate)));
            var groupActorRef = Sys.ActorOf(groupProps, "random-group1");

            // rapidly fail children. the router should handle children failing
            // while itself is still being recreated
            for (var i = 0; i < 20; i++)
            {
                groupActorRef.Tell(1);
            }

            var failCount = 0;

            for (var i = 0; i < 20; i++)
            {
                try
                {
                    await groupActorRef.Ask <int>(2, _delay);
                }
                catch
                {
                    failCount++;
                }
            }
            failCount.Should().Be(0);
        }
Example #18
0
        public void Set_of_connected_cluster_systems_must_when_three_nodes_after_cluster_convergence_updates_membership_table_then_all_MembershipChangeListeners_should_be_triggered()
        {
            var latch             = new TestLatch();
            var expectedAddresses = ImmutableList.Create(GetAddress(_config.First), GetAddress(_config.Second), GetAddress(_config.Third));
            var listener          = Sys.ActorOf(Props.Create(() => new Listener(latch, expectedAddresses)).WithDeploy(Deploy.Local));

            Cluster.Subscribe(listener, new[] { typeof(ClusterEvent.IMemberEvent) });
            EnterBarrier("listener-2-registered");

            RunOn(() =>
            {
                Cluster.Join(GetAddress(_config.First));
            }, _config.Third);

            latch.Ready();

            EnterBarrier("after-2");
        }
Example #19
0
        public void GracefulStop_must_complete_Task_with_TaskCanceledException_when_actor_not_terminated_within_timeout()
        {
            //arrange
            var target = Sys.ActorOf <TargetActor>();
            var latch  = new TestLatch();

            //act
            target.Tell(Tuple.Create(latch, TimeSpan.FromSeconds(2)));

            //assert
            XAssert.Throws <TaskCanceledException>(() =>
            {
                var task = target.GracefulStop(TimeSpan.FromMilliseconds(500));
                task.Wait();
                var result = task.Result;
            });
            latch.Open();
        }
Example #20
0
        public void BroadcastGroup_router_must_broadcast_message_using_Ask()
        {
            var doneLatch = new TestLatch(Sys, 2);
            var counter1  = new AtomicCounter(0);
            var counter2  = new AtomicCounter(0);
            var actor1    = Sys.ActorOf(Props.Create(() => new BroadcastTarget(doneLatch, counter1)));
            var actor2    = Sys.ActorOf(Props.Create(() => new BroadcastTarget(doneLatch, counter2)));

            var routedActor = Sys.ActorOf(Props.Create <TestActor>().WithRouter(new BroadcastGroup(actor1.Path.ToString(), actor2.Path.ToString())));

            routedActor.Ask(new Broadcast(1));
            routedActor.Tell(new Broadcast("end"));

            doneLatch.Ready(TimeSpan.FromSeconds(1));

            counter1.Current.ShouldBe(1);
            counter2.Current.ShouldBe(1);
        }
        public async Task Scatter_gather_group_must_return_response_even_if_one_of_the_actors_has_stopped()
        {
            var shutdownLatch = new TestLatch(1);

            var actor1 = Sys.ActorOf(Props.Create(() => new StopActor(1, shutdownLatch)));
            var actor2 = Sys.ActorOf(Props.Create(() => new StopActor(14, shutdownLatch)));

            var paths = new List <string> {
                actor1.Path.ToString(), actor2.Path.ToString()
            };
            var routedActor = Sys.ActorOf(new ScatterGatherFirstCompletedGroup(paths, TimeSpan.FromSeconds(3)).Props());

            routedActor.Tell(new Broadcast(new Stop(1)));
            shutdownLatch.Ready(TestKitSettings.DefaultTimeout);
            var res = await routedActor.Ask <int>(0, TimeSpan.FromSeconds(10));

            res.Should().Be(14);
        }
        public void Scatter_gather_router_must_deliver_a_broadcast_message_using_tell()
        {
            var doneLatch = new TestLatch(sys, 2);
            var counter1  = new AtomicInteger(0);
            var counter2  = new AtomicInteger(0);
            var actor1    = sys.ActorOf(Props.Create(() => new BroadcastTarget(doneLatch, counter1)));
            var actor2    = sys.ActorOf(Props.Create(() => new BroadcastTarget(doneLatch, counter2)));

            var routedActor = sys.ActorOf(Props.Create <TestActor>().WithRouter(new ScatterGatherFirstCompletedGroup(TimeSpan.FromSeconds(1), actor1.Path.ToString(), actor2.Path.ToString())));

            routedActor.Tell(new Broadcast(1));
            routedActor.Tell(new Broadcast("end"));

            doneLatch.Ready(TimeSpan.FromSeconds(1));

            counter1.Value.ShouldBe(1);
            counter2.Value.ShouldBe(1);
        }
        public void An_actor_with_receive_timeout_must_get_timeout_while_receiving_only_NotInfluenceReceiveTimeout_messages()
        {
            var timeoutLatch = new TestLatch(2);

            Action <IActorDsl> actor = d =>
            {
                d.OnPreStart = c => c.SetReceiveTimeout(TimeSpan.FromSeconds(1));
                d.Receive <ReceiveTimeout>((o, c) =>
                {
                    c.Self.Tell(new TransparentTick());
                    timeoutLatch.CountDown();
                });
                d.Receive <TransparentTick>((_, __) => { });
            };
            var timeoutActor = Sys.ActorOf(Props.Create(() => new Act(actor)));

            timeoutLatch.Ready(TestKitSettings.DefaultTimeout);
            Sys.Stop(timeoutActor);
        }
Example #24
0
        public void Routers_in_general_must_not_terminate_when_resizer_is_used()
        {
            var latch   = new TestLatch(1);
            var resizer = new TestResizer(latch);
            var router  = Sys.ActorOf(new RoundRobinPool(0, resizer).Props(Props.Create <BlackHoleActor>()));

            Watch(router);
            latch.Ready(RemainingOrDefault);

            router.Tell(new GetRoutees());
            var routees = ExpectMsg <Routees>().Members.ToList();

            routees.Count.Should().Be(2);

            routees.ForEach(r => r.Send(PoisonPill.Instance, TestActor));

            // expect no Terminated
            ExpectNoMsg(2.Seconds());
        }
Example #25
0
 protected override void OnReceive(object message)
 {
     message.Match()
     .With <Tuple <TestLatch, TestLatch> >(t =>
     {
         TestLatch busy = t.Item1, receivedLatch = t.Item2;
         usedActors.TryAdd(0, Self.Path.ToString());
         Self.Tell("another in busy mailbox");
         receivedLatch.CountDown();
         busy.Ready(TestLatch.DefaultTimeout);
     })
     .With <Tuple <int, TestLatch> >(t =>
     {
         var msg = t.Item1; var receivedLatch = t.Item2;
         usedActors.TryAdd(msg, Self.Path.ToString());
         receivedLatch.CountDown();
     })
     .With <string>(t => { });
 }
        public void An_actor_with_receive_timeout_must_get_timeout_while_receiving_NotInfluenceReceiveTimeout_messages()
        {
            var timeoutLatch = new TestLatch();
            var timeoutActor = Sys.ActorOf(Props.Create(() => new TimeoutActor(timeoutLatch, TimeSpan.FromSeconds(1))));

            var cancellationToken = new CancellationTokenSource();

            Sys.Scheduler.Schedule(
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(100),
                () =>
            {
                timeoutActor.Tell(new TransparentTick());
                timeoutActor.Tell(new Identify(null));
            }, cancellationToken.Token);

            timeoutLatch.Ready(TestKitSettings.DefaultTimeout);
            cancellationToken.Cancel();
            Sys.Stop(timeoutActor);
        }
Example #27
0
            public Listener(TestLatch latch, ImmutableList <Address> expectedAddresses)
            {
                _latch             = latch;
                _expectedAddresses = expectedAddresses;

                Receive <ClusterEvent.CurrentClusterState>(state =>
                {
                    _members = state.Members;
                });

                Receive <ClusterEvent.MemberUp>(m =>
                {
                    _members = _members.Remove(m.Member).Add(m.Member);

                    if (!_members.Select(c => c.Address).Except(_expectedAddresses).Any())
                    {
                        _latch.CountDown();
                    }
                });
            }
Example #28
0
        public void Router_in_general_must_not_terminate_when_resizer_is_used()
        {
            var latch   = new TestLatch(Sys, 1);
            var resizer = new TestResizer(latch);
            var router  =
                Sys.ActorOf(new RoundRobinPool(0, resizer, SupervisorStrategy.DefaultStrategy, "").Props(Props.Create <NoOpActor>()));

            Watch(router);

            latch.Open();
            //Await.ready(latch, remainingOrDefault); //TODO: what is remainingOrDefault

            router.Tell(new GetRoutees(), TestActor);
            var routees = ExpectMsg <Routees>().Members.ToList();

            routees.Count().ShouldBe(2);
            routees.ForEach(r => r.Send(PoisonPill.Instance, TestActor));
            // expect no Terminated
            ExpectNoMsg(TimeSpan.FromSeconds(2));
        }
Example #29
0
        public void ActorGraphInterpreter_should_trigger_PostStop_in_all_stages_when_abruptly_terminated_and_no_upstream_boundaries()
        {
            this.AssertAllStagesStopped(() =>
            {
                var materializer = ActorMaterializer.Create(Sys);
                var gotStop      = new TestLatch(1);
                var downstream   = this.CreateSubscriberProbe <string>();

                Source.Repeat("whatever")
                .Via(new PostStopSnitchFlow(gotStop))
                .To(Sink.FromSubscriber(downstream)).Run(materializer);

                downstream.RequestNext();

                materializer.Shutdown();
                gotStop.Ready(RemainingOrDefault);

                downstream.ExpectError().Should().BeOfType <AbruptTerminationException>();
            }, Materializer);
        }
Example #30
0
        public void Smallest_mailbox_router_must_deliver_messages_to_idle_actor()
        {
            var usedActors = new ConcurrentDictionary <int, string>();
            var router     = Sys.ActorOf(new SmallestMailboxPool(3).Props(Props.Create(() => new SmallestMailboxActor(usedActors))));

            var busy      = new TestLatch(1);
            var received0 = new TestLatch(1);

            router.Tell(Tuple.Create(busy, received0));
            received0.Ready(TestLatch.DefaultTimeout);

            var received1 = new TestLatch(1);

            router.Tell(Tuple.Create(1, received1));
            received1.Ready(TestLatch.DefaultTimeout);

            var received2 = new TestLatch(1);

            router.Tell(Tuple.Create(2, received2));
            received2.Ready(TestLatch.DefaultTimeout);

            var received3 = new TestLatch(1);

            router.Tell(Tuple.Create(3, received3));
            received3.Ready(TestLatch.DefaultTimeout);

            busy.CountDown();

            var busyPath = usedActors[0];

            Assert.NotEqual(busyPath, null);

            Assert.Equal(usedActors.Count, 4);
            var path1 = usedActors[1];
            var path2 = usedActors[2];
            var path3 = usedActors[3];

            Assert.NotEqual(path1, busyPath);
            Assert.NotEqual(path2, busyPath);
            Assert.NotEqual(path3, busyPath);
        }