Пример #1
0
        public void Setup(BenchmarkContext context)
        {
            MsgReceived = context.GetCounter("MsgReceived");
            System      = ActorSystem.Create("PerfSys", Config);
            int count = 0;
            Action <IActorDsl> actor = d => d.ReceiveAny((o, c) =>
            {
                MsgReceived.Increment();
                count++;
                if (count == ExpectedMessages)
                {
                    ResetEvent.Set();
                }
            });

            TestActor = System.ActorOf(Props.Create(() => new Act(actor)).WithDispatcher("calling-thread-dispatcher"), "testactor");

            SpinWait.SpinUntil(() => TestActor.AsInstanceOf <RepointableActorRef>().IsStarted);

            // force initialization of the actor
            for (var i = 0; i < ExpectedMessages - 1; i++)
            {
                TestActor.AsInstanceOf <RepointableActorRef>().Underlying.AsInstanceOf <ActorCell>().Mailbox.MessageQueue.Enqueue(TestActor, new Envelope("hit", ActorRefs.Nobody)); // queue all of the messages into the actor
            }
        }
Пример #2
0
 /// <inheritdoc cref="IMessageQueue"/>
 public void Enqueue(IActorRef receiver, Envelope envelope)
 {
     if (!_queue.TryAdd(envelope, PushTimeOut)) // dump messages that can't be delivered in-time into DeadLetters
     {
         receiver.AsInstanceOf <IInternalActorRef>().Provider.DeadLetters.Tell(new DeadLetter(envelope.Message, envelope.Sender, receiver), envelope.Sender);
     }
 }
Пример #3
0
        public static Task <bool> GracefulStop(this IActorRef target, TimeSpan timeout, object stopMessage)
        {
            var internalTarget = target.AsInstanceOf <IInternalActorRef>();

            var promiseRef = PromiseActorRef.Apply(internalTarget.Provider, timeout, target, stopMessage.GetType().Name);

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

                internalTarget.SendSystemMessage(new Unwatch(internalTarget, promiseRef));
                return returnResult;
            }, TaskContinuationOptions.ExecuteSynchronously));
        }
Пример #4
0
 public override void Send(object message, IActorRef sender)
 {
     if (sender is LocalActorRef)
     {
         sender.AsInstanceOf<LocalActorRef>().Provider.DeadLetters.Tell(message);
     }
 }
Пример #5
0
 public void Enqueue(IActorRef receiver, Envelope envelope)
 {
     if (!_queue.TryAdd(envelope, PushTimeOut)) // dump messages that can't be delivered in-time into DeadLetters
     {
         receiver.AsInstanceOf<IInternalActorRef>().Provider.DeadLetters.Tell(new DeadLetter(envelope.Message, envelope.Sender, receiver), envelope.Sender);
     }
 }
Пример #6
0
 public override void Send(object message, IActorRef sender)
 {
     if (sender is LocalActorRef)
     {
         sender.AsInstanceOf <LocalActorRef>().Provider.DeadLetters.Tell(message);
     }
 }
Пример #7
0
        /// <summary>
        ///     Restarts the child.
        /// </summary>
        /// <param name="child">The child.</param>
        /// <param name="cause">The cause.</param>
        /// <param name="suspendFirst">if set to <c>true</c> [suspend first].</param>
        protected void RestartChild(IActorRef child, Exception cause, bool suspendFirst)
        {
            var c = child.AsInstanceOf <IInternalActorRef>();

            if (suspendFirst)
            {
                c.Suspend();
            }
            c.AsInstanceOf <IInternalActorRef>().Restart(cause);
        }
Пример #8
0
        public void Setup(BenchmarkContext context)
        {
            MsgReceived = context.GetCounter("MsgReceived");
            System = ActorSystem.Create("PerfSys", Config);
            int count = 0;
            Action<IActorDsl> actor = d => d.ReceiveAny((o, c) =>
            {
                MsgReceived.Increment();
                count++;
                if(count == ExpectedMessages)
                    ResetEvent.Set();
            });
            TestActor = System.ActorOf(Props.Create(() => new Act(actor)).WithDispatcher("calling-thread-dispatcher"), "testactor");

            SpinWait.SpinUntil(() => TestActor.AsInstanceOf<RepointableActorRef>().IsStarted);

            // force initialization of the actor
            for(var i = 0; i < ExpectedMessages-1;i++)
                TestActor.AsInstanceOf<RepointableActorRef>().Underlying.AsInstanceOf<ActorCell>().Mailbox.MessageQueue.Enqueue(TestActor, new Envelope("hit", ActorRefs.Nobody)); // queue all of the messages into the actor
        }
Пример #9
0
 void AwaitStarted(IActorRef actorRef)
 {
     AwaitCondition(() =>
     {
         if (actorRef is RepointableActorRef)
         {
             return(actorRef.AsInstanceOf <RepointableActorRef>().IsStarted);
         }
         return(true);
     }, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(10));
 }
