Exemplo n.º 1
0
 protected PluginSpec(Config config = null, string actorSystemName = null, ITestOutputHelper output = null)
     : base(FromConfig(config), actorSystemName, output)
 {
     Extension  = Persistence.Instance.Apply(Sys as ExtendedActorSystem);
     Pid        = "p-" + Counter.IncrementAndGet();
     WriterGuid = Guid.NewGuid().ToString();
 }
Exemplo n.º 2
0
        private static void Main(string[] args)
        {
 //           var config = ConfigurationFactory.ParseString(@"
 //               akka.loglevel = DEBUG
 //               akka.actor.debug.lifecycle = off");

            var config = ConfigurationFactory.ParseString(@"
                akka.loglevel = DEBUG 
                akka.actor.debug.lifecycle = off
                akka.actor.deployment 
                {
                    /router1 
                    {
                        router = smallest-mailbox-pool
                        nr-of-instances = 3
                    }
                }
");

//            var config = ConfigurationFactory.ParseString(@"
//                akka.loglevel = DEBUG 
//                akka.actor.debug.lifecycle = off
//                akka.actor.deployment 
//                {
//                    /router1 
//                    {
//                        router = smallest-mailbox-pool
//                        nr-of-instances = 3
//                    }
//                }
//");

            var actorSystem = ActorSystem.Create("routing-demo", config);

            var counter = new AtomicCounter();
            counter.IncrementAndGet();

            var router =
                actorSystem.ActorOf(
                    Props.Create(
                        () => new RouteeActor(() => counter.IncrementAndGet()))
                        .WithRouter(FromConfig.Instance), "router1");

            //            var router =
            //                actorSystem.ActorOf(
            //                    Props.Create<RouteeActor>(
            //                        () => new RouteeActor(() => counter.IncrementAndGet()))
            //                        .WithRouter(FromConfig.Instance), "router1");

            for (int i = 0; i < 10; i++)
            {
                router.Tell(i);
            }

            Console.ReadLine();
        }
Exemplo n.º 3
0
        public void A_restart_with_backoff_source_should_stop_on_completion_if_it_should_only_be_restarted_in_failures()
        {
            this.AssertAllStagesStopped(() =>
            {
                var created = new AtomicCounter(0);
                var probe   = RestartSource.OnFailuresWithBackoff(() =>
                {
                    created.IncrementAndGet();
                    var enumerable = new List <string> {
                        "a", "b", "c"
                    }.Select(c =>
                    {
                        switch (c)
                        {
                        case "c": return(created.Current == 1 ? throw new ArgumentException("failed") : "c");

                        default: return(c);
                        }
                    });
                    return(Source.From(enumerable));
                }, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20), 0).RunWith(this.SinkProbe <string>(), Materializer);

                probe.RequestNext("a");
                probe.RequestNext("b");
                // will fail, and will restart
                probe.RequestNext("a");
                probe.RequestNext("b");
                probe.RequestNext("c");

                created.Current.Should().Be(2);

                probe.Cancel();
            }, Materializer);
        }
