Ejemplo n.º 1
0
 /// <summary>
 /// Pipes the output of a Task directly to the <paramref name="recipient"/>'s mailbox once
 /// the task completes
 /// </summary>
 /// <typeparam name="T">TBD</typeparam>
 /// <param name="taskToPipe">TBD</param>
 /// <param name="recipient">TBD</param>
 /// <param name="sender">TBD</param>
 /// <param name="success">TBD</param>
 /// <param name="failure">TBD</param>
 /// <returns>TBD</returns>
 public static Task PipeTo <T>(this Task <T> taskToPipe, ICanTell recipient, IActorRef sender = null, Func <T, object> success = null, Func <Exception, object> failure = null)
 {
     sender = sender ?? ActorRefs.NoSender;
     return(taskToPipe.ContinueWith(tresult =>
     {
         if (tresult.IsFaulted)
         {
             recipient.Tell(failure != null
                 ? failure(tresult.Exception)
                 : new Status.Failure(tresult.Exception), sender);
         }
         else if (tresult.IsCanceled)
         {
             var ex = tresult.Exception ?? new AggregateException(new TaskCanceledException());
             recipient.Tell(failure != null
                 ? failure(ex)
                 : new Status.Failure(ex), sender);
         }
         else if (tresult.IsCompleted)
         {
             recipient.Tell(success != null
                 ? success(tresult.Result)
                 : tresult.Result, sender);
         }
     }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default));
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Pipes the output of a Task directly to the <see cref="recipient"/>'s mailbox once
 /// the task completes
 /// </summary>
 public static Task PipeTo <T>(this Task <T> taskToPipe, ICanTell recipient, IActorRef sender = null)
 {
     sender = sender ?? ActorRefs.NoSender;
     return(taskToPipe.ContinueWith(tresult =>
     {
         if (tresult.IsCanceled || tresult.IsFaulted)
         {
             recipient.Tell(new Status.Failure(tresult.Exception), sender);
         }
         else if (tresult.IsCompleted)
         {
             recipient.Tell(tresult.Result, sender);
         }
     }, TaskContinuationOptions.ExecuteSynchronously & TaskContinuationOptions.AttachedToParent));
 }
Ejemplo n.º 3
0
        private static Task <object> Ask(ICanTell self, object message, IActorRefProvider provider,
                                         TimeSpan?timeout)
        {
            var result = new TaskCompletionSource <object>();

            timeout = timeout ?? provider.Settings.AskTimeout;

            if (timeout != Timeout.InfiniteTimeSpan && timeout.Value > default(TimeSpan))
            {
                var cancellationSource = new CancellationTokenSource();
                cancellationSource.Token.Register(() => result.TrySetCanceled());
                cancellationSource.CancelAfter(timeout.Value);
            }

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

            //The future actor needs to be registered in the temp container
            provider.RegisterTempActor(future, path);
            self.Tell(message, future);
            return(result.Task);
        }
Ejemplo n.º 4
0
 private void LogResultProcessing(RunnableScriptObject message, ICanTell statusUpdateActor)
 {
     statusUpdateActor.Tell(new UpdateRunStatusAsProcessingRequestMessage
     {
         ScriptId = message.RunnableScriptId
     }, Self);
 }
Ejemplo n.º 5
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="initialDelay">TBD</param>
        /// <param name="interval">TBD</param>
        /// <param name="receiver">TBD</param>
        /// <param name="message">TBD</param>
        /// <param name="sender">TBD</param>
        /// <param name="cancelable">TBD</param>
        protected override void InternalScheduleTellRepeatedly(TimeSpan initialDelay, TimeSpan interval,
                                                               ICanTell receiver, object message, IActorRef sender, ICancelable cancelable)
        {
            var cancellationToken = cancelable == null ? CancellationToken.None : cancelable.Token;

            InternalScheduleRepeatedly(initialDelay, interval, () => receiver.Tell(message, sender), cancellationToken);
        }
Ejemplo n.º 6
0
        private static Task <object> Ask(ICanTell self, object message, IActorRefProvider provider,
                                         TimeSpan?timeout)
        {
            var result = new TaskCompletionSource <object>();

            CancellationTokenSource timeoutCancellation = null;

            timeout = timeout ?? provider.Settings.AskTimeout;

            if (timeout != Timeout.InfiniteTimeSpan && timeout.Value > default(TimeSpan))
            {
                timeoutCancellation = new CancellationTokenSource();
                timeoutCancellation.Token.Register(() => result.TrySetCanceled());
                timeoutCancellation.CancelAfter(timeout.Value);
            }

            //create a new tempcontainer path
            ActorPath path = provider.TempPath();
            //callback to unregister from tempcontainer
            Action unregister =
                () =>
            {
                // cancelling timeout (if any) in order to prevent memory leaks
                // (a reference to 'result' variable in CancellationToken's callback)
                timeoutCancellation?.Cancel();
                provider.UnregisterTempActor(path);
            };

            var future = new FutureActorRef(result, unregister, path);

            //The future actor needs to be registered in the temp container
            provider.RegisterTempActor(future, path);
            self.Tell(message, future);
            return(result.Task);
        }
Ejemplo n.º 7
0
        private static async Task <object> Ask(ICanTell self, Func <IActorRef, object> messageFactory, IActorRefProvider provider,
                                               TimeSpan?timeout, CancellationToken cancellationToken)
        {
            TaskCompletionSource <object> result = TaskEx.NonBlockingTaskCompletionSource <object>();

            CancellationTokenSource timeoutCancellation = null;

            timeout = timeout ?? provider.Settings.AskTimeout;
            var ctrList = new List <CancellationTokenRegistration>(2);

            if (timeout != Timeout.InfiniteTimeSpan && timeout.Value > default(TimeSpan))
            {
                timeoutCancellation = new CancellationTokenSource();

                ctrList.Add(timeoutCancellation.Token.Register(() =>
                {
                    result.TrySetException(new AskTimeoutException($"Timeout after {timeout} seconds"));
                }));

                timeoutCancellation.CancelAfter(timeout.Value);
            }

            if (cancellationToken.CanBeCanceled)
            {
                ctrList.Add(cancellationToken.Register(() => result.TrySetCanceled()));
            }

            //create a new tempcontainer path
            ActorPath path = provider.TempPath();

            var future = new FutureActorRef(result, () => { }, path, TaskEx.IsRunContinuationsAsynchronouslyAvailable);

            //The future actor needs to be registered in the temp container
            provider.RegisterTempActor(future, path);
            var message = messageFactory(future);

            self.Tell(message, future);

            try
            {
                return(await result.Task);
            }
            finally
            {
                //callback to unregister from tempcontainer

                provider.UnregisterTempActor(path);

                for (var i = 0; i < ctrList.Count; i++)
                {
                    ctrList[i].Dispose();
                }

                if (timeoutCancellation != null)
                {
                    timeoutCancellation.Dispose();
                }
            }
        }
 protected override void InternalScheduleTellOnce(TimeSpan delay, ICanTell receiver, object message, IActorRef sender, ICancelable cancelable)
 {
     var cancellationToken = cancelable == null ? CancellationToken.None : cancelable.Token;
     InternalScheduleOnce(delay, () =>
     {
         receiver.Tell(message, sender);
     }, cancellationToken);
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Pipes the output of a Task directly to the <paramref name="recipient"/>'s mailbox once
 /// the task completes.  As this task has no result, only exceptions will be piped to the <paramref name="recipient"/>
 /// </summary>
 /// <param name="taskToPipe">TBD</param>
 /// <param name="recipient">TBD</param>
 /// <param name="sender">TBD</param>
 /// <param name="success">TBD</param>
 /// <param name="failure">TBD</param>
 /// <returns>TBD</returns>
 public static Task PipeTo(this Task taskToPipe, ICanTell recipient, IActorRef sender = null, Func <object> success = null, Func <Exception, object> failure = null)
 {
     sender = sender ?? ActorRefs.NoSender;
     return(taskToPipe.ContinueWith(tresult =>
     {
         if (tresult.IsCanceled || tresult.IsFaulted)
         {
             recipient.Tell(failure != null
                 ? failure(tresult.Exception)
                 : new Status.Failure(tresult.Exception), sender);
         }
         else if (tresult.IsCompleted && success != null)
         {
             recipient.Tell(success(), sender);
         }
     }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default));
 }
Ejemplo n.º 10
0
        private static Task <object> Ask(ICanTell self, object message, IActorRefProvider provider,
                                         TimeSpan?timeout, CancellationToken cancellationToken)
        {
            TaskCompletionSource <object> result;

            if (isRunContinuationsAsynchronouslyAvailable)
            {
                result = new TaskCompletionSource <object>((TaskCreationOptions)RunContinuationsAsynchronously);
            }
            else
            {
                result = new TaskCompletionSource <object>();
            }

            CancellationTokenSource timeoutCancellation = null;

            timeout = timeout ?? provider.Settings.AskTimeout;
            List <CancellationTokenRegistration> ctrList = new List <CancellationTokenRegistration>(2);

            if (timeout != Timeout.InfiniteTimeSpan && timeout.Value > default(TimeSpan))
            {
                timeoutCancellation = new CancellationTokenSource();
                ctrList.Add(timeoutCancellation.Token.Register(() => result.TrySetCanceled()));
                timeoutCancellation.CancelAfter(timeout.Value);
            }

            if (cancellationToken.CanBeCanceled)
            {
                ctrList.Add(cancellationToken.Register(() => result.TrySetCanceled()));
            }

            //create a new tempcontainer path
            ActorPath path = provider.TempPath();
            //callback to unregister from tempcontainer
            Action unregister =
                () =>
            {
                // cancelling timeout (if any) in order to prevent memory leaks
                // (a reference to 'result' variable in CancellationToken's callback)
                if (timeoutCancellation != null)
                {
                    timeoutCancellation.Cancel();
                    timeoutCancellation.Dispose();
                }
                for (var i = 0; i < ctrList.Count; i++)
                {
                    ctrList[i].Dispose();
                }
                provider.UnregisterTempActor(path);
            };

            var future = new FutureActorRef(result, unregister, path, isRunContinuationsAsynchronouslyAvailable);

            //The future actor needs to be registered in the temp container
            provider.RegisterTempActor(future, path);
            self.Tell(message, future);
            return(result.Task);
        }
Ejemplo n.º 11
0
        protected override void InternalScheduleTellOnce(TimeSpan delay, ICanTell receiver, object message, IActorRef sender, ICancelable cancelable)
        {
            var cancellationToken = cancelable == null ? CancellationToken.None : cancelable.Token;

            InternalScheduleOnce(delay, () =>
            {
                receiver.Tell(message, sender);
            }, cancellationToken);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <typeparam name="T">TBD</typeparam>
        /// <param name="self">TBD</param>
        /// <param name="messageFactory">Factory method that creates a message that can encapsulate the 'Sender' IActorRef</param>
        /// <param name="timeout">TBD</param>
        /// <param name="cancellationToken">TBD</param>
        /// <exception cref="ArgumentException">
        /// This exception is thrown if the system can't resolve the target provider.
        /// </exception>
        /// <returns>TBD</returns>
        public static Task <T> Ask <T>(this ICanTell self, Func <IActorRef, object> messageFactory, TimeSpan?timeout, CancellationToken cancellationToken)
        {
            IActorRefProvider provider = ResolveProvider(self);

            if (provider == null)
            {
                throw new ArgumentException("Unable to resolve the target Provider", nameof(self));
            }

            var result = TaskEx.NonBlockingTaskCompletionSource <T>();

            CancellationTokenSource timeoutCancellation = null;

            timeout = timeout ?? provider.Settings.AskTimeout;

            CancellationTokenRegistration?ctr1 = null;
            CancellationTokenRegistration?ctr2 = null;

            if (timeout != Timeout.InfiniteTimeSpan && timeout.Value > default(TimeSpan))
            {
                timeoutCancellation = new CancellationTokenSource();

                ctr1 = timeoutCancellation.Token.Register(() =>
                {
                    result.TrySetException(new AskTimeoutException($"Timeout after {timeout} seconds"));
                });

                timeoutCancellation.CancelAfter(timeout.Value);
            }

            if (cancellationToken.CanBeCanceled)
            {
                ctr2 = cancellationToken.Register(() => result.TrySetCanceled());
            }

            var future = provider.CreateFutureRef(result);
            var path   = future.Path;

            //The future actor needs to be unregistered in the temp container
            _ = result.Task.ContinueWith(t =>
            {
                provider.UnregisterTempActor(path);

                ctr1?.Dispose();
                ctr2?.Dispose();
                timeoutCancellation?.Dispose();
            }, TaskContinuationOptions.ExecuteSynchronously);

            //The future actor needs to be registered in the temp container
            provider.RegisterTempActor(future, path);
            var message = messageFactory(future);

            self.Tell(message, future);

            return(result.Task);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Pipes the output of a Task directly to the <paramref name="recipient"/>'s mailbox once
        /// the task completes
        /// </summary>
        /// <typeparam name="T">TBD</typeparam>
        /// <param name="taskToPipe">TBD</param>
        /// <param name="recipient">TBD</param>
        /// <param name="sender">TBD</param>
        /// <param name="success">TBD</param>
        /// <param name="failure">TBD</param>
        /// <returns>A detached task</returns>
        public static async Task PipeTo <T>(this Task <T> taskToPipe, ICanTell recipient, IActorRef sender = null, Func <T, object> success = null, Func <Exception, object> failure = null)
        {
            sender = sender ?? ActorRefs.NoSender;

            try
            {
                var result = await taskToPipe.ConfigureAwait(false);

                recipient.Tell(success != null
                    ? success(result)
                    : result, sender);
            }
            catch (Exception ex)
            {
                recipient.Tell(failure != null
                    ? failure(ex)
                    : new Status.Failure(ex), sender);
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Pipes the output of a Task directly to the <paramref name="recipient"/>'s mailbox once
 /// the task completes
 /// </summary>
 public static Task PipeTo <T>(this Task <T> taskToPipe, ICanTell recipient, IActorRef sender = null, Func <T, object> success = null, Func <Exception, object> failure = null)
 {
     sender = sender ?? ActorRefs.NoSender;
     return(taskToPipe.ContinueWith(tresult =>
     {
         if (tresult.IsCanceled || tresult.IsFaulted)
         {
             recipient.Tell(failure != null
                 ? failure((Exception)tresult.Exception)
                 : new Status.Failure((Exception)tresult.Exception), sender);
         }
         else if (tresult.IsCompleted)
         {
             recipient.Tell(success != null
                 ? success(tresult.Result)
                 : tresult.Result, sender);
         }
     }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.AttachedToParent));
 }
Ejemplo n.º 15
0
 // ReSharper disable once MemberCanBePrivate.Global - Akka needs it to be public
 public ProxyActor(TestKitBase testKit, ICanTell target)
 {
     IActorRef testActor = testKit.TestActor;
     ReceiveAny(m =>
     {
         if (Sender.Equals(testActor))
             target.Tell(m, Self);
         else
             testActor.Tell(m, Self);
     });
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Pipes the output of a Task directly to the <paramref name="recipient"/>'s mailbox once
 /// the task completes.  As this task has no result, only exceptions will be piped to the <paramref name="recipient"/>
 /// </summary>
 public static Task PipeTo(this Task taskToPipe, ICanTell recipient, IActorRef sender = null)
 {
     sender = sender ?? ActorRefs.NoSender;
     return(taskToPipe.ContinueWith(tresult =>
     {
         if (tresult.IsCanceled || tresult.IsFaulted)
         {
             recipient.Tell(new Status.Failure(tresult.Exception), sender);
         }
     }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default));
 }
Ejemplo n.º 17
0
 public void Log <TState>(LogLevel logLevel,
                          EventId eventId,
                          TState state,
                          Exception exception,
                          Func <TState, Exception, string> formatter)
 {
     _loggingActors.Tell(new LogItemBuilder()
                         .SetLogLevel(logLevel)
                         .SetEventId(eventId)
                         .SetState(state)
                         .SetException(exception)
                         .SetFormatter((o, ex) => formatter?.Invoke((TState)o, ex))
                         .Build(), null);
 }
Ejemplo n.º 18
0
        private void LogResultSuccess(RunnableScriptObject message, ICanTell storageActor, ICanTell scriptPullActor, ICanTell statusUpdateActor)
        {
            storageActor.Tell(new DbResultMessage
            {
                RunnableScriptId = message.RunnableScriptId,
                ReturnMessage    = "SUCCESS",
                ReturnValue      = 0
            }, Self);

            var updateMessage = new UpdateRunStatusAsCompletedRequestMessage
            {
                ScriptId = message.RunnableScriptId
            };

            statusUpdateActor.Tell(updateMessage, Self);
            scriptPullActor.Tell(updateMessage, Self);
        }
Ejemplo n.º 19
0
        private void LogResultFailure(RunnableScriptObject message, ICanTell storageActor,
                                      ICanTell statusUpdateActor, Exception e)
        {
            storageActor.Tell(new DbResultMessage
            {
                RunnableScriptId = message.RunnableScriptId,
                ReturnData       = null,
                ReturnException  = e,
                ReturnMessage    = "FAILURE",
                ReturnValue      = -1
            }, Self);

            statusUpdateActor.Tell(new UpdateRunStatusAsErroredOutRequestMessage
            {
                ScriptId  = message.RunnableScriptId,
                ErrorText = e.ToString()
            }, Self);
        }
Ejemplo n.º 20
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                ICanTell subscriber = _actorSystem.ActorSelection("/user/UIEventSubscriber")
                                      .ResolveOne(TimeSpan.FromSeconds(5), cancellationToken)
                                      .Result;

                subscriber.Tell(new SetHub(this), ActorRefs.NoSender);

                return(Task.CompletedTask);
            }
            catch (ActorNotFoundException ex)
            {
                _logger.LogError(ex, "UI EventSubscriberActor not found in ActorSystem.");

                return(Task.FromCanceled(cancellationToken));
            }
        }
Ejemplo n.º 21
0
        public static async Task <TResponse> Query <TResponse>(this ActorSystem system, ICanTell destination, object query, TimeSpan timeout)
        {
            var provider = (system as ActorSystemImpl)?.Provider;

            if (provider == null)
            {
                throw new NotSupportedException("Unable to resolve the target Provider");
            }

            var refs   = AskRefs.Create(provider, timeout);
            var iquery = Even.Query.Create(refs.FutureActorRef, query, timeout);

            if (destination != null)
            {
                destination.Tell(iquery, refs.FutureActorRef);
            }
            else
            {
                system.EventStream.Publish(iquery);
            }

            object taskResult;

            try
            {
                taskResult = await refs.CompletionSource.Task;
            }
            catch (TaskCanceledException ex)
            {
                throw new QueryException("Query timeout.", ex);
            }
            catch (Exception ex)
            {
                throw new QueryException("Unexpected query exception.", ex);
            }

            return((TResponse)taskResult);
        }
Ejemplo n.º 22
0
 public void Handle(CheckTime message)
 {
     _timeServer.Tell("gettime", Self);
 }
Ejemplo n.º 23
0
        private void Log(string text)
        {
            var logMsg = new LoggingActor.Log(text);

            _logger.Tell(logMsg, Self);
        }
Ejemplo n.º 24
0
 protected override void InternalScheduleTellOnce(TimeSpan delay, ICanTell receiver, object message, IActorRef sender,
     ICancelable cancelable)
 {
     receiver.Tell(message, sender);
 }
 protected override void InternalScheduleTellRepeatedly(TimeSpan initialDelay, TimeSpan interval, ICanTell receiver, object message, IActorRef sender, ICancelable cancelable)
 {
     var cancellationToken = cancelable == null ? CancellationToken.None : cancelable.Token;
     InternalScheduleRepeatedly(initialDelay, interval, () => receiver.Tell(message, sender), cancellationToken);
 }
Ejemplo n.º 26
0
 private static void Respond(ICanTell dest, string message, IEnumerable <IDomainEvent> events = null)
 {
     dest.Tell(new CommandResponse(message, events), ActorRefs.NoSender);
 }
Ejemplo n.º 27
0
 protected override void InternalScheduleTellRepeatedly(TimeSpan initialDelay, TimeSpan interval, ICanTell receiver, object message,
     IActorRef sender, ICancelable cancelable)
 {
     receiver.Tell(message, sender);
 }
Ejemplo n.º 28
0
 private static void ErrorResponse(ICanTell dest, string message)
 {
     dest.Tell(new ErrorCommandResponse(message), ActorRefs.NoSender);
 }
Ejemplo n.º 29
0
 public RecipientWatcherActor(ICanTell watchingTarget)
 {
     _watchingTarget = watchingTarget;
     _watchingTarget.Tell(new HandshakeMessage(), Self);
 }
Ejemplo n.º 30
0
 protected override void InternalScheduleTellRepeatedly(TimeSpan initialDelay, TimeSpan interval, ICanTell receiver, object message,
                                                        IActorRef sender, ICancelable cancelable)
 {
     receiver.Tell(message, sender);
 }
Ejemplo n.º 31
0
 protected override void InternalScheduleTellOnce(TimeSpan delay, ICanTell receiver, object message, IActorRef sender,
                                                  ICancelable cancelable)
 {
     receiver.Tell(message, sender);
 }
 public void Run()
 {
     _receiver.Tell(_message, _sender);
 }