Exemple #1
0
        /// <summary>
        ///     Processor for user defined messages.
        /// </summary>
        /// <param name="message">The message.</param>
        protected override void OnReceive(object message)
        {
            if (message is SetRespondTo)
            {
                result = ((SetRespondTo) message).Result;
                respondTo = Sender;
            }
            else
            {
                if (respondTo != ActorRef.NoSender)
                {
                    Self.Stop();
                    respondTo.Tell(new CompleteFuture(() => result.SetResult(message)));
                    Become(_ => { });
                }
                else
                {
                    //if there is no listening actor asking,
                    //just eval the result directly
                    Self.Stop();
                    Become(_ => { });

                    result.SetResult(message);
                }
            }
        }
 public Dispatcher(ActorRef journalWriter, ActorRef executor)
 {
     _executor = executor;
     _journalWriter = journalWriter;
     Receive<Command>(command => _journalWriter.Tell(new RequestContext(command, Sender)));
     Receive<Query>(query => _executor.Tell(new RequestContext(query, Sender)));
 }
        public ClusterMetricsCollector(ActorRef publisher)
        {
            _publisher = publisher;
            _cluster = Cluster.Get(Context.System);
            Collector = MetricsCollector.Get(Context.System.AsInstanceOf<ExtendedActorSystem>(), _cluster.Settings);
            LatestGossip = MetricsGossip.Empty;
            Nodes = ImmutableHashSet.Create<Address>();

            _metricsTask = new CancellationTokenSource();
            Context.System.Scheduler.Schedule(_cluster.Settings.PeriodicTasksInitialDelay.Max(_cluster.Settings.MetricsInterval), 
                _cluster.Settings.MetricsInterval, Self, InternalClusterAction.MetricsTick.Instance, _metricsTask.Token);

            _gossipTask = new CancellationTokenSource();
            Context.System.Scheduler.Schedule(_cluster.Settings.PeriodicTasksInitialDelay.Max(_cluster.Settings.GossipInterval),
                _cluster.Settings.GossipInterval, Self, InternalClusterAction.GossipTick.Instance, _gossipTask.Token);

            Receive<InternalClusterAction.GossipTick>(tick => Gossip());
            Receive<InternalClusterAction.MetricsTick>(tick => Collect());
            Receive<MetricsGossipEnvelope>(envelope => ReceiveGossip(envelope));
            Receive<ClusterEvent.CurrentClusterState>(state => ReceiveState(state));
            Receive<ClusterEvent.MemberUp>(up => AddMember(up.Member));
            Receive<ClusterEvent.MemberRemoved>(removed => RemoveMember(removed.Member));
            Receive<ClusterEvent.MemberExited>(exited => RemoveMember(exited.Member));
            Receive<ClusterEvent.UnreachableMember>(member => RemoveMember(member.Member));
            Receive<ClusterEvent.ReachableMember>(member =>
            {
                if (member.Member.Status == MemberStatus.Up) AddMember(member.Member);
            });
            Receive<ClusterEvent.IMemberEvent>(@event => { }); //not interested in other types of member event
        }
 /// <summary>
 /// Directly inject messages into actor receive behavior. Any exceptions
 /// thrown will be available to you, while still being able to use
 /// become/unbecome.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="sender">The sender.</param>
 public void Receive(object message, ActorRef sender = null)
 {
     var cell = Cell;
     sender = sender.IsNobody() ? cell.System.DeadLetters : sender;
     var envelope = new Envelope { Message = message, Sender = sender };
     cell.UseThreadContext(() => cell.ReceiveMessageForTest(envelope));
 }
Exemple #5
0
        private void PickUpFork(ActorRef fork)
        {
            if (this.LeftFork == fork)
            {
                Console.WriteLine("{0} has {1} in his left hand", this.Self.Name(), fork.Name());
                this.OwnsLeftFork = true;
            }
            else if(this.RightFork == fork)
            {
                Console.WriteLine("{0} has {1} in his right hand", this.Self.Name(), fork.Name());
                this.OwnsRightFork = true;
            }

            if ((!this.OwnsLeftFork || !this.OwnsRightFork) && 
                (this.random.Next(1) == 1))
            {
                this.DropFork(this.LeftFork);
                this.DropFork(this.RightFork);

                this.StartWaiting();
                return;
            }

            this.StartEating();
        }
Exemple #6
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));
        }