Exemplo n.º 4
0
        private (AtomicCounter, TestPublisher.Probe <string>, TestSubscriber.Probe <string>, TestPublisher.Probe <string>, TestSubscriber.Probe <string>) SetupFlow(
            TimeSpan minBackoff,
            TimeSpan maxBackoff,
            int maxRestarts     = -1,
            bool onlyOnFailures = false)
        {
            var created       = new AtomicCounter(0);
            var probe1        = this.SourceProbe <string>().ToMaterialized(this.SinkProbe <string>(), Keep.Both).Run(Materializer);
            var flowInSource  = probe1.Item1;
            var flowInProbe   = probe1.Item2;
            var probe2        = this.SourceProbe <string>().ToMaterialized(BroadcastHub.Sink <string>(), Keep.Both).Run(Materializer);
            var flowOutProbe  = probe2.Item1;
            var flowOutSource = probe2.Item2;

            // We can't just use ordinary probes here because we're expecting them to get started/restarted. Instead, we
            // simply use the probes as a message bus for feeding and capturing events.
            var probe3 = this.SourceProbe <string>().ViaMaterialized(RestartFlowFactory(() =>
            {
                created.IncrementAndGet();
                var snk = Flow.Create <string>()
                          .TakeWhile(s => s != "cancel")
                          .To(Sink.ForEach <string>(c => flowInSource.SendNext(c))
                              .MapMaterializedValue(task => task.ContinueWith(
                                                        t1 =>
                {
                    if (t1.IsFaulted || t1.IsCanceled)
                    {
                        flowInSource.SendNext("in error");
                    }
                    else
                    {
                        flowInSource.SendNext("in complete");
                    }
                })));

                var src = flowOutSource.TakeWhile(s => s != "complete").Select(c =>
                {
                    if (c == "error")
                    {
                        throw new ArgumentException("failed");
                    }
                    return(c);
                }).WatchTermination((s1, task) =>
                {
                    task.ContinueWith(_ =>
                    {
                        flowInSource.SendNext("out complete");
                        return(NotUsed.Instance);
                    }, TaskContinuationOptions.OnlyOnRanToCompletion);
                    return(s1);
                });

                return(Flow.FromSinkAndSource(snk, src));
            }, onlyOnFailures, RestartSettings.Create(minBackoff, maxBackoff, 0).WithMaxRestarts(maxRestarts, minBackoff)), Keep.Left)
                         .ToMaterialized(this.SinkProbe <string>(), Keep.Both).Run(Materializer);
            var source = probe3.Item1;
            var sink   = probe3.Item2;

            return(created, source, flowInProbe, flowOutProbe, sink);
        }
Exemplo n.º 5
0
        public void A_restart_with_backoff_sink_should_not_restart_the_sink_when_maxRestarts_is_reached()
        {
            this.AssertAllStagesStopped(() =>
            {
                var created           = new AtomicCounter(0);
                var(queue, sinkProbe) = this.SourceProbe <string>().ToMaterialized(this.SinkProbe <string>(), Keep.Both).Run(Materializer);
                var probe             = this.SourceProbe <string>()
                                        .ToMaterialized(RestartSink.WithBackoff(() =>
                {
                    created.IncrementAndGet();
                    return(Flow.Create <string>().TakeWhile(c => c != "cancel", inclusive: true).To(Sink.ForEach <string>(c => queue.SendNext(c))));
                }, _shortRestartSettings.WithMaxRestarts(1, _shortMinBackoff)), Keep.Left)
                                        .Run(Materializer);

                probe.SendNext("cancel");
                sinkProbe.RequestNext("cancel");
                probe.SendNext("cancel");
                sinkProbe.RequestNext("cancel");

                probe.ExpectCancellation();

                created.Current.Should().Be(2);

                sinkProbe.Cancel();
                probe.SendComplete();
            }, Materializer);
        }
Exemplo n.º 6
0
        public void A_restart_with_backoff_source_should_allow_using_withMaxRestarts_instead_of_minBackoff_to_determine_the_maxRestarts_reset_time()
        {
            this.AssertAllStagesStopped(() =>
            {
                var created = new AtomicCounter(0);
                var probe   = RestartSource.WithBackoff(() =>
                {
                    created.IncrementAndGet();
                    return(Source.From(new List <string> {
                        "a", "b"
                    }).TakeWhile(c => c != "b"));
                }, _shortRestartSettings.WithMaxRestarts(2, TimeSpan.FromSeconds(1)))
                              .RunWith(this.SinkProbe <string>(), Materializer);

                probe.RequestNext("a");
                probe.RequestNext("a");

                Thread.Sleep(_shortMinBackoff + TimeSpan.FromTicks(_shortMinBackoff.Ticks * 2) + _shortMinBackoff); // if using shortMinBackoff as deadline cause reset

                probe.RequestNext("a");

                probe.Request(1);
                probe.ExpectComplete();

                created.Current.Should().Be(3);

                probe.Cancel();
            }, Materializer);
        }
        public BatchingSqliteJournalSpec(ITestOutputHelper output)
            : base(CreateSpecConfig($"Datasource=memdb-journal-batch-{counter.IncrementAndGet()}.db;Mode=Memory;Cache=Shared"), "BatchingSqliteJournalSpec", output)
        {
            SqlitePersistence.Get(Sys);

            Initialize();
        }