Пример #10
0
        /// <summary>
        /// The serialized path of an actorRef, based on the current transport serialization information.
        /// If there is no external address available for the requested address then the systems default
        /// address will be used.
        ///
        /// If there is no external address available in the given <see cref="IActorRef"/> then the systems default
        /// address will be used and that is retrieved from the ThreadLocal <see cref="Information"/>
        /// that was set with <see cref="Serialization.WithTransportInformation{T}"/>
        /// </summary>
        /// <param name="actorRef">The <see cref="IActorRef"/> to be serialized.</param>
        /// <returns>Absolute path to the serialized actor.</returns>
        public static string SerializedActorPath(IActorRef actorRef)
        {
            if (Equals(actorRef, ActorRefs.NoSender))
            {
                return(String.Empty);
            }

            var path = actorRef.Path;
            ExtendedActorSystem originalSystem = null;

            if (actorRef is ActorRefWithCell)
            {
                originalSystem = actorRef.AsInstanceOf <ActorRefWithCell>().Underlying.System.AsInstanceOf <ExtendedActorSystem>();
            }

            if (CurrentTransportInformation == null)
            {
                if (originalSystem == null)
                {
                    var res = path.ToSerializationFormat();
                    return(res);
                }

                try
                {
                    var defaultAddress = originalSystem.Provider.DefaultAddress;
                    var res            = path.ToSerializationFormatWithAddress(defaultAddress);
                    return(res);
                }
                catch
                {
                    return(path.ToSerializationFormat());
                }
            }

            //CurrentTransportInformation exists
            var system  = CurrentTransportInformation.System;
            var address = CurrentTransportInformation.Address;

            if (originalSystem == null || originalSystem == system)
            {
                var res = path.ToSerializationFormatWithAddress(address);
                return(res);
            }
            else
            {
                var provider = originalSystem.Provider;
                var res      =
                    path.ToSerializationFormatWithAddress(provider.GetExternalAddressFor(address) ?? provider.DefaultAddress);
                return(res);
            }
        }
Пример #11
0
        public void Setup(BenchmarkContext context)
        {
            MsgReceived = context.GetCounter("MsgReceived");
            System = ActorSystem.Create("PerfSys");
            Action<IActorDsl> actor = d => d.ReceiveAny((o, c) =>
            {
                MsgReceived.Increment();
            });
            TestActor = System.ActorOf(Props.Create(() => new Act(actor)), "testactor");
            var id = TestActor.Ask<ActorIdentity>(new Identify(null), TimeSpan.FromSeconds(3)).Result;

            Mailbox = new Mailbox(new UnboundedMessageQueue());
            Mailbox.SetActor(TestActor.AsInstanceOf<RepointableActorRef>().Underlying.AsInstanceOf<ActorCell>());
        }
Пример #12
0
        private static ImmutableList<IActorRef> Recurse(IActorRef @ref)
        {
            var empty = new List<IActorRef>();
            var list = empty;
            if (@ref is ActorRefWithCell)
            {
                var cell = @ref.AsInstanceOf<ActorRefWithCell>().Underlying;
                if (cell.ChildrenContainer is EmptyChildrenContainer ||
                    cell.ChildrenContainer is TerminatedChildrenContainer ||
                    cell.ChildrenContainer is TerminatingChildrenContainer) list = empty;
                else list = cell.ChildrenContainer.Children.Cast<IActorRef>().ToList();
            }

            return ImmutableList<IActorRef>.Empty.Add(@ref).AddRange(list.SelectMany(Recurse));
        }
Пример #13
0
        public void Setup(BenchmarkContext context)
        {
            MsgReceived = context.GetCounter("MsgReceived");
            System      = ActorSystem.Create("PerfSys");
            Action <IActorDsl> actor = d => d.ReceiveAny((o, c) =>
            {
                MsgReceived.Increment();
            });

            TestActor = System.ActorOf(Props.Create(() => new Act(actor)), "testactor");
            var id = TestActor.Ask <ActorIdentity>(new Identify(null), TimeSpan.FromSeconds(3)).Result;

            Mailbox = new Mailbox(new UnboundedMessageQueue());
            Mailbox.SetActor(TestActor.AsInstanceOf <RepointableActorRef>().Underlying.AsInstanceOf <ActorCell>());
        }
Пример #14
0
        public static Task <bool> GracefulStop(this IActorRef target, TimeSpan timeout, object stopMessage)
        {
            var internalTarget = target.AsInstanceOf <IInternalActorRef>();

            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, unregister, path);

            internalTarget.Tell(new Watch(internalTarget, fref));
            target.Tell(stopMessage, ActorRefs.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));
        }
        public override IMessageQueue Create(IActorRef owner, ActorSystem system)
        {
            if (owner is ActorRefWithCell)
            {
                var actorType = owner.AsInstanceOf <ActorRefWithCell>().Underlying.Props.Type;
                if (!typeof(ActorBase).IsAssignableFrom(actorType))
                {
                    throw new ArgumentException(
                              $"Don't use anonymouse actor classes, actor class for {owner} was [{actorType.FullName}]");
                }
                // StreamTcpManager is allowed to use another dispatcher
                if (actorType.FullName.StartsWith("Akka.Streams."))
                {
                    throw new ArgumentException(
                              $"{owner} with actor class [{actorType.FullName}] must not run on default dispatcher in tests. Did you forget to define `props.withDispatcher` when creating the actor? Or did you forget to configure the `akka.stream.materializer` setting accordingly or force the dispatcher using `ActorMaterializerSettings(sys).withDispatcher(\"akka.test.stream-dispatcher\")` in the test?");
                }
            }

            return(new UnboundedMessageQueue());
        }
