public void BackoffOnRestartSupervisor_must_respect_maxNrOfRetries_property_of_OneForOneStrategy()
        {
            var probe      = CreateTestProbe();
            var supervisor = Sys.ActorOf(SupervisorProps(probe.Ref));

            probe.ExpectMsg("STARTED");

            EventFilter.Exception <TestException>().Expect(5, () =>
            {
                probe.Watch(supervisor);
                for (int i = 1; i <= 5; i++)
                {
                    supervisor.Tell("THROW");
                    if (i < 5)
                    {
                        // Since we should've died on this throw, don't expect to be started.
                        // We're not testing timing, so set a reasonably high timeout.
                        probe.ExpectMsg("STARTED", 4.Seconds());
                    }
                }

                probe.ExpectTerminated(supervisor);
            });
        }
Exemple #2
0
        public void BackoffSupervisor_must_support_default_stopping_strategy_when_using_Backoff_OnStop()
        {
            // TODO: use FilterException
            EventFilter.Exception <TestException>().Expect(1, () =>
            {
                var supervisor = Create(OnStopOptions().WithDefaultStoppingStrategy());
                supervisor.Tell(BackoffSupervisor.GetCurrentChild.Instance);
                var c1 = ExpectMsg <BackoffSupervisor.CurrentChild>().Ref;
                Watch(c1);
                supervisor.Tell(BackoffSupervisor.GetRestartCount.Instance);
                ExpectMsg <BackoffSupervisor.RestartCount>().Count.Should().Be(0);

                c1.Tell("boom");
                ExpectTerminated(c1);
                AwaitAssert(() =>
                {
                    supervisor.Tell(BackoffSupervisor.GetCurrentChild.Instance);
                    // new instance
                    ExpectMsg <BackoffSupervisor.CurrentChild>().Ref.Should().NotBeSameAs(c1);
                });
                supervisor.Tell(BackoffSupervisor.GetRestartCount.Instance);
                ExpectMsg <BackoffSupervisor.RestartCount>().Count.Should().Be(1);
            });
        }
Exemple #3
0
        public void DeathWatch_must_fail_a_monitor_which_doesnt_handle_Terminated()
        {
            EventFilter.Exception <ActorKilledException>().And.Exception <DeathPactException>().Expect(2, () =>
            {
                var strategy = new FailedSupervisorStrategy(TestActor);
                _supervisor  = Sys.ActorOf(Props.Create(() => new Supervisor(strategy)).WithDeploy(Deploy.Local));

                var failed  = _supervisor.Ask(Props.Empty).Result as IActorRef;
                var brother = _supervisor.Ask(Props.Create(() => new BrotherActor(failed))).Result as IActorRef;

                StartWatching(brother);

                failed.Tell(Kill.Instance);
                var result = ReceiveWhile(TimeSpan.FromSeconds(5), msg =>
                {
                    var res = 0;
                    msg.Match()
                    .With <FF>(ff =>
                    {
                        if (ff.Fail.Cause is ActorKilledException && ff.Fail.Child == failed)
                        {
                            res = 1;
                        }
                        if (ff.Fail.Cause is DeathPactException && ff.Fail.Child == brother)
                        {
                            res = 2;
                        }
                    })
                    .With <WrappedTerminated>(x => res = x.Terminated.ActorRef == brother ? 3 : 0);
                    return(res.ToString());
                }, 3);

                ((IInternalActorRef)TestActor).IsTerminated.ShouldBe(false);
                result.ShouldOnlyContainInOrder("1", "2", "3");
            });
        }