Exemplo n.º 8
0
        public static Config CreatePersistenceConfig(bool rememberEntities = false)
        {
            var connectionString =
                "Filename=file:memdb-journal-" + DbId.IncrementAndGet() + ".db;Mode=Memory;Cache=Shared";
            var config = $@"
                akka.actor.provider = cluster
                akka.remote.dot-netty.tcp.port = 0
                akka.cluster.sharding.state-store-mode=persistence
                akka.cluster.sharding.remember-entities = {BoolToToggle(rememberEntities)}
                akka.persistence.journal.plugin = ""akka.persistence.journal.sqlite""
                akka.persistence.journal.sqlite {{
                    class = ""Akka.Persistence.Sqlite.Journal.SqliteJournal, Akka.Persistence.Sqlite""
                    auto-initialize = on
                    connection-string = ""{connectionString}""
                }}
                akka.persistence.snapshot-store {{
                    plugin = ""akka.persistence.snapshot-store.sqlite""
                    sqlite {{
                        class = ""Akka.Persistence.Sqlite.Snapshot.SqliteSnapshotStore, Akka.Persistence.Sqlite""
                        auto-initialize = on
                        connection-string = ""{connectionString}""
                    }}
                }}";

            return(config);
        }
Exemplo n.º 9
0
        public void A_restart_with_backoff_source_should_reset_maxRestarts_when_source_runs_for_at_least_minimum_backoff_without_completing()
        {
            this.AssertAllStagesStopped(() =>
            {
                var created = new AtomicCounter(0);
                var probe   = RestartSource.WithBackoff(() =>
                {
                    created.IncrementAndGet();
                    return(Source.Single("a"));
                }, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), 0, maxRestarts: 2).RunWith(this.SinkProbe <string>(), Materializer);

                probe.RequestNext("a");
                // There should be minBackoff delay
                probe.RequestNext("a");
                // The probe should now be backing off again with with increased backoff

                // Now wait for the delay to pass, then it will start the new source, we also want to wait for the
                // subsequent backoff to pass
                const int minBackoff = 1000;
                Thread.Sleep((minBackoff + (minBackoff * 2) + minBackoff + 500));

                probe.RequestNext("a");
                // We now are able to trigger the third restart, since enough time has elapsed to reset the counter
                probe.RequestNext("a");

                created.Current.Should().Be(4);

                probe.Cancel();
            }, Materializer);
        }
Exemplo n.º 10
0
        public void A_restart_with_backoff_source_should_restart_on_failure()
        {
            this.AssertAllStagesStopped(() =>
            {
                var created = new AtomicCounter(0);
                var probe   = RestartSource.WithBackoff(() =>
                {
                    created.IncrementAndGet();
                    var enumerable = new List <string> {
                        "a", "b", "c"
                    }.Select(c =>
                    {
                        if (c == "c")
                        {
                            throw new ArgumentException("failed");
                        }
                        return(c);
                    });
                    return(Source.From(enumerable));
                }, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20), 0).RunWith(this.SinkProbe <string>(), Materializer);

                probe.RequestNext("a");
                probe.RequestNext("b");
                probe.RequestNext("a");
                probe.RequestNext("b");
                probe.RequestNext("a");

                created.Current.Should().Be(3);

                probe.Cancel();
            }, Materializer);
        }
            protected override bool ReceiveCommand(object message)
            {
                if (!CommonBehavior(message))
                {
                    var cmd = message as Cmd;
                    if (cmd != null)
                    {
                        Sender.Tell(cmd.Data);
                        var @event = new Evt(cmd.Data);

                        PersistAsync(@event, evt =>
                        {
                            Thread.Sleep(300);
                            Sender.Tell(evt.Data.ToString() + "-a-" + _sendMessageCounter.IncrementAndGet());
                        });

                        PersistAsync(@event, evt => Sender.Tell(evt.Data.ToString() + "-b-" + _sendMessageCounter.IncrementAndGet()));

                        return(true);
                    }
                }
                else
                {
                    return(true);
                }
                return(false);
            }