Пример #16
0
        private static ImmutableList <IActorRef> Recurse(IActorRef @ref)
        {
            var empty = new List <IActorRef>();
            var list  = empty;

            if (@ref is ActorRefWithCell)
            {
                var cell = @ref.AsInstanceOf <ActorRefWithCell>().Underlying;
                if (cell.ChildrenContainer is EmptyChildrenContainer ||
                    cell.ChildrenContainer is TerminatedChildrenContainer ||
                    cell.ChildrenContainer is TerminatingChildrenContainer)
                {
                    list = empty;
                }
                else
                {
                    list = cell.ChildrenContainer.Children.Cast <IActorRef>().ToList();
                }
            }

            return(ImmutableList <IActorRef> .Empty.Add(@ref).AddRange(list.SelectMany(Recurse)));
        }
Пример #17
0
        public static string SerializedActorPath(IActorRef @ref)
        {
            /*
             * val path = actorRef.path
             * val originalSystem: ExtendedActorSystem = actorRef match {
             * case a: ActorRefWithCell ⇒ a.underlying.system.asInstanceOf[ExtendedActorSystem]
             * case _                   ⇒ null
             * }
             * Serialization.currentTransportInformation.value match {
             * case null ⇒ originalSystem match {
             * case null ⇒ path.toSerializationFormat
             * case system ⇒
             * try path.toSerializationFormatWithAddress(system.provider.getDefaultAddress)
             * catch { case NonFatal(_) ⇒ path.toSerializationFormat }
             * }
             * case Information(address, system) ⇒
             * if (originalSystem == null || originalSystem == system)
             * path.toSerializationFormatWithAddress(address)
             * else {
             * val provider = originalSystem.provider
             * path.toSerializationFormatWithAddress(provider.getExternalAddressFor(address).getOrElse(provider.getDefaultAddress))
             * }
             * }*/
            ActorSystem originalSystem = null;

            if (@ref is ActorRefWithCell)
            {
                originalSystem = @ref.AsInstanceOf <ActorRefWithCell>().Underlying.System;
                if (CurrentTransportInformation == null)
                {
                    return(@ref.Path.ToSerializationFormat());
                }
                return(@ref.Path.ToStringWithAddress(CurrentTransportInformation.Address));
            }
            return(@ref.Path.ToSerializationFormat());
        }
Пример #18
0
 void AwaitStarted(IActorRef actorRef)
 {
     AwaitCondition(() =>
     {
         if (actorRef is RepointableActorRef)
             return actorRef.AsInstanceOf<RepointableActorRef>().IsStarted;
         return true;
     }, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(10));
 }
Пример #19
0
 /// <summary>
 /// Resumes the previously failed child. Suspend/resume needs to be done in
 /// matching pairs, otherwise actors will wake up too soon or never at all.
 /// <note>
 /// <b>Never apply this to a child which is not the currently failing child.</b>
 /// </note>
 /// </summary>
 /// <param name="child">The child actor that is being resumed.</param>
 /// <param name="exception">The exception that caused the child actor to fail.</param>
 protected void ResumeChild(IActorRef child, Exception exception)
 {
     child.AsInstanceOf <IInternalActorRef>().Resume(exception);
 }
Пример #20
0
        public static string SerializedActorPath(IActorRef @ref)
        {
            /*
val path = actorRef.path
    val originalSystem: ExtendedActorSystem = actorRef match {
      case a: ActorRefWithCell ⇒ a.underlying.system.asInstanceOf[ExtendedActorSystem]
      case _                   ⇒ null
    }
    Serialization.currentTransportInformation.value match {
      case null ⇒ originalSystem match {
        case null ⇒ path.toSerializationFormat
        case system ⇒
          try path.toSerializationFormatWithAddress(system.provider.getDefaultAddress)
          catch { case NonFatal(_) ⇒ path.toSerializationFormat }
      }
      case Information(address, system) ⇒
        if (originalSystem == null || originalSystem == system)
          path.toSerializationFormatWithAddress(address)
        else {
          val provider = originalSystem.provider
          path.toSerializationFormatWithAddress(provider.getExternalAddressFor(address).getOrElse(provider.getDefaultAddress))
        }
    }*/
            ActorSystem originalSystem = null;
            if (@ref is ActorRefWithCell)
            {
                originalSystem = @ref.AsInstanceOf<ActorRefWithCell>().Underlying.System;
                if (CurrentTransportInformation == null)
                {
                    return @ref.Path.ToSerializationFormat();
                }
                return @ref.Path.ToStringWithAddress(CurrentTransportInformation.Address);
            }
            return @ref.Path.ToSerializationFormat();
        }