Ejemplo n.º 1
0
            public void Schedule(ActorRef actor, TimeSpan timeout)
            {
                var name    = Name;
                var message = Message;

                Action send;

                if (_debugLog != null)
                {
                    send = () =>
                    {
                        _debugLog.Debug("{3}Timer '{0}' went off. Sending {1} -> {2}", name, message, actor,
                                        _ref.IsCancellationRequested ? "Cancelled " : "");
                        actor.Tell(this, Context.Self);
                    }
                }
                ;
                else
                {
                    send = () => actor.Tell(this, Context.Self);
                }

                if (Repeat)
                {
                    _scheduler.Schedule(timeout, timeout, send, _ref.Token);
                }
                else
                {
                    _scheduler.ScheduleOnce(timeout, send, _ref.Token);
                }
            }
Ejemplo n.º 2
0
 /// <summary>
 ///     Delivers the specified message.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="pathIndex">Index of the path.</param>
 /// <param name="current">The current.</param>
 private void Deliver(object message, ActorRef sender, int pathIndex, ActorRef current)
 {
     if (pathIndex == Elements.Length)
     {
         current.Tell(message, sender);
     }
     else
     {
         SelectionPathElement element = Elements[pathIndex];
         if (current is ActorRefWithCell)
         {
             var withCell = (ActorRefWithCell)current;
             if (element is SelectParent)
             {
                 Deliver(message, sender, pathIndex + 1, withCell.Parent);
             }
             else if (element is SelectChildName)
             {
                 Deliver(message, sender, pathIndex + 1,
                         withCell.GetSingleChild(element.AsInstanceOf <SelectChildName>().Name));
             }
         }
         else
         {
             SelectionPathElement[] rest = Elements.Skip(pathIndex).ToArray();
             current.Tell(new ActorSelectionMessage(message, rest), sender);
         }
     }
 }
Ejemplo n.º 3
0
 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));
 }
Ejemplo n.º 4
0
        public PersistentViewSpec()
            : base(Configuration("inmem", "PersistentViewSpec"))
        {
            _prefProbe = CreateTestProbe();
            _viewProbe = CreateTestProbe();

            _pref = ActorOf(() => new TestPersistentActor(Name, _prefProbe.Ref));
            _pref.Tell("a");
            _pref.Tell("b");

            _prefProbe.ExpectMsg("a-1");
            _prefProbe.ExpectMsg("b-2");
        }
Ejemplo n.º 5
0
 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)));
 }
 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));
     }
 }
Ejemplo n.º 7
0
 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");
 }