Exemplo n.º 12
0
        public void A_restart_with_backoff_sink_should_backoff_before_restart()
        {
            this.AssertAllStagesStopped(() =>
            {
                var created   = new AtomicCounter(0);
                var tuple     = this.SourceProbe <string>().ToMaterialized(this.SinkProbe <string>(), Keep.Both).Run(Materializer);
                var queue     = tuple.Item1;
                var sinkProbe = tuple.Item2;
                var probe     = this.SourceProbe <string>().ToMaterialized(RestartSink.WithBackoff(() =>
                {
                    created.IncrementAndGet();
                    return(Flow.Create <string>().TakeWhile(c => c != "cancel", inclusive: true)
                           .To(Sink.ForEach <string>(c => queue.SendNext(c))));
                }, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 0), Keep.Left).Run(Materializer);

                probe.SendNext("a");
                sinkProbe.RequestNext("a");
                probe.SendNext("cancel");
                sinkProbe.RequestNext("cancel");
                probe.SendNext("b");
                sinkProbe.Request(1);
                var deadline = TimeSpan.FromMilliseconds(100).FromNow();
                sinkProbe.ExpectNext(TimeSpan.FromMilliseconds(300), "b");
                deadline.IsOverdue.Should().BeTrue();

                created.Current.Should().Be(2);

                sinkProbe.Cancel();
                probe.SendComplete();
            }, Materializer);
        }
Exemplo n.º 13
0
        public void A_restart_with_backoff_sink_should_run_normally()
        {
            this.AssertAllStagesStopped(() =>
            {
                var created = new AtomicCounter(0);
                var tcs     = new TaskCompletionSource <IEnumerable <string> >();
                var probe   = this.SourceProbe <string>().ToMaterialized(RestartSink.WithBackoff(() =>
                {
                    created.IncrementAndGet();
                    return(Sink.Seq <string>().MapMaterializedValue(task =>
                    {
                        task.ContinueWith(c => tcs.SetResult(c.Result));
                        return Done.Instance;
                    }));
                }, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(20), 0), Keep.Left).Run(Materializer);

                probe.SendNext("a");
                probe.SendNext("b");
                probe.SendNext("c");
                probe.SendComplete();

                tcs.Task.Result.Should().ContainInOrder("a", "b", "c");
                created.Current.Should().Be(1);
            }, Materializer);
        }
Exemplo n.º 14
0
        public void A_restart_with_backoff_sink_should_not_restart_the_sink_when_completed_while_backing_off()
        {
            this.AssertAllStagesStopped(() =>
            {
                var created   = new AtomicCounter(0);
                var tuple     = this.SourceProbe <string>().ToMaterialized(this.SinkProbe <string>(), Keep.Both).Run(Materializer);
                var queue     = tuple.Item1;
                var sinkProbe = tuple.Item2;
                var probe     = this.SourceProbe <string>().ToMaterialized(RestartSink.WithBackoff(() =>
                {
                    created.IncrementAndGet();
                    return(Flow.Create <string>().TakeWhile(c => c != "cancel", inclusive: true)
                           .To(Sink.ForEach <string>(c => queue.SendNext(c))));
                }, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 0), Keep.Left).Run(Materializer);

                probe.SendNext("a");
                sinkProbe.RequestNext("a");
                probe.SendNext("cancel");
                sinkProbe.RequestNext("cancel");
                // Should be backing off now
                probe.SendComplete();

                // Wait to ensure it isn't restarted
                Thread.Sleep(300);
                created.Current.Should().Be(1);

                sinkProbe.Cancel();
            }, Materializer);
        }
Exemplo n.º 15
0
        public void A_restart_with_backoff_source_should_cancel_the_currently_running_source_when_cancelled()
        {
            this.AssertAllStagesStopped(() =>
            {
                var created = new AtomicCounter(0);
                var tcs     = new TaskCompletionSource <Done>();
                var probe   = RestartSource.WithBackoff(() =>
                {
                    created.IncrementAndGet();
                    return(Source.From(new List <string> {
                        "a", "b"
                    })
                           .WatchTermination((source, _) =>
                    {
                        tcs.SetResult(Done.Instance);
                        return source;
                    }));
                }, TimeSpan.FromMilliseconds(10), TimeSpan.FromSeconds(2), 0).RunWith(this.SinkProbe <string>(), Materializer);

                probe.RequestNext("a");
                probe.Cancel();

                tcs.Task.Result.Should().BeSameAs(Done.Instance);

                // Wait to ensure it isn't restarted
                Thread.Sleep(200);
                created.Current.Should().Be(1);
            }, Materializer);
        }