Exemple #4
0
        public void A_Flow_based_on_an_iterable_must_produce_OnError_when_iterator_throws()
        {
            var iterable = Enumerable.Range(1, 3).Select(x =>
            {
                if (x == 2)
                {
                    throw new IllegalStateException("not two");
                }
                return(x);
            });
            var p = Source.From(iterable).RunWith(Sink.AsPublisher <int>(false), Materializer);
            var c = this.CreateManualSubscriberProbe <int>();

            p.Subscribe(c);
            var sub = c.ExpectSubscription();

            sub.Request(1);
            c.ExpectNext(1);
            c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
            EventFilter.Exception <IllegalStateException>("not two").ExpectOne(() => sub.Request(2));
            c.ExpectError().Message.Should().Be("not two");
            sub.Request(2);
            c.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
        }
Exemple #5
0
        public void DistributedPubSubMediator_can_be_activated_in_child_actor()
        {
            EventFilter.Exception <NullReferenceException>().Expect(0, () =>
            {
                var actor = Sys.ActorOf((dsl, context) =>
                {
                    IActorRef mediator = null;
                    dsl.OnPreStart     = actorContext =>
                    {
                        mediator = DistributedPubSub.Get(actorContext.System).Mediator;
                    };

                    dsl.Receive <string>(s => s.Equals("check"), (s, actorContext) =>
                    {
                        actorContext.Sender.Tell(mediator);
                    });
                }, "childActor");

                actor.Tell("check");
                var a = ExpectMsg <IActorRef>();
                a.ShouldNotBe(ActorRefs.NoSender);
                a.ShouldNotBe(ActorRefs.Nobody);
            });
        }
        public void A_supervisor_hierarchy_must_Restart_Manager_And_Workers_In_AllForOne()
        {
            var countDown = new CountdownEvent(4);
            SupervisorStrategy strategy = new OneForOneStrategy(_ => Directive.Restart);
            var boss = ActorOf(Props.Create(() => new Supervisor(strategy)), "boss");

            Func <Exception, Directive> decider = _ => { return(Directive.Escalate); };
            var managerProps = new PropsWithName(Props.Create(() => new CountDownActor(countDown, new AllForOneStrategy(decider))), "manager");
            var manager      = boss.Ask <IActorRef>(managerProps, TestKitSettings.DefaultTimeout).Result;

            var workerProps = Props.Create(() => new CountDownActor(countDown, SupervisorStrategy.DefaultStrategy));
            var worker1     = manager.Ask <IActorRef>(new PropsWithName(workerProps, "worker1"), TestKitSettings.DefaultTimeout).Result;
            var worker2     = manager.Ask <IActorRef>(new PropsWithName(workerProps, "worker2"), TestKitSettings.DefaultTimeout).Result;
            var worker3     = manager.Ask <IActorRef>(new PropsWithName(workerProps, "worker3"), TestKitSettings.DefaultTimeout).Result;

            EventFilter.Exception <ActorKilledException>().ExpectOne(() =>
            {
                worker1.Tell(Kill.Instance);
                // manager + all workers should be restarted by only killing a worker
                // manager doesn't trap exits, so boss will restart manager

                countDown.Wait(TimeSpan.FromSeconds(5)).ShouldBe(true);
            });
        }
        public void When_child_revives_monitor_should_be_created_even_on_collision()
        {
            var ChildId = "testChild";

            var create = new MessageMetadataEnvelop <ICommand>(new InflateNewBallonCommand(42, ChildId),
                                                               MessageMetadata.New(ChildId, null, null));

            _hubRef.Tell(create);

            Task.Run(async() =>
            {
                while (true)
                {
                    var activate = new MessageMetadataEnvelop <ICommand>(new WriteTitleCommand(100, ChildId),
                                                                         MessageMetadata.New(ChildId, null, null));

                    _hubRef.Tell(activate);
                    await Task.Delay(150);
                }
            });

            EventFilter.Exception <InvalidActorNameException>()
            .Expect(0, TimeSpan.FromSeconds(10), () => { });
        }