Exemple #7
0
 public override void Send(object message, ActorRef sender)
 {
     foreach (Routee routee in  routees)
     {
         routee.Send(message, sender);
     }
 }
Exemple #8
0
 public override void Send(object message, ActorRef sender)
 {
     if (sender is LocalActorRef)
     {
         sender.AsInstanceOf<LocalActorRef>().Provider.DeadLetters.Tell(message);
     }
 }
 // ReSharper disable ConvertToLambdaExpression
 public DeadLettersEventFilterTests() : base("akka.loglevel=ERROR")
 {
     _deadActor = Sys.ActorOf(BlackHoleActor.Props, "dead-actor");
     Watch(_deadActor);
     Sys.Stop(_deadActor);
     ExpectTerminated(_deadActor);
 }
Exemple #10
0
 public FutureActorRef(TaskCompletionSource<object> result, ActorRef sender, Action unregister, ActorPath path)
 {
     _result = result;
     _sender = sender ?? ActorRef.NoSender;
     _unregister = unregister;
     Path = path;
 }
 public ClientReceiveActor(ActorRef actor, long repeat, TaskCompletionSource<bool> latch)
 {
     var received=0L;
     var sent=0L;
     Receive<Messages.Msg>(m =>
     {
         received++;
         if(sent < repeat)
         {
             actor.Tell(m);
             sent++;
         }
         else if(received >= repeat)
         {
             latch.SetResult(true);
         }
     });
     Receive<Messages.Run>(r =>
     {
         var msg = new Messages.Msg();
         for(int i = 0; i < Math.Min(1000, repeat); i++)
         {
             actor.Tell(msg);
             sent++;
         }
     });
     Receive<Messages.Started>(s => Sender.Tell(s));
 }
 public TestPersistentView(string name, ActorRef probe, TimeSpan interval, string failAt = null)
 {
     _name = name;
     _probe = probe;
     _interval = interval;
     _failAt = failAt;
 }
Exemple #13
0
 public Remoting(ExtendedActorSystem system, RemoteActorRefProvider provider)
     : base(system, provider)
 {
     log = Logging.GetLogger(system, "remoting");
     _eventPublisher = new EventPublisher(system, log, Logging.LogLevelFor(provider.RemoteSettings.RemoteLifecycleEventsLogLevel));
     _transportSupervisor = system.SystemActorOf(Props.Create<TransportSupervisor>(), "transports");
 }
Exemple #14
0
 public FutureActorRef(TaskCompletionSource<object> result, ActorRef sender, Action unregister, ActorPath path)
 {
     this.result = result;
     this.sender = sender;
     this.unregister = unregister;
     Path = path;
 }
Exemple #15
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="DaemonMsgCreate" /> class.
 /// </summary>
 /// <param name="props">The props.</param>
 /// <param name="deploy">The deploy.</param>
 /// <param name="path">The path.</param>
 /// <param name="supervisor">The supervisor.</param>
 public DaemonMsgCreate(Props props, Deploy deploy, string path, ActorRef supervisor)
 {
     Props = props;
     Deploy = deploy;
     Path = path;
     Supervisor = supervisor;
 }
        /// <summary>
        ///     Construct an <see cref="Akka.Actor.ActorSelection"/> from the given path, which is
        ///     parsed for wildcards (these are replaced by regular expressions
        ///     internally). No attempt is made to verify the existence of any part of
        ///     the supplied path, it is recommended to send a message and gather the
        ///     replies in order to resolve the matching set of actors.
        /// </summary>
        public static ActorSelection ActorSelection(string path, ActorSystem system, ActorRef lookupRoot)
        {
            var provider = ((ActorSystemImpl)system).Provider;
            if(Uri.IsWellFormedUriString(path, UriKind.Absolute))
            {
                ActorPath actorPath;
                if(!ActorPath.TryParse(path, out actorPath))
                    return new ActorSelection(provider.DeadLetters, "");

                var actorRef = provider.RootGuardianAt(actorPath.Address);
                return new ActorSelection(actorRef, actorPath.Elements);
            }
            //no path given
            if(string.IsNullOrEmpty(path))
            {
                return new ActorSelection(system.DeadLetters, "");
            }

            //absolute path
            var elements = path.Split('/');
            if(elements[0] == "")
            {
                return new ActorSelection(provider.RootGuardian, elements.Skip(1));
            }

            return new ActorSelection(lookupRoot, path);
        }
 public LifeCycleTest2Actor(ActorRef testActor, string id, AtomicCounter generationProvider)
 {
     this.testActor = testActor;
     this.id = id;
     this.generationProvider = generationProvider;
     this.CurrentGeneration = generationProvider.Next();
 }
 public LifeCycleTest2Actor(ActorRef testActor, string id, AtomicInteger generationProvider)
 {
     this.testActor = testActor;
     this.id = id;
     this.generationProvider = generationProvider;
     this.CurrentGeneration = generationProvider.GetAndIncrement();
 }
