public LifeCycleTest2Actor(IActorRef testActor, string id, AtomicCounter generationProvider) { this.testActor = testActor; this.id = id; this.generationProvider = generationProvider; this.CurrentGeneration = generationProvider.Next(); }
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 ListenerActor(TestLatch fooLatch, TestLatch barLatch, AtomicCounter barCount) { _fooLatch = fooLatch; _barLatch = barLatch; _barCount = barCount; Listeners = new ListenerSupport(); }
public void Listener_must_listen_in() { //arrange var fooLatch = new TestLatch(2); var barLatch = new TestLatch(2); var barCount = new AtomicCounter(0); var broadcast = Sys.ActorOf<BroadcastActor>(); var newListenerProps = Props.Create(() => new ListenerActor(fooLatch, barLatch, barCount)); var a1 = Sys.ActorOf(newListenerProps); var a2 = Sys.ActorOf(newListenerProps); var a3 = Sys.ActorOf(newListenerProps); //act broadcast.Tell(new Listen(a1)); broadcast.Tell(new Listen(a2)); broadcast.Tell(new Listen(a3)); broadcast.Tell(new Deafen(a3)); broadcast.Tell(new WithListeners(a => a.Tell("foo"))); broadcast.Tell("foo"); //assert barLatch.Ready(TestLatch.DefaultTimeout); Assert.Equal(2, barCount.Current); fooLatch.Ready(TestLatch.DefaultTimeout); foreach (var actor in new[] {a1, a2, a3, broadcast}) { Sys.Stop(actor); } }
static ActorSystem LaunchFrontend(string port) { Console.WriteLine("Start - actorsystem for frontend node - port: {0}", port); var config = ConfigurationFactory.ParseString("akka.remote.helios.tcp.port=" + port) .WithFallback(ConfigurationFactory.ParseString("akka.cluster.roles = [frontend]")) .WithFallback(_clusterConfig); var system = ActorSystem.Create("ClusterSystem", config); var frontend = system.ActorOf(Props.Create<FrontendActor>(port), "frontend"); var interval = TimeSpan.FromSeconds(2); var timeout = TimeSpan.FromSeconds(5); var counter = new AtomicCounter(); system.Scheduler.Advanced.ScheduleRepeatedly(interval, interval, () => frontend.Ask(new Messages.Request("request-" + counter.GetAndIncrement() + " from frontend node port " + port), timeout) .ContinueWith( r => { if (!r.IsCanceled) { Console.WriteLine(r.Result); // Debug.WriteLine(r.Result); } })); Console.WriteLine("End - actorsystem for frontend node - port: {0}", port); return system; }
public RoundRobinPoolActor(TestLatch doneLatch, AtomicCounter counter) { _doneLatch = doneLatch; _counter = counter; Receive<string>(s => s == "hit", c => Sender.Tell(id.Value)); Receive<string>(s => s == "end", c => _doneLatch.CountDown()); }
public BroadcastTarget(TestLatch doneLatch, AtomicCounter counter) { _doneLatch = doneLatch; _counter = counter; Receive<string>(s => s == "end", c => _doneLatch.CountDown()); Receive<int>(msg => _counter.AddAndGet(msg)); }
public BackendLoadBalancingOptions(LoadBalancingMode mode) { Mode = mode; // Increment returns the new value and we want the first return value to be 0. RoundRobinState = new AtomicCounter() { Value = -1 }; }
public void InitPool(int size) { m_type = MsgType.Pool; m_flags = MsgFlags.None; m_data = BufferPool.Take(size); m_size = size; m_atomicCounter = new AtomicCounter(); }
/// <summary> /// Initialise this Msg to be of MsgType.GC with the given data-buffer value. /// </summary> /// <param name="data">the byte-array of data to assign to the Msg's Data property</param> /// <param name="offset">first byte in the data array</param> /// <param name="size">the number of bytes that are in the data byte-array</param> public void InitGC([NotNull] byte[] data, int offset, int size) { MsgType = MsgType.GC; Flags = MsgFlags.None; Data = data; Size = size; Offset = offset; m_refCount = null; }
/// <summary> /// Clear this Msg to empty - ie, set MsgFlags to None, MsgType to Empty, and clear the Data. /// </summary> public void InitEmpty() { MsgType = MsgType.Empty; Flags = MsgFlags.None; Size = 0; Offset = 0; Data = null; m_refCount = null; }
/// <summary> /// Initialise this Msg to be of MsgType.Pool, with a data-buffer of the given number of bytes. /// </summary> /// <param name="size">the number of bytes to allocate in the data-buffer</param> public void InitPool(int size) { MsgType = MsgType.Pool; Flags = MsgFlags.None; Data = BufferPool.Take(size); Size = size; Offset = 0; m_refCount = new AtomicCounter(); }
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(); }
// // Flow // private Tuple <AtomicCounter, TestPublisher.Probe <string>, TestSubscriber.Probe <string>, TestPublisher.Probe <string>, TestSubscriber.Probe <string> > SetupFlow(TimeSpan minBackoff, TimeSpan maxBackoff) { 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(RestartFlow.WithBackoff(() => { 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)); }, minBackoff, maxBackoff, 0), Keep.Left) .ToMaterialized(this.SinkProbe <string>(), Keep.Both).Run(Materializer); var source = probe3.Item1; var sink = probe3.Item2; return(Tuple.Create(created, source, flowInProbe, flowOutProbe, sink)); }
public void BTActor_EmptyParallelOk() { var counter = new AtomicCounter(0); var latch = new TestLatch(); var bt = Sys.ActorOf(Props.Create(() => new EmptyParallelOk(counter, latch))); latch.Ready(); Assert.Equal(0, counter.Current); }
public void BTActor_ReceiveAny_While() { AtomicCounter counter = new AtomicCounter(5); var bt = Sys.ActorOf(Props.Create(() => new WhileCountdown(counter))); bt.Tell("RUN", TestActor); Enumerable.Range(1, 5).Reverse().ForEach(i => ExpectMsg(i)); }
internal static void TestCorrectness() { Console.WriteLine(GlobalAtomicCounter.next()); Console.WriteLine(GlobalAtomicCounter.next()); AtomicCounter ac = new AtomicCounter(); Console.WriteLine(ac.next()); Console.WriteLine(ac.next()); }
public void ParallelTest() { var counter = new AtomicCounter(); Parallel.For(0, 50, i => { counter.Increment(); }); Assert.Equal(50, counter.Value); }
/// <summary> /// Initialise this Msg to be of MsgType.Pool, with a data-buffer of the given number of bytes. /// </summary> /// <param name="size">the number of bytes to allocate in the data-buffer</param> public void InitPool(int size) { MsgType = MsgType.Pool; Flags = MsgFlags.None; m_data = BufferPool.Take(size); Size = size; m_offset = 0; EnsureAtomicCounterNull(); m_refCount = AtomicCounterPool.Take(); }
public void BTActor_Success_After_Failure_Fails() { TestLatch latch = new TestLatch(); AtomicCounter counter = new AtomicCounter(0); var bt = Sys.ActorOf(Props.Create(() => new SuccessAfterFailure(latch, counter))); latch.Ready(); Assert.Equal(2, counter.Current); }
public void BTActor_SequenceParallelExecute() { var counter = new AtomicCounter(0); var latch = new TestLatch(); var bt = Sys.ActorOf(Props.Create(() => new SequenceParallelExecute(counter, latch))); latch.Ready(); Assert.Equal(5, counter.Current); }
public void BTActor_ExecuteIncrement() { var counter = new AtomicCounter(0); var latch = new TestLatch(); var bt = Sys.ActorOf(Props.Create(() => new ExecuteIncrement(counter, latch))); latch.Ready(); Assert.Equal(1, counter.Current); }
public static StreamBlockProxy Create(BlockKey key, ReaderBlockCache cache) { var instance = _pool.Allocate(); ThrowHelper.AssertFailFast(AtomicCounter.GetIsDisposed(ref instance._rc), "Pooled proxy must be in disposed state."); instance._key = key; instance._cache = cache; // cache owns one ref instance._rc = 1; return(instance); }
private void FindHeartbeatCounter(CountersReader counters) { var heartbeatCounterId = ServiceHeartbeat.FindCounterId(counters, ctx.ServiceId()); if (CountersReader.NULL_COUNTER_ID == heartbeatCounterId) { throw new InvalidOperationException("failed to find heartbeat counter"); } heartbeatCounter = new AtomicCounter(counters.ValuesBuffer, heartbeatCounterId); }
public FailAfterSuccess(TestLatch latch, AtomicCounter counter) { StartWith( AllSucceed( AnySucceed( After( Execute(_ => counter.GetAndIncrement()), Fail()), Execute(_ => counter.GetAndIncrement())), Execute(_ => latch.CountDown())), null); }
public void An_actor_with_receive_timeout_must_be_able_to_turn_off_timeout_if_desired() { var count = new AtomicCounter(0); var timeoutLatch = new TestLatch(); var timeoutActor = Sys.ActorOf(Props.Create(() => new TurnOffTimeoutActor(timeoutLatch, count))); timeoutActor.Tell(new Tick()); timeoutLatch.Ready(TestKitSettings.DefaultTimeout); count.Current.ShouldBe(1); Sys.Stop(timeoutActor); }
public void TestProbe_restart_a_failing_child_if_the_given_supervisor_says_so() { var restarts = new AtomicCounter(0); var probe = CreateTestProbe(); var child = probe.ChildActorOf(Props.Create(() => new FailingActor(restarts)), SupervisorStrategy.DefaultStrategy); AwaitAssert(() => { child.Tell("hello"); restarts.Current.ShouldBeGreaterThan(1); }); }
public void Should_use_multiple_threads_to_process_queue() { var atomicCounter = new AtomicCounter(0); var fiber = FiberFactory.CreateFiber(2); for (var i = 0; i < 1000; i++) { fiber.Add(() => atomicCounter.GetAndIncrement()); } fiber.GracefulShutdown(TimeSpan.FromSeconds(1)).Wait(); //wait for the fiber to finish Assert.AreEqual(1000, atomicCounter.Current); }
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 async Task Supervisor_should_handle_multiple_child_failure() { var counter = new AtomicCounter(0); var supervisor = Sys.ActorOf(Props.Create <ParentActor>(counter), "supervisor"); supervisor.Tell("spam-fails"); supervisor.Tell("run-test"); await Task.Delay(1000); counter.Current.Should().Be(0); }
/// <summary> /// Create an agent and initialise it. /// </summary> /// <param name="errorHandler"> to be called if an <seealso cref="Exception"/> is encountered </param> /// <param name="errorCounter"> to be incremented each time an exception is encountered. This may be null. </param> /// <param name="agent"> to be run in this thread. </param> public AgentInvoker( ErrorHandler errorHandler, AtomicCounter errorCounter, IAgent agent ) { Objects.RequireNonNull(errorHandler, "errorHandler"); Objects.RequireNonNull(agent, "agent"); _errorHandler = errorHandler; _errorCounter = errorCounter; _agent = agent; }
public void Decrement_ThreadSafety() { const int Iterations = 100_000; var counter = new AtomicCounter(); Parallel.For(0, Iterations, i => { counter.Decrement(); }); Assert.Equal(-Iterations, counter.Value); }
public SuccessAfterFailure(TestLatch latch, AtomicCounter counter) { StartWith( AllSucceed( AllComplete( After( AllSucceed( Execute(_ => counter.GetAndIncrement()), Fail()), Not(Fail())), Execute(_ => counter.GetAndIncrement())), Execute(_ => latch.CountDown())), null); }
/// <summary> /// Resets all frame statistics. Run exactly once per frame. /// </summary> public void NewFrame() { if (currentFrame != null) { currentFrame.Postprocess(); PendingFrames.Enqueue(currentFrame); if (PendingFrames.Count >= max_pending_frames) { FrameStatistics oldFrame; PendingFrames.TryDequeue(out oldFrame); FramesHeap.FreeObject(oldFrame); } } currentFrame = FramesHeap.ReserveObject(); currentFrame.Clear(); if (HandleGC) { for (int i = 0; i < lastAmountGarbageCollects.Length; ++i) { int amountCollections = GC.CollectionCount(i); if (lastAmountGarbageCollects[i] != amountCollections) { lastAmountGarbageCollects[i] = amountCollections; currentFrame.GarbageCollections.Add(i); } } } for (int i = 0; i < (int)StatisticsCounterType.AmountTypes; ++i) { AtomicCounter counter = Counters[i]; if (counter != null) { currentFrame.Counts[(StatisticsCounterType)i] = counter.Reset(); } } //check for dropped (stutter) frames if (Clock.ElapsedFrameTime > spike_time) { newDroppedFrame(); } //reset frame totals currentCollectionTypeStack.Clear(); //backgroundMonitorStackTrace = null; consumeStopwatchElapsedTime(); }
public LeastUsedPicker(IReadOnlyList <Subchannel> subchannels) { // Ensure all subchannels have an associated counter. foreach (var subchannel in subchannels) { if (!subchannel.Attributes.TryGetValue(CounterKey, out _)) { var counter = new AtomicCounter(); subchannel.Attributes.Set(CounterKey, counter); } } _subchannels = subchannels.ToList(); }
public void A_UnfoldResourceSource_must_not_close_the_resource_twice_when_read_fails() { var closedCounter = new AtomicCounter(0); var testException = new TestException("failing read"); var probe = Source.UnfoldResource <int, int>( () => 23, // the best resource there is _ => throw testException, _ => closedCounter.IncrementAndGet() ).RunWith(this.SinkProbe <int>(), Materializer); probe.Request(1); probe.ExpectError().Should().Be(testException); closedCounter.Current.Should().Be(1); }
public void Actor_lifecycle_test3() { var generationProvider = new AtomicCounter(); string id = Guid.NewGuid().ToString(); var supervisor = Sys.ActorOf(Props.Create(() => new Supervisor(new OneForOneStrategy(3, TimeSpan.FromSeconds(1000), x => Directive.Restart)))); var restarterProps = Props.Create(() => new LifeCycleTest2Actor(TestActor, id, generationProvider)); var restarter = supervisor.Ask <IInternalActorRef>(restarterProps).Result; ExpectMsg(Tuple.Create("preStart", id, 0)); restarter.Tell("status"); ExpectMsg(Tuple.Create("OK", id, 0)); restarter.Stop(); ExpectMsg(Tuple.Create("postStop", id, 0)); ExpectNoMsg(TimeSpan.FromSeconds(1)); }
public SimpleBroadcastActor(AtomicCounter counter) { _counter = counter; Receive <int>(i => i == 1, c => { lock (_lock) Counter++; throw new InvalidOperationException($"I'm dead. #{Counter}"); }); Receive <int>(i => i == 2, c => { _counter.AddAndGet(1); Sender.Tell(2); }); }
public void BroadcastGroup_router_must_broadcast_message_using_Ask() { var doneLatch = new TestLatch(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); }
static void LaunchFrontend(string[] args) { var port = args.Length > 0 ? args[0] : "0"; var config = ConfigurationFactory.ParseString("akka.remote.helios.tcp.port=" + port) .WithFallback(ConfigurationFactory.ParseString("akka.cluster.roles = [frontend]")) .WithFallback(_clusterConfig); var system = ActorSystem.Create("ClusterSystem", config); var backendRouter = system.ActorOf( Props.Empty.WithRouter(new ClusterRouterGroup(new ConsistentHashingGroup("/user/backend"), new ClusterRouterGroupSettings(10, false, "backend", ImmutableHashSet.Create("/user/backend"))))); var frontend = system.ActorOf(Props.Create(() => new FrontendActor(backendRouter)), "frontend"); var interval = TimeSpan.FromSeconds(12); var counter = new AtomicCounter(); system.Scheduler.Advanced.ScheduleRepeatedly(interval, interval,() => frontend.Tell(new StartCommand("hello-" + counter.GetAndIncrement()))); }
static void LaunchFrontend(string[] args) { var port = args.Length > 0 ? args[0] : "0"; var config = ConfigurationFactory.ParseString("akka.remote.helios.tcp.port=" + port) .WithFallback(ConfigurationFactory.ParseString("akka.cluster.roles = [frontend]")) .WithFallback(_clusterConfig); var system = ActorSystem.Create("ClusterSystem", config); var frontend = system.ActorOf(Props.Create<TransformationFrontend>(), "frontend"); var interval = TimeSpan.FromSeconds(2); var timeout = TimeSpan.FromSeconds(5); var counter = new AtomicCounter(); system.Scheduler.Advanced.ScheduleRepeatedly(interval, interval, () => frontend.Ask(new TransformationMessages.TransformationJob("hello-" + counter.GetAndIncrement()), timeout) .ContinueWith( r => Console.WriteLine(r.Result))); }
public void BroadcastGroup_router_must_broadcast_message_using_Ask() { var doneLatch = new TestLatch(2); var counter1 = new AtomicCounter(0); var actor1 = Sys.ActorOf(Props.Create(() => new BroadcastTarget(doneLatch, counter1))); var counter2 = new AtomicCounter(0); var actor2 = Sys.ActorOf(Props.Create(() => new BroadcastTarget(doneLatch, counter2))); var paths = new List<string> { actor1.Path.ToString(), actor2.Path.ToString() }; var routedActor = Sys.ActorOf(new BroadcastGroup(paths).Props()); routedActor.Ask(new Broadcast(1)); routedActor.Tell(new Broadcast("end")); doneLatch.Ready(RemainingOrDefault); counter1.Current.Should().Be(1); counter2.Current.Should().Be(1); }
public void Tail_chopping_group_router_must_deliver_a_broadcast_message_using_tell() { var doneLatch = new TestLatch(2); var counter1 = new AtomicCounter(0); var actor1 = Sys.ActorOf(Props.Create(() => new BroadcastTarget(doneLatch, counter1))); var counter2 = new AtomicCounter(0); var actor2 = Sys.ActorOf(Props.Create(() => new BroadcastTarget(doneLatch, counter2))); var paths = new List<string> { actor1.Path.ToString(), actor2.Path.ToString() }; var routedActor = Sys.ActorOf(new TailChoppingGroup(paths, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(100)).Props()); routedActor.Tell(new Broadcast(1)); routedActor.Tell(new Broadcast("end")); doneLatch.Ready(TestKitSettings.DefaultTimeout); counter1.Current.Should().Be(1); counter2.Current.Should().Be(1); }
public void ShouldIncrementByDefaultStep() { var counter = new AtomicCounter(1); int actual = counter.Next(); Assert.AreEqual(2, actual); }
public void Tail_chopping_router_must_deliver_a_broadcast_message_using_tell() { var doneLatch = new TestLatch(2); var counter1 = new AtomicCounter(0); var counter2 = new AtomicCounter(0); var actor1 = Sys.ActorOf(Props.Create(() => new BroadcastTarget(doneLatch, counter1)), "Actor1"); var actor2 = Sys.ActorOf(Props.Create(() => new BroadcastTarget(doneLatch, counter2)), "Actor2"); var routedActor = Sys.ActorOf(Props.Create<TestActor>() .WithRouter(new TailChoppingGroup(new[] { actor1.Path.ToString(), actor2.Path.ToString() }, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(100)) )); routedActor.Tell(new Broadcast(1)); routedActor.Tell(new Broadcast("end")); doneLatch.Ready(TimeSpan.FromSeconds(1)); counter1.Current.ShouldBe(1); counter2.Current.ShouldBe(1); }
public void ShouldIncrementBySpecifiedStep() { var counter = new AtomicCounter(1, 100); int actual = counter.Next(); Assert.AreEqual(101, actual); }
public void ActorLifecycleTest3() { var generationProvider = new AtomicCounter(); string id = Guid.NewGuid().ToString(); var supervisor = Sys.ActorOf(Props.Create(() => new Supervisor(new OneForOneStrategy(3, TimeSpan.FromSeconds(1000), x => Directive.Restart)))); var restarterProps = Props.Create(() => new LifeCycleTest2Actor(TestActor, id, generationProvider)); var restarter = supervisor.Ask<IInternalActorRef>(restarterProps).Result; ExpectMsg(Tuple.Create("preStart", id, 0)); restarter.Tell("status"); ExpectMsg(Tuple.Create("OK", id, 0)); restarter.Stop(); ExpectMsg(Tuple.Create("postStop", id, 0)); ExpectNoMsg(TimeSpan.FromSeconds(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); }
public TurnOffTimeoutActor(TestLatch timeoutLatch, AtomicCounter counter) { _timeoutLatch = timeoutLatch; _counter = counter; Context.SetReceiveTimeout(TimeSpan.FromMilliseconds(500)); }
public BroadcastTarget(TestLatch latch, AtomicCounter counter) { _latch = latch; _counter = counter; }
public async Task Round_robin_pool_must_deliver_messages_in_a_round_robin_fashion() { const int connectionCount = 10; const int iterationCount = 10; var doneLatch = new TestLatch(connectionCount); var counter = new AtomicCounter(0); var replies = new Dictionary<int, int>(); for (int i = 0; i < connectionCount; i++) { replies[i] = 0; } var actor = Sys.ActorOf(new RoundRobinPool(connectionCount) .Props(Props.Create(() => new RoundRobinPoolActor(doneLatch, counter))), "round-robin"); for (int i = 0; i < iterationCount; i++) { for (int k = 0; k < connectionCount; k++) { int id = await actor.Ask<int>("hit"); replies[id] = replies[id] + 1; } } counter.Current.Should().Be(connectionCount); actor.Tell(new Broadcast("end")); doneLatch.Ready(5.Seconds()); replies.Values.ForEach(c => c.Should().Be(iterationCount)); }