Exemple #8
0
        public void Unfold_Source_must_terminate_with_a_failure_if_there_is_an_exception_thrown()
        {
            EventFilter.Exception <Exception>(message: "expected").ExpectOne(() =>
            {
                var task = Source.Unfold((0, 1), tuple =>
                {
                    var a = tuple.Item1;
                    var b = tuple.Item2;
                    if (a > 10000000)
                    {
                        throw new Exception("expected");
                    }

                    return(((b, a + b), a).AsOption());
                }).RunAggregate(new LinkedList <int>(), (ints, i) =>
                {
                    ints.AddFirst(i);
                    return(ints);
                }, Materializer);
                task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3)))
                .Should().Throw <Exception>()
                .WithMessage("expected");
            });
        }
        public void BackoffSupervisor_must_support_manual_reset()
        {
            Action <IActorRef> assertManualReset = supervisor =>
            {
                supervisor.Tell(BackoffSupervisor.GetCurrentChild.Instance);
                var c1 = ExpectMsg <BackoffSupervisor.CurrentChild>().Ref;
                Watch(c1);
                c1.Tell("boom");
                ExpectTerminated(c1);

                AwaitAssert(() =>
                {
                    supervisor.Tell(BackoffSupervisor.GetRestartCount.Instance);
                    ExpectMsg <BackoffSupervisor.RestartCount>().Count.Should().Be(1);
                });

                AwaitAssert(() =>
                {
                    supervisor.Tell(BackoffSupervisor.GetCurrentChild.Instance);
                    // new instance
                    ExpectMsg <BackoffSupervisor.CurrentChild>().Ref.Should().NotBeSameAs(c1);
                });

                // TODO: this Thread.Sleep should be removed
                Thread.Sleep(500);

                supervisor.Tell("hello");
                ExpectMsg("hello");

                // making sure the Reset is handled by supervisor
                supervisor.Tell("hello");
                ExpectMsg("hello");

                supervisor.Tell(BackoffSupervisor.GetRestartCount.Instance);
                ExpectMsg <BackoffSupervisor.RestartCount>().Count.Should().Be(0);
            };

            // TODO: use FilterException
            EventFilter.Exception <TestException>().Expect(2, () =>
            {
                var stoppingStrategy = new OneForOneStrategy(ex =>
                {
                    if (ex is TestException)
                    {
                        return(Directive.Stop);
                    }

                    // TODO: should restart be there?
                    return(Directive.Restart);
                });

                var restartingStrategy = new OneForOneStrategy(ex =>
                {
                    if (ex is TestException)
                    {
                        return(Directive.Restart);
                    }

                    // TODO: should restart be there?
                    return(Directive.Restart);
                });

                assertManualReset(
                    Create(OnStopOptions(ManualChild.Props(TestActor))
                           .WithManualReset()
                           .WithSupervisorStrategy(stoppingStrategy)));

                assertManualReset(
                    Create(OnFailureOptions(ManualChild.Props(TestActor))
                           .WithManualReset()
                           .WithSupervisorStrategy(restartingStrategy)));
            });
        }
        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());
        }
 public ActorPublisherSpec(ITestOutputHelper output = null) : base(Config, output)
 {
     EventFilter.Exception <IllegalStateException>().Mute();
 }
 public void DoNotInterceptMessagesWhenSourceDoesNotMatch()
 {
     EventFilter.Exception <SomeException>(source: "this is clearly not the source");
     Log.Error(new SomeException(), "whatever");
     ExpectMsg <Error>(err => (string)err.Message == "whatever");
 }
 public void CanInterceptMessagesWhenContainsIsSpecified()
 {
     EventFilter.Exception <SomeException>(contains: "ate")
     .ExpectOne(() => Log.Error(new SomeException(), "whatever"));
     ExpectNoMsg(TimeSpan.FromMilliseconds(100));
 }
 public void SingleExceptionIsIntercepted()
 {
     EventFilter.Exception <SomeException>()
     .ExpectOne(() => Log.Error(new SomeException(), "whatever"));
     ExpectNoMsg(TimeSpan.FromMilliseconds(100));
 }