Ejemplo n.º 8
0
        protected virtual bool SpecialHandle(object message, ActorRef sender)
        {
            var w = message as Watch;

            if (w != null)
            {
                if (w.Watchee == this && w.Watcher != this)
                {
                    w.Watcher.Tell(new DeathWatchNotification(w.Watchee, existenceConfirmed: false, addressTerminated: false));
                }
                return(true);
            }
            if (message is Unwatch)
            {
                return(true);    //Just ignore
            }
            var identify = message as Identify;

            if (identify != null)
            {
                sender.Tell(new ActorIdentity(identify.MessageId, null));
                return(true);
            }
            var sel = message as ActorSelectionMessage;

            if (sel != null)
            {
                var selectionIdentify = sel.Message as Identify;
                if (selectionIdentify != null)
                {
                    if (!sel.WildCardFanOut)
                    {
                        sender.Tell(new ActorIdentity(selectionIdentify.MessageId, null));
                    }
                }
                else
                {
                    _eventStream.Publish(new DeadLetter(sel.Message, sender.IsNobody() ? _provider.DeadLetters : sender, this));
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 9
0
        public AkkaJournaler(ActorRef executor, int batchSize, IJournalWriter journalWriter)
        {
            _journalWriter = journalWriter;
            BatchSize = batchSize;
            _executor = executor;
            Receive<RequestContext>(t => Accept(t));
            Receive<ReceiveTimeout>(_ => Go());
            Receive<JournalAcknowledgement>(_ => _executor.Tell(_waitingForJournalAck.Dequeue()));

            SetReceiveTimeout(Interval);
        }
Ejemplo n.º 10
0
        public override void Post(Envelope envelope)
        {
            var message = envelope.Message;

            if (message is SystemMessage)
            {
                Mailbox.DebugPrint("DeadLetterMailbox forwarded system message " + envelope + " as a DeadLetter");
                _deadLetters.Tell(new DeadLetter(message, _deadLetters, _deadLetters), _deadLetters);//TODO: When we have refactored Post to SystemEnqueue(ActorRef receiver, Envelope envelope), replace _deadLetters with receiver
            }
            else if (message is DeadLetter)
            {
                //Just drop it like it's hot
                Mailbox.DebugPrint("DeadLetterMailbox dropped DeadLetter " + envelope);
            }
            else
            {
                Mailbox.DebugPrint("DeadLetterMailbox forwarded message " + envelope + " as a DeadLetter");
                var sender = envelope.Sender;
                _deadLetters.Tell(new DeadLetter(message, sender, _deadLetters), sender);//TODO: When we have refactored Post to Enqueue(ActorRef receiver, Envelope envelope), replace _deadLetters with receiver
            }
        }
Ejemplo n.º 11
0
 protected override void TellInternal(object message, ActorRef sender)
 {
     unregister();
     if (sender != NoSender)
     {
         sender.Tell(new CompleteFuture(() => result.TrySetResult(message)));
     }
     else
     {
         result.TrySetResult(message);
     }
 }
Ejemplo n.º 12
0
        public override void Post(ActorRef receiver, Envelope envelope)
        {
            var message = envelope.Message;

            if (message is SystemMessage)
            {
                Mailbox.DebugPrint("DeadLetterMailbox forwarded system message " + envelope + " as a DeadLetter");
                _deadLetters.Tell(new DeadLetter(message, receiver, receiver), receiver);
            }
            else if (message is DeadLetter)
            {
                //Just drop it like it's hot
                Mailbox.DebugPrint("DeadLetterMailbox dropped DeadLetter " + envelope);
            }
            else
            {
                Mailbox.DebugPrint("DeadLetterMailbox forwarded message " + envelope + " as a DeadLetter");
                var sender = envelope.Sender;
                _deadLetters.Tell(new DeadLetter(message, sender, receiver), sender);
            }
        }
        public ClusterDomainEventPublisherSpec()
        {
            _memberSubscriber = CreateTestProbe();
            Sys.EventStream.Subscribe(_memberSubscriber.Ref, typeof(ClusterEvent.IMemberEvent));
            Sys.EventStream.Subscribe(_memberSubscriber.Ref, typeof(ClusterEvent.LeaderChanged));

            _publisher = Sys.ActorOf(Props.Create<ClusterDomainEventPublisher>());
            //TODO: If parent told of exception then test should fail (if not expected in some way)?
            _publisher.Tell(new InternalClusterAction.PublishChanges(g0));
            _memberSubscriber.ExpectMsg(new ClusterEvent.MemberUp(aUp));
            _memberSubscriber.ExpectMsg(new ClusterEvent.LeaderChanged(aUp.Address));
        }
Ejemplo n.º 14
0
 /// <summary>
 ///     Delivers the specified message.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="pathIndex">Index of the path.</param>
 /// <param name="current">The current.</param>
 private void Deliver(object message, ActorRef sender, int pathIndex, ActorRef current)
 {
     if (pathIndex == Elements.Length)
     {
         current.Tell(message, sender);
     }
     else
     {
         var element = Elements[pathIndex];
         if (current is ActorRefWithCell)
         {
             var withCell = (ActorRefWithCell)current;
             if (element is SelectParent)
             {
                 Deliver(message, sender, pathIndex + 1, withCell.Parent);
             }
             else if (element is SelectChildName)
             {
                 Deliver(message, sender, pathIndex + 1,
                         withCell.GetSingleChild(element.AsInstanceOf <SelectChildName>().Name));
             }
             else if (element is SelectChildPattern)
             {
                 var pattern  = element as SelectChildPattern;
                 var children =
                     withCell.Children.Where(c => c.Path.Name.Like(pattern.PatternStr));
                 foreach (ActorRef matchingChild in children)
                 {
                     Deliver(message, sender, pathIndex + 1, matchingChild);
                 }
             }
         }
         else
         {
             var rest = Elements.Skip(pathIndex).ToArray();
             current.Tell(new ActorSelectionMessage(message, rest), sender);
         }
     }
 }
 protected override void Print(LogEvent m)
 {           
     if(m.Message is ForwardAllEventsTo)
     {
         _forwarder = ((ForwardAllEventsTo)m.Message).Forwarder;
         _forwarder.Tell("OK");
     }
     else if(_forwarder != null)
     {
         _forwarder.Forward(m);
     }
     else
     {
         base.Print(m);
     }
 }
Ejemplo n.º 16
0
        public static Task <bool> GracefulStop(this ActorRef target, TimeSpan timeout, object stopMessage)
        {
            var internalTarget = target.AsInstanceOf <InternalActorRef>();

            if (internalTarget.IsTerminated)
            {
                return(Task.Run(() => true));
            }

            var provider = Futures.ResolveProvider(target);
            var promise  = new TaskCompletionSource <object>();

            //set up the timeout
            var cancellationSource = new CancellationTokenSource();

            cancellationSource.Token.Register(() => promise.TrySetCanceled());
            cancellationSource.CancelAfter(timeout);

            //create a new tempcontainer path
            var path = provider.TempPath();
            //callback to unregister from tempcontainer
            Action unregister = () => provider.UnregisterTempActor(path);

            var fref = new FutureActorRef(promise, ActorRef.NoSender, unregister, path);

            internalTarget.Tell(new Watch(internalTarget, fref));
            target.Tell(stopMessage, ActorRef.NoSender);
            return(promise.Task.ContinueWith(t =>
            {
                var returnResult = false;
                PatternMatch.Match(t.Result)
                .With <Terminated>(terminated =>
                {
                    returnResult = (terminated.ActorRef.Path.Equals(target.Path));
                })
                .Default(m =>
                {
                    returnResult = false;
                });

                internalTarget.Tell(new Unwatch(target, fref));
                return returnResult;
            }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.AttachedToParent));
        }
Ejemplo n.º 17
0
 /// <summary>
 ///     Tells the internal.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="sender">The sender.</param>
 protected override void TellInternal(object message, ActorRef sender)
 {
     message
     .Match()
     .With <Identify>(m => sender.Tell(new ActorIdentity(m.MessageId, this)))
     .With <DeadLetter>(m =>
     {
         if (!SpecialHandle(m.Message, m.Sender))
         {
             eventStream.Publish(m);
         }
     })
     .Default(m =>
     {
         if (!SpecialHandle(message, sender))
         {
             eventStream.Publish(new DeadLetter(message, sender == NoSender ? provider.DeadLetters : sender,
                                                this));
         }
     });
 }
Ejemplo n.º 18
0
 protected override void TellInternal(object message, ActorRef sender)
 {
     if (message is SystemMessage) //we have special handling for system messages
     {
         SendSystemMessage(message.AsInstanceOf <SystemMessage>(), sender);
     }
     else
     {
         if (Interlocked.Exchange(ref status, COMPLETED) == INITIATED)
         {
             _unregister();
             if (_sender == NoSender || message is Terminated)
             {
                 _result.TrySetResult(message);
             }
             else
             {
                 _sender.Tell(new CompleteFuture(() => _result.TrySetResult(message)));
             }
         }
     }
 }
Ejemplo n.º 19
0
 protected override bool ReceiveMessage(object message)
 {
     var strMessage = message as string;
     switch(strMessage)
     {
         case "complexRequest":
             _replyTo = Sender;
             var worker = TestActorRef.Create<WorkerActor>(System);
             worker.Tell("work");
             return true;
         case "complexRequest2":
             var worker2 = TestActorRef.Create<WorkerActor>(System);
             worker2.Tell(Sender, Self);
             return true;
         case "workDone":
             _replyTo.Tell("complexReply", Self);
             return true;
         case "simpleRequest":
             Sender.Tell("simpleReply", Self);
             return true;
     }
     return false;
 }
Ejemplo n.º 20
0
 protected virtual bool SpecialHandle(object message, ActorRef sender)
 {
     var w = message as Watch;
     if(w != null)
     {
         if(w.Watchee == this && w.Watcher != this)
         {
             w.Watcher.Tell(new DeathWatchNotification(w.Watchee, existenceConfirmed: false, addressTerminated: false));
         }
         return true;
     }
     if(message is Unwatch)
         return true;    //Just ignore
     var identify = message as Identify;
     if(identify != null)
     {
         sender.Tell(new ActorIdentity(identify.MessageId, null));
         return true;
     }
     var sel = message as ActorSelectionMessage;
     if(sel != null)
     {
         var selectionIdentify = sel.Message as Identify;
         if(selectionIdentify != null)
         {
             if(!sel.WildCardFanOut)
                 sender.Tell(new ActorIdentity(selectionIdentify.MessageId, null));
         }
         else
         {
             _eventStream.Publish(new DeadLetter(sel.Message, sender.IsNobody() ? _provider.DeadLetters : sender, this));
         }
         return true;
     }
     return false;
 }
Ejemplo n.º 21
0
 /// <summary>
 ///     Tells the internal.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="sender">The sender.</param>
 protected override void TellInternal(object message, ActorRef sender)
 {
     message
         .Match()
         .With<Identify>(m => sender.Tell(new ActorIdentity(m.MessageId, this)))
         .With<DeadLetter>(m =>
         {
             if (!SpecialHandle(m.Message, m.Sender))
                 eventStream.Publish(m);
         })
         .Default(m =>
         {
             if (!SpecialHandle(message, sender))
                 eventStream.Publish(new DeadLetter(message, sender == NoSender ? provider.DeadLetters : sender,
                     this));
         });
 }
            public ChaosApp(ActorRef probe)
            {
                _probe = probe;
                _destination = Context.ActorOf(Props.Create(() => new ChaosDestination(_probe)), "destination");
                _sender = Context.ActorOf(Props.Create(() => new ChaosSender(_destination, _probe)), "sender");

                Receive<Start>(_ =>
                {
                    for (int i = 1; i < GuaranteedDeliveryFailureSpec.NumberOfMessages; i++)
                    {
                        _sender.Tell(i);
                    }
                });
                Receive<ProcessingFailure>(x => _sender.Tell(x.I));
                Receive<JournalingFailure>(x => _sender.Tell(x.I));
            }
Ejemplo n.º 23
0
        public override void Start()
        {
            log.Info("Starting remoting");

            if (_endpointManager == null)
            {
                _endpointManager =
                System.SystemActorOf(
                    Props.Create(() => new EndpointManager(System.Settings.Config, log)).WithDeploy(Deploy.Local),
                    EndpointManagerName);

                try
                {
                    var addressPromise = new TaskCompletionSource<IList<ProtocolTransportAddressPair>>();
                    _endpointManager.Tell(new EndpointManager.Listen(addressPromise));

                    addressPromise.Task.Wait(Provider.RemoteSettings.StartupTimeout);
                    var akkaProtocolTransports = addressPromise.Task.Result;
                    if(akkaProtocolTransports.Count==0)
                        throw new Exception("No transports enabled");
                    Addresses = new HashSet<Address>(akkaProtocolTransports.Select(a => a.Address));
                    //   this.transportMapping = akkaProtocolTransports
                    //       .ToDictionary(p => p.ProtocolTransport.Transport.SchemeIdentifier,);
                    IEnumerable<IGrouping<string, ProtocolTransportAddressPair>> tmp =
                        akkaProtocolTransports.GroupBy(t => t.ProtocolTransport.SchemeIdentifier);
                    _transportMapping = new Dictionary<string, HashSet<ProtocolTransportAddressPair>>();
                    foreach (var g in tmp)
                    {
                        var set = new HashSet<ProtocolTransportAddressPair>(g);
                        _transportMapping.Add(g.Key, set);
                    }

                    DefaultAddress = akkaProtocolTransports.Head().Address;
                    _addresses = new HashSet<Address>(akkaProtocolTransports.Select(x => x.Address));

                    log.Info("Remoting started; listening on addresses : [{0}]", string.Join(",", _addresses.Select(x => x.ToString())));

                    _endpointManager.Tell(new EndpointManager.StartupFinished());
                    _eventPublisher.NotifyListeners(new RemotingListenEvent(_addresses.ToList()));

                }
                catch (TaskCanceledException ex)
                {
                    NotifyError("Startup was cancelled due to timeout", ex);
                    throw;
                }
                catch (TimeoutException ex)
                {
                    NotifyError("Startup timed out", ex);
                    throw;
                }
                catch (Exception ex)
                {
                    NotifyError("Startup failed", ex);
                    throw;
                }
            }
            else
            {
                log.Warning("Remoting was already started. Ignoring start attempt.");
            }
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Send message to an actor while using the probe as the sender.
 /// Replies will be available for inspection with all of TestKit's assertion
 /// methods.
 /// </summary>
 /// <param name="actor">The actor.</param>
 /// <param name="message">The message.</param>
 public void Send(ActorRef actor, object message)
 {
     actor.Tell(message, TestActor);
 }
Ejemplo n.º 25
0
            protected override void OnReceive(object message)
            {
                PatternMatch.Match(message)
                .With<InitializeLogger>(m =>
                {
                    var bus = m.LoggingBus;
                    bus.Subscribe(this.Self, typeof(SetTarget));
                    bus.Subscribe(this.Self, typeof(UnhandledMessage));

                    Sender.Tell(new LoggerInitialized());
                })
                .With<SetTarget>(m =>
                {
                    dst = m.Ref;
                    dst.Tell("OK");
                })
                .With<LogEvent>(m => dst.Tell(m))
                .With<UnhandledMessage>(m => dst.Tell(m));
            }
Ejemplo n.º 26
0
 /// <summary>
 ///     Delivers the specified message.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="pathIndex">Index of the path.</param>
 /// <param name="current">The current.</param>
 private void Deliver(object message, ActorRef sender, int pathIndex, ActorRef current)
 {
     if (pathIndex == Elements.Length)
     {
         current.Tell(message, sender);
     }
     else
     {
         SelectionPathElement element = Elements[pathIndex];
         if (current is ActorRefWithCell)
         {
             var withCell = (ActorRefWithCell) current;
             if (element is SelectParent)
                 Deliver(message, sender, pathIndex + 1, withCell.Parent);
             else if (element is SelectChildName)
                 Deliver(message, sender, pathIndex + 1,
                     withCell.GetSingleChild(element.AsInstanceOf<SelectChildName>().Name));
         }
         else
         {
             SelectionPathElement[] rest = Elements.Skip(pathIndex).ToArray();
             current.Tell(new ActorSelectionMessage(message, rest), sender);
         }
     }
 }
Ejemplo n.º 27
0
 /// <summary>
 ///     May only be called from the owner actor
 /// </summary>
 /// <param name="watchee"></param>
 public void Watch(ActorRef watchee)
 {
     watchees.Add(watchee);
     watchee.Tell(new Watch(watchee, Self), Self);
 }
Ejemplo n.º 28
0
            public DumbObserver(ActorPath path2, ActorRef testActorRef)
            {
                _testActorRef = testActorRef;

                Receive<ActorIdentity>(identity =>
                {
                    Context.Watch(identity.Subject);
                });

                Receive<Terminated>(terminated =>
                {
                    _testActorRef.Tell(terminated.ActorRef.Path);
                });

                Context.ActorSelection(path2).Tell(new Identify(path2));
            }
Ejemplo n.º 29
0
            public Observer(ActorPath path2, ActorPath path3, TestLatch watchEstablished, ActorRef testActorRef)
            {
                _watchEstablished = watchEstablished;
                _testActorRef = testActorRef;

                Receive<ActorIdentity>(identity => identity.MessageId.Equals(path2), identity =>
                {
                    Context.Watch(identity.Subject);
                    _watchEstablished.CountDown();
                });

                Receive<ActorIdentity>(identity => identity.MessageId.Equals(path3), identity =>
                {
                    Context.Watch(identity.Subject);
                    _watchEstablished.CountDown();
                });

                Receive<Terminated>(terminated =>
                {
                    _testActorRef.Tell(terminated.ActorRef.Path);
                });

                Context.ActorSelection(path2).Tell(new Identify(path2));
                Context.ActorSelection(path3).Tell(new Identify(path3));

            }
Ejemplo n.º 30
0
 /// <summary>
 /// Forwards the last received message to the specified actor as if the 
 /// <see cref="TestKitBase.LastMessage"/> was sent directly to the actor in the first place.
 /// </summary>
 /// <param name="actor">The actor to forward to.</param>
 public void Forward(ActorRef actor)
 {
     actor.Tell(LastMessage, Sender);
 }
Ejemplo n.º 31
0
        public void PersistentView_should_check_if_incoming_message_is_persistent()
        {
            _pref.Tell("c");
            _prefProbe.ExpectMsg("c-3");

            _view = ActorOf(() => new PersistentOrNotTestPersistentView(Name, _viewProbe.Ref));
            _view.Tell("d");
            _view.Tell("e");

            _viewProbe.ExpectMsg("replicated-a-1");
            _viewProbe.ExpectMsg("replicated-b-2");
            _viewProbe.ExpectMsg("replicated-c-3");
            _viewProbe.ExpectMsg("normal-d-3");
            _viewProbe.ExpectMsg("normal-e-3");

            _pref.Tell("f");
            _viewProbe.ExpectMsg("replicated-f-4");
        }
Ejemplo n.º 32
0
        public void PersistentView_should_run_size_limited_updates_on_user_request()
        {
            _pref.Tell("c");
            _pref.Tell("d");
            _pref.Tell("e");
            _pref.Tell("f");
            _prefProbe.ExpectMsg("c-3");
            _prefProbe.ExpectMsg("d-4");
            _prefProbe.ExpectMsg("e-5");
            _prefProbe.ExpectMsg("f-6");

            _view = ActorOf(() => new PassiveTestPersistentView(Name, _viewProbe.Ref, null));
            _view.Tell(new Update(isAwait: true, replayMax: 2));
            _view.Tell("get");
            _viewProbe.ExpectMsg("replicated-b-2");

            _view.Tell(new Update(isAwait: true, replayMax: 1));
            _view.Tell("get");
            _viewProbe.ExpectMsg("replicated-c-3");

            _view.Tell(new Update(isAwait: true, replayMax: 4));
            _view.Tell("get");
            _viewProbe.ExpectMsg("replicated-f-6");
        }
Ejemplo n.º 33
0
        private void Subscribe(ActorRef subscriber, ClusterEvent.SubscriptionInitialStateMode initMode,
            IEnumerable<Type> to)
        {
            if (initMode == ClusterEvent.SubscriptionInitialStateMode.InitialStateAsEvents)
            {
                Action<object> pub = @event =>
                {
                    var eventType = @event.GetType();
                    //TODO: IsAssignableFrom same as in scala?
                    if (to.Any(o => o.IsAssignableFrom(eventType)))
                        subscriber.Tell(@event);
                };
                PublishDiff(Gossip.Empty, _latestGossip, pub);
            }
            else if(initMode == ClusterEvent.SubscriptionInitialStateMode.InitialStateAsSnapshot)
            {
                SendCurrentClusterState(subscriber);
            }

            foreach (var t in to) _eventStream.Subscribe(subscriber, t);
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Schedules a message to a receiver.
 /// </summary>
 /// <param name="initialDelay">The initial delay.</param>
 /// <param name="interval">The interval.</param>
 /// <param name="receiver">The receiver.</param>
 /// <param name="message">The message.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>Task.</returns>
 public Task Schedule(TimeSpan initialDelay, TimeSpan interval, ActorRef receiver, object message,
                      CancellationToken cancellationToken)
 {
     return(InternalSchedule(initialDelay, interval, () => receiver.Tell(message), cancellationToken));
 }
Ejemplo n.º 35
0
            protected override bool Receive(object message)
            {
                var type = message.ToString();
                switch (type)
                {
                    case "complexRequest":
                        {
                            _replyTo = Sender;
                            var worker = Context.ActorOf(Props.Create<WorkerActor>());
                            worker.Tell("work");
                            break;
                        }
                    case "complexRequest2":
                        {
                            var worker = Context.ActorOf(Props.Create<WorkerActor>());
                            worker.Tell(new ReplyTo(Sender));
                            break;
                        }
                    case "workDone":
                        _replyTo.Tell("complexReply");
                        break;
                    case "simpleRequest":
                        Sender.Tell("simpleReply");
                        break;
                }

                return true;
            }
Ejemplo n.º 36
0
        private void DropFork(ActorRef fork)
        {
            if (this.LeftFork == fork)
            {
                //Console.WriteLine("{0} doesn't have  {1} in his left hand", this.Self.Name(), fork.Name());
                this.OwnsLeftFork = false;
            }
            else if(this.RightFork == fork)
            {
                //Console.WriteLine("{0} doesn't have {1} in his right hand", this.Self.Name(), fork.Name());
                this.OwnsRightFork = false;
            }

            fork.Tell(new ForkDropRequest(this.Self));
        }
Ejemplo n.º 37
0
 /// <summary>
 ///     May only be called from the owner actor
 /// </summary>
 /// <param name="watchee"></param>
 public void Unwatch(ActorRef watchee)
 {
     watchees.Remove(watchee);
     watchee.Tell(new Unwatch(watchee, Self));
 }
Ejemplo n.º 38
0
 public void Send(ActorRef actorRef, object msg)
 {
     actorRef.Tell(msg, Receiver);
 }
Ejemplo n.º 39
0
 /// <summary>
 ///     Delivers the specified message.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="pathIndex">Index of the path.</param>
 /// <param name="current">The current.</param>
 private void Deliver(object message, ActorRef sender, int pathIndex, ActorRef current)
 {
     if (pathIndex == Elements.Length)
     {
         current.Tell(message, sender);
     }
     else
     {
         SelectionPathElement element = Elements[pathIndex];
         if (current is ActorRefWithCell)
         {
             var withCell = (ActorRefWithCell) current;
             if (element is SelectParent)
                 Deliver(message, sender, pathIndex + 1, withCell.Parent);
             else if (element is SelectChildName)
                 Deliver(message, sender, pathIndex + 1,
                     withCell.GetSingleChild(element.AsInstanceOf<SelectChildName>().Name));
             else if (element is SelectChildPattern)
             {
                 var pattern = element as SelectChildPattern;
                 var children = withCell.Children.Where(c => c.Path.Name.Like(pattern.PatternStr));
                 foreach(var matchingChild in children)
                 {
                     Deliver(message, sender, pathIndex + 1, matchingChild);
                 }                        
             }
         }
         else
         {
             SelectionPathElement[] rest = Elements.Skip(pathIndex).ToArray();
             current.Tell(new ActorSelectionMessage(message, rest), sender);
         }
     }
 }
Ejemplo n.º 40
0
 public void PersistentView_should_take_snapshots()
 {
     _view = ActorOf(() => new SnapshottingPersistentView(Name, _viewProbe.Ref));
     _viewProbe.ExpectMsg("replicated-a-1");
     _viewProbe.ExpectMsg("replicated-b-2");
     _view.Tell("snap");
     _viewProbe.ExpectMsg("snapped");
     _view.Tell("restart");
     _pref.Tell("c");
     _viewProbe.ExpectMsg("replicated-b-2");
     _viewProbe.ExpectMsg("replicated-c-3");
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Forwards a message to the specified actor. As sender the sender of the last message is used.
 /// </summary>
 /// <param name="actor">The actor to forward to.</param>
 /// <param name="message">The message.</param>
 public void Forward(ActorRef actor, object message)
 {
     actor.Tell(message, Sender);
 }
Ejemplo n.º 42
0
 public void PersistentView_should_run_updates_again_on_failure_outside_an_update_cycle()
 {
     _view = ActorOf(() => new TestPersistentView(Name, _viewProbe.Ref, TimeSpan.FromSeconds(5), null));
     _viewProbe.ExpectMsg("replicated-a-1");
     _viewProbe.ExpectMsg("replicated-b-2");
     _view.Tell("boom");
     _viewProbe.ExpectMsg("replicated-a-1");
     _viewProbe.ExpectMsg("replicated-b-2");
 }
Ejemplo n.º 43
0
 /// <summary>
 /// The current snapshot state corresponding to latest gossip 
 /// to mimic what you would have seen if you were listening to the events.
 /// </summary>
 private void SendCurrentClusterState(ActorRef receiver)
 {
     var state = new ClusterEvent.CurrentClusterState(
         _latestGossip.Members,
         _latestGossip.Overview.Reachability.AllUnreachableOrTerminated.Select(_latestGossip.GetMember)
             .ToImmutableHashSet(),
         _latestGossip.SeenBy.Select(s => s.Address).ToImmutableHashSet(),
         _latestGossip.Leader == null ? null : _latestGossip.Leader.Address,
         _latestGossip.AllRoles.ToImmutableDictionary(r => r, r => _latestGossip.RoleLeader(r).Address)
         );
     receiver.Tell(state);
 }