Exemple #19
0
 public Persistent(object payload, long sequenceNr = 0L, string persistenceId = null, bool isDeleted = false, ActorRef sender = null)
 {
     Payload = payload;
     SequenceNr = sequenceNr;
     IsDeleted = isDeleted;
     PersistenceId = persistenceId ?? string.Empty;
     Sender = sender;
 }
 public KillableActor(ActorRef testActor)
 {
     TestActor = testActor;
     Receive<string>(s => s == "go away", s =>
     {
         throw new ArgumentException("Goodbye then!");
     });
 }
 public void PersistentView_should_receive_live_updates_from_persistent_actor()
 {
     _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref));
     _viewProbe.ExpectMsg("replicated-a-1");
     _viewProbe.ExpectMsg("replicated-b-2");
     _pref.Tell("c");
     _viewProbe.ExpectMsg("replicated-c-3");
 }
Exemple #22
0
 public Message(InternalActorRef recipient, Address recipientAddress, SerializedMessage serializedMessage, ActorRef senderOptional = null, SeqNo seq = null)
 {
     Seq = seq;
     SenderOptional = senderOptional;
     SerializedMessage = serializedMessage;
     RecipientAddress = recipientAddress;
     Recipient = recipient;
 }
Exemple #23
0
        public void Tell(object message, ActorRef sender)
        {
            if (sender == null)
            {
                throw new ArgumentNullException("sender");
            }

            TellInternal(message, sender);
        }
Exemple #24
0
        /// <summary>
        /// Subscribes the specified subscriber.
        /// </summary>
        /// <param name="subscriber">The subscriber.</param>
        /// <param name="channel">The channel.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        /// <exception cref="System.ArgumentNullException">subscriber</exception>
        public override bool Subscribe(ActorRef subscriber, Type channel)
        {
            if (subscriber == null)
                throw new ArgumentNullException("subscriber");

            if (debug)
                Publish(new Debug(SimpleName(this), GetType(), "subscribing " + subscriber + " to channel " + channel));
            return base.Subscribe(subscriber, channel);
        }
 public void RegisterWritableEndpointUid(ActorRef writer, int uid)
 {
     var address = writableToAddress[writer];
     if (addressToWritable[address] is EndpointManager.Pass)
     {
         var pass = (EndpointManager.Pass) addressToWritable[address];
         addressToWritable[address] = new EndpointManager.Pass(pass.Endpoint, uid);
     }
 }
 protected override void PreStart()
 {
     //Fire up a TestRunCoordinator instance and subscribe to FactData messages when they arrive
     if (UseTestCoordinator)
     {
         TestCoordinatorActorRef = Context.ActorOf<TestRunCoordinator>();
         TestCoordinatorActorRef.Tell(new TestRunCoordinator.SubscribeFactCompletionMessages(Self));
     }
 }
Exemple #27
0
 public void RegisterWritableEndpointUid(ActorRef writer, int uid)
 {
     var address = writableToAddress[writer];
     addressToWritable[address].Match()
         .With<EndpointManager.Pass>(pass =>
         {
             addressToWritable[address] = new EndpointManager.Pass(pass.Endpoint, uid);
         });
 }
Exemple #28
0
 private void MainForm_Load(object sender, EventArgs e)
 {
     StockActor =
         ActorSystem
         .ActorOf(
             Props.Create(() => new DispatcherActor(DataAvailable, StatusChange))
             .WithDispatcher("akka.actor.synchronized-dispatcher") //dispatch on GUI thread
         ); //new DispatcherActor(DataAvailable, StatusChange)
 }
 public void PersistentView_should_run_updates_at_specified_interval()
 {
     _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref, TimeSpan.FromSeconds(2), null));
     _viewProbe.ExpectMsg("replicated-a-1");
     _viewProbe.ExpectMsg("replicated-b-2");
     _pref.Tell("c");
     _viewProbe.ExpectNoMsg(TimeSpan.FromSeconds(1));
     _viewProbe.ExpectMsg("replicated-c-3");
 }
 public void PersistentView_should_run_updates_on_user_request()
 {
     _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref, TimeSpan.FromSeconds(5), null));
     _viewProbe.ExpectMsg("replicated-a-1");
     _viewProbe.ExpectMsg("replicated-b-2");
     _pref.Tell("c");
     _prefProbe.ExpectMsg("c-3");
     _view.Tell(new Update(isAwait: false));
     _viewProbe.ExpectMsg("replicated-c-3");
 }