Exemplo n.º 16
0
            public Logic(ProducerStage <TKey, TValue, TPass> self) : base(self.Shape)
            {
                this.self     = self;
                this.producer = self.producerProvider();

                SetHandler(self.Out, onPull: () => TryPull(self.In));
                SetHandler(self.In, onPush: () =>
                {
                    var msg    = Grab(self.In);
                    var result = SendToProducer(msg);
                    awaitingConfirmation.IncrementAndGet();
                    Push(self.Out, result);
                },
                           onUpstreamFinish: () =>
                {
                    inputIsClosed = true;
                    completionState.SetResult(NotUsed.Instance);
                    CheckForCompletion();
                },
                           onUpstreamFailure: cause =>
                {
                    inputIsClosed = true;
                    completionState.SetException(cause);
                    CheckForCompletion();
                });
            }
Exemplo n.º 17
0
        public void A_UnfoldResourceSource_must_not_close_the_resource_twice_when_read_fails_and_then_close_fails()
        {
            var closedCounter = new AtomicCounter(0);
            var testException = new TestException("boom");

            var probe = Source.UnfoldResource <int, int>(
                () => 23, // the best resource there is
                _ => throw new TestException("failing read"),
                _ =>
            {
                closedCounter.IncrementAndGet();
                if (closedCounter.Current == 1)
                {
                    throw testException;
                }
            }
                ).RunWith(this.SinkProbe <int>(), Materializer);

            EventFilter.Exception <TestException>().Expect(1, () =>
            {
                probe.Request(1);
                probe.ExpectError().Should().Be(testException);
            });

            closedCounter.Current.Should().Be(1);
        }
Exemplo n.º 18
0
            /// <summary>
            /// Add an entry to the cache. Overrides existing entry.
            /// </summary>
            public void Add(KeyValuePair <TKey, TVal> entry)
            {
                var i = _n.IncrementAndGet();

                _elements[i & _mask] = entry;
                _lastUsed            = DateTime.UtcNow;
            }
Exemplo n.º 19
0
        internal override Routee NewRoutee(Props routeeProps, IActorContext context)
        {
            var name     = "c" + _childNameCounter.IncrementAndGet();
            var actorRef = ((ActorCell)context).AttachChild(Local.EnrichWithPoolDispatcher(routeeProps, context), false, name);

            return(new ActorRefRoutee(actorRef));
        }
Exemplo n.º 20
0
        public BatchingSqliteJournalSpec(ITestOutputHelper output)
            : base(CreateSpecConfig("FullUri=file:memdb-journal-" + counter.IncrementAndGet() + ".db?mode=memory&cache=shared;"), "BatchingSqliteJournalSpec", output)
        {
            SqlitePersistence.Get(Sys);

            Initialize();
        }
Exemplo n.º 21
0
        public SqliteJournalSpec(ITestOutputHelper output)
            : base(CreateSpecConfig("Filename=file:memdb-journal-" + counter.IncrementAndGet() + ".db;Mode=Memory;Cache=Shared"), "SqliteJournalSpec", output)
        {
            SqlitePersistence.Get(Sys);

            Initialize();
        }
Exemplo n.º 22
0
        public void A_restart_with_backoff_source_should_backoff_before_restart()
        {
            this.AssertAllStagesStopped(() =>
            {
                var created = new AtomicCounter(0);
                var probe   = RestartSource.WithBackoff(() =>
                {
                    created.IncrementAndGet();
                    return(Source.From(new List <string> {
                        "a", "b"
                    }));
                }, TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(1000), 0).RunWith(this.SinkProbe <string>(), Materializer);

                probe.RequestNext("a");
                probe.RequestNext("b");
                probe.Request(1);
                // There should be a delay of at least 200ms before we receive the element, wait for 100ms.
                var deadline = TimeSpan.FromMilliseconds(100).FromNow();
                // But the delay shouldn't be more than 300ms.
                probe.ExpectNext(TimeSpan.FromMilliseconds(300), "a");
                deadline.IsOverdue.Should().Be(true);

                created.Current.Should().Be(2);

                probe.Cancel();
            }, Materializer);
        }
Exemplo n.º 23
0
        public SqliteSnapshotStoreSpec(ITestOutputHelper output)
            : base(CreateSpecConfig("FullUri=file:memdb-snapshot-" + counter.IncrementAndGet() + ".db?mode=memory&cache=shared;"), "SqliteSnapshotStoreSpec", output)
        {
            SqlitePersistence.Get(Sys);

            Initialize();
        }
Exemplo n.º 24
0
        public void When_CancelFalse_is_called_Then_first_exception_should_not_prevent_rest_from_being_called()
        {
            var c = new Cancelable(Sys.Scheduler);
            var callbacks = new AtomicCounter(0);
            c.Token.Register(() => { throw new Exception("Something wonderful has happened."); });
            c.Token.Register(() => callbacks.IncrementAndGet());
            c.Token.Register(() => { throw new Exception("Your AKKA is alive!!!"); });
            try
            {
                //First callback should prevent the second one from being called
                c.Cancel(throwOnFirstException: false);
            }
            catch (AggregateException aggregateException)
            {
                aggregateException = aggregateException.Flatten();
                foreach (var e in aggregateException.InnerExceptions)
                {
                    if (!e.Message.StartsWith("Your") && !e.Message.StartsWith("Something"))
                        throw new Exception("Invalid exception received: " + e, e);

                }
            }
            //HACK: Using the fact that when Cancel is called, callbacks are executed synchronously
            callbacks.Current.ShouldBe(1);
            c.IsCancellationRequested.ShouldBeTrue();
            c.Token.IsCancellationRequested.ShouldBeTrue();
        }
Exemplo n.º 25
0
        protected DiResolverSpec(Config config = null, string actorSystemName = null, string testActorName = null)
            : base(new XunitAssertions(), config, actorSystemName, testActorName)
        {
            _pid = "p-" + Counter.IncrementAndGet();
// ReSharper disable once DoNotCallOverridableMethodsInConstructor
            var resolver = ConfigureDependencyResolver(Sys);
        }
Exemplo n.º 26
0
        private TestKitBase(TestKitAssertions assertions, ActorSystem system, Config config, string actorSystemName = null)
        {
            if (assertions == null)
            {
                throw new ArgumentNullException("assertions");
            }
            if (system == null)
            {
                var configWithDefaultFallback = config.SafeWithFallback(_defaultConfig);
                system = ActorSystem.Create(actorSystemName ?? "test", configWithDefaultFallback);
            }

            _assertions = assertions;
            _system     = system;
            system.RegisterExtension(new TestKitExtension());
            system.RegisterExtension(new TestKitAssertionsExtension(assertions));
            _testKitSettings = TestKitExtension.For(_system);
            _queue           = new BlockingQueue <MessageEnvelope>();
            _log             = Logging.GetLogger(system, GetType());


            var testActor = CreateTestActor(system, "testActor" + _testActorId.IncrementAndGet());

            _testActor = testActor;
            //Wait for the testactor to start
            AwaitCondition(() =>
            {
                var repRef = _testActor as RepointableRef;
                return(repRef == null || repRef.IsStarted);
            }, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(10));
        }
        public void When_CancelFalse_is_called_Then_first_exception_should_not_prevent_rest_from_being_called()
        {
            var c         = new Cancelable(Sys.Scheduler);
            var callbacks = new AtomicCounter(0);

            c.Token.Register(() => { throw new Exception("Something wonderful has happened."); });
            c.Token.Register(() => callbacks.IncrementAndGet());
            c.Token.Register(() => { throw new Exception("Your AKKA is alive!!!"); });
            try
            {
                //First callback should prevent the second one from being called
                c.Cancel(throwOnFirstException: false);
            }
            catch (AggregateException aggregateException)
            {
                aggregateException = aggregateException.Flatten();
                foreach (var e in aggregateException.InnerExceptions)
                {
                    if (!e.Message.StartsWith("Your") && !e.Message.StartsWith("Something"))
                    {
                        throw new Exception("Invalid exception received: " + e, e);
                    }
                }
            }
            //HACK: Using the fact that when Cancel is called, callbacks are executed synchronously
            callbacks.Current.ShouldBe(1);
            c.IsCancellationRequested.ShouldBeTrue();
            c.Token.IsCancellationRequested.ShouldBeTrue();
        }
 public Bug25FixSpec(ITestOutputHelper helper, DatabaseFixture fixture)
     : base(CreateSpecConfig(fixture, Counter.Current), output: helper)
 {
     _connectionString = new MongoUrl(fixture.ConnectionString + Counter.Current);
     Counter.IncrementAndGet();
     _output   = helper;
     _database = new Lazy <IMongoDatabase>(() =>
                                           new MongoClient(_connectionString)
                                           .GetDatabase(_connectionString.DatabaseName));
 }