Exemple #31
0
 public CurrentState(ActorRef fsmRef, TS state)
 {
     State  = state;
     FsmRef = fsmRef;
 }
Exemple #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PostRestartException"/> class.
 /// </summary>
 /// <param name="actor">The actor whose constructor or postRestart() hook failed.</param>
 /// <param name="cause">Cause is the exception thrown by that actor within preRestart().</param>
 /// <param name="originalCause">The original causeis the exception which caused the restart in the first place.</param>
 public PostRestartException(ActorRef actor, Exception cause, Exception originalCause)
     : base(actor, "Exception post restart (" + (originalCause == null ?"null" : originalCause.GetType().ToString()) + ")", cause)
 {
     _originalCause = originalCause;
 }
Exemple #33
0
 public UnsubscribeTransitionCallBack(ActorRef actorRef)
 {
     ActorRef = actorRef;
 }
Exemple #34
0
 public Transition(ActorRef fsmRef, TS @from, TS to)
 {
     To     = to;
     From   = @from;
     FsmRef = fsmRef;
 }
Exemple #35
0
        /*
         * if (children.nonEmpty) {
         * if (restart && children.forall(_.requestRestartPermission(retriesWindow)))
         * children foreach (crs ⇒ restartChild(crs.child, cause, suspendFirst = (crs.child != child)))
         * else
         * for (c ← children) context.stop(c.child)
         * }*/

        /// <summary>
        ///     Resumes the child.
        /// </summary>
        /// <param name="child">The child.</param>
        /// <param name="exception">The exception.</param>
        protected void ResumeChild(ActorRef child, Exception exception)
        {
            child.AsInstanceOf <InternalActorRef>().Resume(exception);
        }
Exemple #36
0
 /// <summary>
 ///     Processes the failure.
 /// </summary>
 /// <param name="actorCell">The actor cell.</param>
 /// <param name="restart">if set to <c>true</c> [restart].</param>
 /// <param name="child">The child.</param>
 /// <param name="cause">The cause.</param>
 protected abstract void ProcessFailure(ActorCell actorCell, bool restart, ActorRef child, Exception cause);
Exemple #37
0
 public Get(DateTime deadline, ActorRef client = null)
     : this()
 {
     Deadline = deadline;
     Client   = client;
 }
Exemple #38
0
 /// <summary>
 ///     Handles the specified child.
 /// </summary>
 /// <param name="child">The actor that caused the evaluation to occur</param>
 /// <param name="x">The exception that caused the evaluation to occur.</param>
 /// <returns>Directive.</returns>
 public abstract Directive Handle(ActorRef child, Exception x);
Exemple #39
0
 public void Send(ActorRef actorRef, object msg)
 {
     actorRef.Tell(msg, Receiver);
 }
Exemple #40
0
 /// <summary>
 /// Make the inbox’s actor watch the <paramref name="target"/> actor such that
 /// reception of the <see cref="Terminated"/> message can then be awaited.
 /// </summary>
 public void Watch(ActorRef target)
 {
     Receiver.Tell(new StartWatch(target));
 }
Exemple #41
0
 public IQuery WithClient(ActorRef client)
 {
     return(new Get(Deadline, client));
 }
Exemple #42
0
 public IQuery WithClient(ActorRef client)
 {
     return(new Select());
 }
Exemple #43
0
 public StartWatch(ActorRef target)
     : this()
 {
     Target = target;
 }
Exemple #44
0
 public DeathPactException(ActorRef deadActor)
     : base("Monitored actor [" + deadActor + "] terminated")
 {
     _deadActor = deadActor;
 }
Exemple #45
0
 public ActorInitializationException(ActorRef actor, string message, Exception cause = null) : base(message, cause)
 {
     _actor = actor;
 }