Exemplo n.º 29
0
        /// <summary>
        /// Initializes the <see cref="TestState"/> for a new spec.
        /// </summary>
        /// <param name="system">The actor system this test will use. Can be null.</param>
        /// <param name="config">The configuration that <paramref name="system"/> will use if it's null.</param>
        /// <param name="actorSystemName">The name that <paramref name="system"/> will use if it's null.</param>
        /// <param name="testActorName">The name of the test actor. Can be null.</param>
        protected void InitializeTest(ActorSystem system, Config config, string actorSystemName, string testActorName)
        {
            _testState = new TestState();

            if (system == null)
            {
                var configWithDefaultFallback = config.SafeWithFallback(_defaultConfig);
                system = ActorSystem.Create(actorSystemName ?? "test", configWithDefaultFallback);
            }

            _testState.System = system;

            system.RegisterExtension(new TestKitExtension());
            system.RegisterExtension(new TestKitAssertionsExtension(_assertions));

            _testState.TestKitSettings    = TestKitExtension.For(_testState.System);
            _testState.Queue              = new BlockingQueue <MessageEnvelope>();
            _testState.Log                = Logging.GetLogger(system, GetType());
            _testState.EventFilterFactory = new EventFilterFactory(this);

            //register the CallingThreadDispatcherConfigurator
            _testState.System.Dispatchers.RegisterConfigurator(CallingThreadDispatcher.Id,
                                                               new CallingThreadDispatcherConfigurator(_testState.System.Settings.Config, _testState.System.Dispatchers.Prerequisites));

            if (string.IsNullOrEmpty(testActorName))
            {
                testActorName = "testActor" + _testActorId.IncrementAndGet();
            }

            var testActor = CreateTestActor(system, testActorName);

            //Wait for the testactor to start
            // Calling sync version here, since .Wait() causes deadlock
            AwaitCondition(() =>
            {
                var repRef = testActor as IRepointableRef;
                return(repRef == null || repRef.IsStarted);
            }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));

            if (!(this is INoImplicitSender))
            {
                InternalCurrentActorCellKeeper.Current = (ActorCell)((ActorRefWithCell)testActor).Underlying;
            }
            else if (!(this is TestProbe))
            //HACK: we need to clear the current context when running a No Implicit Sender test as sender from an async test may leak
            //but we should not clear the current context when creating a testprobe from a test
            {
                InternalCurrentActorCellKeeper.Current = null;
            }
            SynchronizationContext.SetSynchronizationContext(
                new ActorCellKeepingSynchronizationContext(InternalCurrentActorCellKeeper.Current));

            _testState.TestActor = testActor;
        }
        public void Setup(BenchmarkContext context)
        {
            _opsCounter  = context.GetCounter(MsgRcvCounter);
            _actorSystem = ActorSystem.Create("SpecActor" + ActorSystemId.IncrementAndGet(), Config);
            _dedup       = _actorSystem.ActorOf(Props.Create(() => new TestDeDuplicatingActor()), "deduper");

            // need to do a warm-up (ensures the actor is fully initialized before test begins)
            context.Trace.Debug("START: Warming up DeDuplicatingActor");
            _dedup.Ask <ActorIdentity>(new Identify(null)).Wait();
            context.Trace.Debug("FINISH: Warming up DeDuplicatingActor");
        }
Exemplo n.º 31
0
        public void Given_a_canceled_Cancelable_with_callback_Then_Cancel_should_be_possible_to_call_again_but_callbacks_should_not_be_called_again()
        {
            var c = new Cancelable(Sys.Scheduler);
            var callbacks = new AtomicCounter(0);
            c.Token.Register(() => callbacks.IncrementAndGet());
            c.Cancel();

            c.Cancel();

            //HACK: Using the fact that when Cancel is called, callbacks are executed synchronously
            callbacks.Current.ShouldBe(1);
        }
Exemplo n.º 32
0
        public static Config JournalConfig(string connectionString)
        {
            TableName = "TestTable" + TableVersionCounter.IncrementAndGet();

            return(ConfigurationFactory.ParseString(
                       @"akka.loglevel = DEBUG
                akka.persistence.journal.plugin = ""akka.persistence.journal.azure-table""
                akka.persistence.journal.azure-table.connection-string=""" + connectionString + @"""
                akka.persistence.journal.azure-table.verbose-logging = on
                akka.test.single-expect-default = 3s")
                   .WithFallback("akka.persistence.journal.azure-table.table-name=" + TableName));
        }
        public void Given_a_canceled_Cancelable_with_callback_Then_Cancel_should_be_possible_to_call_again_but_callbacks_should_not_be_called_again()
        {
            var c         = new Cancelable(Sys.Scheduler);
            var callbacks = new AtomicCounter(0);

            c.Token.Register(() => callbacks.IncrementAndGet());
            c.Cancel();

            c.Cancel();

            //HACK: Using the fact that when Cancel is called, callbacks are executed synchronously
            callbacks.Current.ShouldBe(1);
        }
        public void A_supervisor_hierarchy_must_handle_failure_in_creation_when_supervision_strategy_returns_Resume_and_Restart()
        {
            var createAttempt = new AtomicCounter(0);
            var preStartCalled = new AtomicCounter(0);
            var postRestartCalled = new AtomicCounter(0);

            EventFilter.Exception<Failure>()
                .And.Exception<InvalidOperationException>("OH NO!")
                .And.Error(start: "changing Recreate into Create")
                .And.Error(start: "changing Resume into Create")
                .Mute(() =>
                {
                    //Create:
                    // failresumer
                    //    |
                    // failingChild
                    //    | (sometimes)
                    // workingChild
                    var failresumer = ActorOf((resumerDsl, context) =>
                    {
                        resumerDsl.Strategy = new OneForOneStrategy(ex => ex is ActorInitializationException ? (createAttempt.Current % 2 == 0 ? Directive.Resume : Directive.Restart) : Directive.Escalate);
                        var failingChild = context.ActorOf((childDsl, childContext) =>
                        {
                            var ca = createAttempt.IncrementAndGet();
                            if (ca <= 6 && ca % 3 == 0)
                                childContext.ActorOf(BlackHoleActor.Props, "workingChild" + ca);
                            if (ca < 6)
                                throw new InvalidOperationException("OH NO!");
                            childDsl.OnPreStart = _ => preStartCalled.IncrementAndGet();
                            childDsl.OnPostRestart = (e, _) => postRestartCalled.IncrementAndGet();
                            childDsl.ReceiveAny((m, actorContext) => actorContext.Sender.Tell(m));
                        }, "failingChild");
                        resumerDsl.ReceiveAny((m, _) => failingChild.Forward(m));
                    }, "failresumer");

                    //Send failresumer some meatballs. This message will be forwarded to failingChild
                    failresumer.Tell("Köttbullar");
                    ExpectMsg("Köttbullar");
                });

            createAttempt.Current.ShouldBe(6);
            preStartCalled.Current.ShouldBe(1);
            postRestartCalled.Current.ShouldBe(0);
        }
        public void A_Flow_with_SelectAsyncUnordered_must_not_run_more_futures_than_configured()
        {
            this.AssertAllStagesStopped(() =>
            {
                const int parallelism = 8;
                var counter = new AtomicCounter();
                var queue = new BlockingQueue<Tuple<TaskCompletionSource<int>, long>>();

                var timer = new Thread(() =>
                {
                    var delay = 500; // 50000 nanoseconds
                    var count = 0;
                    var cont = true;
                    while (cont)
                    {
                        try
                        {
                            var t = queue.Take(CancellationToken.None);
                            var promise = t.Item1;
                            var enqueued = t.Item2;
                            var wakeup = enqueued + delay;
                            while (DateTime.Now.Ticks < wakeup) { }
                            counter.Decrement();
                            promise.SetResult(count);
                            count++;
                        }
                        catch
                        {
                            cont = false;
                        }
                    }
                });

                timer.Start();

                Func<Task<int>> deferred = () =>
                {
                    var promise = new TaskCompletionSource<int>();
                    if (counter.IncrementAndGet() > parallelism)
                        promise.SetException(new Exception("parallelism exceeded"));
                    else
                        queue.Enqueue(Tuple.Create(promise, DateTime.Now.Ticks));
                    return promise.Task;
                };

                try
                {
                    const int n = 10000;
                    var task = Source.From(Enumerable.Range(1, n))
                        .SelectAsyncUnordered(parallelism, _ => deferred())
                        .RunAggregate(0, (c, _) => c + 1, Materializer);

                    task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
                    task.Result.Should().Be(n);
                }
                finally
                {
                    timer.Interrupt();
                }
            }, Materializer);
        }