Beispiel #1
0
        public async Task <bool> SimulateMatch(List <UserRequest> players, ActorInfo actorInfo)
        {
            if (players[0].EndAfterSeconds && players[1].EndAfterSeconds)
            {
                _updateTimer = RegisterTimer(Update, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
            }

            bool added = await this.StateManager.TryAddStateAsync <int>(IndexName, actorInfo.ActorIndex);

            if (!added)
            {
                // value already exists, which means processing has already started.
                throw new InvalidOperationException($"Cannot assign index {actorInfo.ActorIndex} to actor!");
            }

            added = await this.StateManager.TryAddStateAsync <GameState>(GameStateName, new GameState(players));

            if (!added)
            {
                // value already exists, which means processing has already started.
                throw new InvalidOperationException("Processing for this actor has already started.");
            }

            return(true);
        }
 protected override Task OnActivateAsync()
 {
     _actortimer = RegisterTimer(DoWork, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(15)
                                 );
     ActorEventSource.Current.ActorMessage(this, "Actor activated.");
     return(this.StateManager.TryAddStateAsync("count", 0));
 }
 protected override Task OnActivateAsync()
 {
     this.StateManager.AddStateAsync<TermiteState>("State", new TermiteState { X = rand.Next(0, size), Y = rand.Next(0, size), HasWoodchip = false });
     mTimer = RegisterTimer(Move, this.StateManager.GetStateAsync<TermiteState>("State"), TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(50));
     boxClient = ServiceProxy.Create<IBox>(new Uri("fabric:/TermiteModel/Box"), new ServicePartitionKey(0));
     return Task.FromResult(true);
 }
Beispiel #4
0
        public virtual async Task <string> OnCreated(string id, string json, CancellationToken cancellationToken)
        {
            await this.StateManager.SetStateAsync <string>(MyInstance, json, cancellationToken);

            await this.StateManager.SetStateAsync <string>(IdKey, id, cancellationToken);

            var switches = await this.StateManager.GetStateAsync <Dictionary <string, string> >(SwitchesKey);

            ensureHandler(switches);
            var extendedState = await mHandler.OnCreated(id, json, switches);

            if (extendedState.Succeeded == true)
            {
                if (!string.IsNullOrEmpty(extendedState.UpdatedState))
                {
                    await this.StateManager.SetStateAsync <string>(MyState, extendedState.UpdatedState, cancellationToken);
                }
                if (!string.IsNullOrEmpty(extendedState.UpdatedEntity))
                {
                    await this.StateManager.SetStateAsync <string>(MyInstance, extendedState.UpdatedEntity, cancellationToken);
                }
                updateTimer = RegisterTimer(
                    WatchStatusAsync,             // Callback method
                    extendedState.UpdatedState,   // Parameter to pass to the callback method
                    TimeSpan.FromSeconds(3),      // Amount of time to delay before the callback is invoked
                    TimeSpan.FromSeconds(3));     // Time interval between invocations of the callback method
            }
            return(extendedState.UpdatedEntity);
        }
Beispiel #5
0
        private async Task SendPings()
        {
            this.SendCounter++;

            ActorEventSource.Current.ActorMessage(this, "[FailureDetector] Wants to send some pings");
            foreach (var node in this.Nodes)
            {
                ActorEventSource.Current.ActorMessage(this, "[FailureDetector] Wants to send ping to node {0}", node.Key);
                ActorEventSource.Current.ActorMessage(this, "[FailureDetector] Alive {0}", this.Alive.ContainsKey(node.Value));
                ActorEventSource.Current.ActorMessage(this, "[FailureDetector] Responses {0}", this.Responses.ContainsKey(node.Value));
                if (this.Alive.ContainsKey(node.Value) &&
                    !this.Responses.ContainsKey(node.Value))
                {
                    ActorEventSource.Current.ActorMessage(this, "[FailureDetector] Sending ping to node {0}", node.Key);

                    ActorEventSource.Current.ActorMessage(this, "[Monitor] Notifies ping to node {0}", node.Key);
                    await SafetyMonitor.NotifyPing(node.Key);

                    await node.Value.Ping(PingCounter ++, this.FailureDetectorId);
                }
            }

            this.Timer = this.RegisterTimer(HandleTimeout, null,
                                            TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
        }
        protected override async Task OnActivateAsync()
        {
            try
            {
                await this.StateManager.TryAddStateAsync <Dictionary <int, ProductStockTrend> >("ProductStockTrends", new Dictionary <int, ProductStockTrend>());

                TimeSpan startDelay = TimeSpan.Parse(ConfigurationHelper.ReadValue("AppSettings", "PredictionTimerStartDelay"));
                TimeSpan interval   = TimeSpan.Parse(ConfigurationHelper.ReadValue("AppSettings", "PredictionTimerInterval"));

                if (!int.TryParse(ConfigurationHelper.ReadValue("AppSettings", "PredictionNotificationAttempts"), out this.notificationAttempts))
                {
                    this.notificationAttempts = 10;
                }

                // register timer to regularly check for updates
                this.notificationTimer = this.RegisterTimer(
                    this.RunNotificationAsync,
                    null,
                    startDelay,
                    interval
                    );

                this.mlClient = AzureMlClientFactory.CreateClient();

                await base.OnActivateAsync();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, nameof(this.OnActivateAsync));
                throw;
            }
        }
        /// <summary>
        /// This method is called whenever an actor is activated.
        /// Creates the initial state object and starts the Message forwarding timer.
        /// </summary>
        protected override async Task OnActivateAsync()
        {
            if (Id.Kind != ActorIdKind.String)
            {
                throw new InvalidOperationException("BrokerActor can only be created using a String ID. The ID should be the Full Name of the Message Type.");
            }

            _messageType = Id.GetStringId();


            if (!await StateManager.ContainsStateAsync(StateKey))
            {
                // This is the first time this actor has ever been activated.
                // Set the actor's initial state values.
                var state = new BrokerActorState
                {
                    SubscriberMessages    = new Dictionary <ReferenceWrapper, Queue <MessageWrapper> >(),
                    SubscriberDeadLetters = new Dictionary <ReferenceWrapper, Queue <MessageWrapper> >()
                };
                await StateManager.TryAddStateAsync(StateKey, state);

                ActorEventSourceMessage("State initialized.");
            }

            if (_timer == null)
            {
                _timer = RegisterTimer(async _ =>
                {
                    await ProcessQueuesAsync();
                }, null, DueTime, Period);

                ActorEventSourceMessage("Timer initialized.");
            }
        }
Beispiel #8
0
 /// <summary>
 /// Shutdowns the dispatcher
 /// </summary>
 internal static void Shutdown()
 {
     if (m_oneSecondTimer != null)
     {
         m_oneSecondTimer.Stop();
         m_oneSecondTimer = null;
     }
 }
        /// <summary>
        ///     This method is called whenever an actor is activated.
        ///     An actor is activated the first time any of its methods are invoked.
        /// </summary>
        protected override Task OnActivateAsync()
        {
            ActorEventSource.Current.ActorMessage(this, "Actor activated.");

            EchoTimer = RegisterTimer(OnTimer, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));

            return(Task.FromResult(0));
        }
Beispiel #10
0
        private async Task InternalHandle(object _)
        {
            var handle = string.Empty;

            try
            {
                UnregisterTimer(_handleTimer);

                var handleList = (await StateManager.GetStateNamesAsync()).ToList();

                if (!handleList.Any())
                {
                    return;
                }

                var messageDataConditional = await StateManager.TryGetStateAsync <MessageData>(handleList.First());

                if (!messageDataConditional.HasValue)
                {
                    _bigBrother.Publish(new WebhookEvent("message was empty"));
                    return;
                }

                var messageData = messageDataConditional.Value;
                handle = messageData.HandleAsString;

                var handler = _eventHandlerFactory.CreateEventHandler(messageData.Type);

                await handler.Call(messageData);

                await StateManager.RemoveStateAsync(messageData.HandleAsString);

                await ActorProxy.Create <IPoolManagerActor>(new ActorId(0)).CompleteWork(messageData.Handle);
            }
            catch (Exception e)
            {
                //don't want msg state managed by fabric just yet, let failures be backed by the service bus subscriptions
                if (handle != string.Empty)
                {
                    await StateManager.RemoveStateAsync(handle);
                }

                BigBrother.Write(e.ToExceptionEvent());
            }
            finally
            {
                //restarts the timer in case there are more than one msg in the state, if not then let it be restarted in the standard msg population flow.
                if ((await StateManager.GetStateNamesAsync()).Any())
                {
                    _handleTimer = RegisterTimer(
                        InternalHandle,
                        null,
                        TimeSpan.FromMilliseconds(100),
                        TimeSpan.MaxValue);
                }
            }
        }
Beispiel #11
0
 /// <summary>
 /// This method is called whenever an actor is activated.
 /// An actor is activated the first time any of its methods are invoked.
 /// </summary>
 protected override Task OnActivateAsync()
 {
     _updateTimer = RegisterTimer(
         MoveObject,                      // Callback method
         null,                            // Parameter to pass to the callback method
         TimeSpan.FromMilliseconds(500),  // Amount of time to delay before the callback is invoked
         TimeSpan.FromMilliseconds(500)); // Time interval between invocations of the callback method
     return(base.OnActivateAsync());
 }
Beispiel #12
0
 protected override Task OnActivateAsync()
 {
     ActorEventSource.Current.ActorMessage(this, "Actor activated.");
     mTimer = this.RegisterTimer(Move,                     //callback function
                                 null,                     //callback state
                                 TimeSpan.FromSeconds(5),  //delay before first callback
                                 TimeSpan.FromSeconds(1)); //callback interval
     return(this.StateManager.TryAddStateAsync("My-Location", new Tuple <double, double>(-122.041934, 47.694861)));
 }
Beispiel #13
0
        /// <summary>
        /// Unregisters a Timer previously set on this actor.
        /// </summary>
        /// <param name="timer">An IActorTimer representing timer that needs to be unregistered.</param>
        /// <returns>Task representing the Unregister timer operation.</returns>
        protected async Task UnregisterTimerAsync(IActorTimer timer)
        {
            await ActorRuntime.DaprInteractor.UnregisterTimerAsync(this.actorTypeName, this.Id.ToString(), timer.Name);

            if (this.timers.ContainsKey(timer.Name))
            {
                this.timers.Remove(timer.Name);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Shutdowns the dispatcher.
        /// </summary>
        internal static void Shutdown()
        {
            if (m_oneSecondTimer == null)
            {
                return;
            }

            m_oneSecondTimer.Stop();
            m_oneSecondTimer = null;
        }
Beispiel #15
0
        protected override async Task OnDeactivateAsync()
        {
            if (this.Timer != null)
            {
                this.UnregisterTimer(this.Timer);
                this.Timer = null;
            }

            await base.OnDeactivateAsync();
        }
Beispiel #16
0
 /// <summary>
 /// Unregisters a Timer previously set on this actor.
 /// </summary>
 /// <param name="timer">IActorTimer representing timer that needs to be unregistered..</param>
 protected void UnregisterTimer(IActorTimer timer)
 {
     if ((timer != null) && (this.timers != null))
     {
         if (this.timers.Remove(timer))
         {
             timer.Dispose();
         }
     }
 }
        /// <summary>
        /// This method is called right before the actor is deactivated.
        /// Unregisters the timer.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Threading.Tasks.Task">Task</see> that represents outstanding OnDeactivateAsync operation.
        /// </returns>
        protected override Task OnDeactivateAsync()
        {
            if (_timer != null)
            {
                UnregisterTimer(_timer);
            }
            _timer = null;

            return(Task.FromResult(true));
        }
        public async Task Handle(MessageData messageData)
        {
            await StateManager.AddOrUpdateStateAsync(messageData.HandlerId.ToString(), messageData, (s, pair) => pair);

            _handleTimer = RegisterTimer(
                InternalHandle,
                messageData,
                TimeSpan.FromMilliseconds(100),
                TimeSpan.MaxValue);
        }
Beispiel #19
0
 protected override Task OnDeactivateAsync()
 {
     if (m_WorkTimer != null)
     {
         UnregisterTimer(m_WorkTimer);
         m_WorkTimer = null;
     }
     m_tc.TrackEvent($"OnDeactivateAsync - {this.GetActorId().ToString()}, Timers Stop");
     m_tc.Flush();
     return(base.OnDeactivateAsync());
 }
Beispiel #20
0
 protected override Task OnActivateAsync()
 {
     if (this.State == null)
     {
         this.State = new TermiteState {
             X = rand.Next(0, size), Y = rand.Next(0, size), HasWoodchip = false
         };
     }
     mTimer = RegisterTimer(Move, this.State, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(50));
     return(Task.FromResult(true));
 }
Beispiel #21
0
        protected override async Task OnDeactivateAsync()
        {
            if (_Timer != null)
            {
                UnregisterTimer(_Timer);
                _Timer = null;
            }
            ActorId StatId = new ActorId(1);
            await StatId.Proxy <IStatistics>().UpdateStats("Gate", _StatDict);

            await base.OnDeactivateAsync();
        }
Beispiel #22
0
 protected override Task OnActivateAsync()
 {
     if (this.State == null)
     {
         this.State = new ActorState {
             PartitionNames = new List <string>(), PartitionLeases = new Dictionary <string, DateTime>()
         };
         ResetPartitionNames();
         mTimer = RegisterTimer(CheckLease, null, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30));
     }
     return(Task.FromResult(true));
 }
Beispiel #23
0
        protected override Task OnActivateAsync()
        {
            // Start timer that will try to register the reminder every 10 seconds until it succeeds or
            // the specified number of retries is made.
            this._reminderRegistrationTimer = this.RegisterTimer(
                asyncCallback: state => this.RegisterWakeUpReminderTimerCallbackAsync(),
                state: null,
                dueTime: TimeSpan.FromMilliseconds(ReminderRegistrationRetryIntervalMilliseconds),
                period: TimeSpan.FromMilliseconds(ReminderRegistrationRetryIntervalMilliseconds));

            return(Task.CompletedTask);
        }
        protected override Task OnActivateAsync()
        {
            if (this.State == null)
            {
                this.State = VisualObject.CreateRandom(this.Id.ToString(), new Random(this.Id.ToString().GetHashCode()));
            }

            this.jsonString = this.State.ToJson();

            // ACTOR MOVEMENT REFRESH
            this.updateTimer = this.RegisterTimer(this.MoveObject, null, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(10));
            return(base.OnActivateAsync());
        }
        protected override async Task OnActivateAsync()
        {
            ActorEventSource.Current.ActorMessage(this, "Actor activated.");

            var assetPairs = await _dictionaryProxy.GetAssetPairsAsync();

            await _assetPairQuoteRepository.AddAllAsync(assetPairs);

            await StateManager.TryAddStateAsync("AssetPairs", assetPairs);

            _updateAssetTimer = RegisterTimer(UpdateAssetPairAsync, null, TimeSpan.FromSeconds(10),
                                              TimeSpan.FromSeconds(10));
        }
Beispiel #26
0
        protected override async Task OnActivateAsync()
        {
            await StateManager.SetStateAsync(Constants.ActivatedStateName, true);

            await StateManager.SetStateAsync(Constants.LastUpdatedStateName, DateTimeOffset.UtcNow);


            _updateTimer = RegisterTimer(
                OnUpdateCheckAsync,        // Callback method
                null,                      // Parameter to pass to the callback method
                TimeSpan.FromMinutes(0),   // Amount of time to delay before the callback is invoked
                TimeSpan.FromSeconds(10)); // Time interval between invocations of the callback method
        }
Beispiel #27
0
        public async Task <GenericResponse> RegisterObserver(ActorId playerAgentID, ActorId[] fromActors)
        {
            var players = await this.StateManager.GetStateAsync <Dictionary <ActorId, MinecraftVersion> >("observers");

            var version = MinecraftVersion.GetNext();

            //Is player already here?
            if (players.ContainsKey(playerAgentID) == true)
            {
                return(new GenericResponse(true, "Already Exist"));
            }

            //this player want to listen to all associated blocks
            var initPlayers = await this.StateManager.GetStateAsync <Dictionary <ActorId, MinecraftVersion> >("initializeObservers");

            initPlayers.Add(playerAgentID, version);
            await this.StateManager.SetStateAsync("initializeObservers", initPlayers);

            //map to hash for faster lookup
            var map = new HashSet <ActorId>();

            foreach (var actor in fromActors)
            {
                map.Add(actor);
            }

            var associations = await this.StateManager.GetStateAsync <Dictionary <ActorId, AssociateChunkMetaData> >("associations");

            //each associated grain needs to update this one
            foreach (var pair in associations)
            {
                var actorID = pair.Key;
                if (map.Contains(actorID) == false)
                {
                    var assocations = pair.Value;
                    assocations.needInitObservers.Add(actorID);
                }
            }

            await this.StateManager.SetStateAsync("associations", associations);

            //if no updates are occuring, now we have a player to update
            if (_updateTimer == null)
            {
                int updateRate = await this.StateManager.GetStateAsync <int>("updateRateMS");

                _updateTimer = RegisterTimer((_) => Fetch(), null, TimeSpan.FromMilliseconds(0), TimeSpan.FromMilliseconds(updateRate));
            }

            return(new GenericResponse());
        }
Beispiel #28
0
        /// <summary>
        /// Schedules the given action using an actor timer.
        /// </summary>
        /// <param name="action"></param>
        protected void InvokeWithTimer(Func <Task> action)
        {
            Contract.Requires <ArgumentNullException>(action != null);

            // hoist timer so it can be unregistered
            IActorTimer timer = null;

            // schedule timer
            timer = RegisterTimer(
                async o => { UnregisterTimer(timer); await action(); },
                null,
                TimeSpan.FromMilliseconds(1),
                TimeSpan.FromMilliseconds(-1));
        }
Beispiel #29
0
        protected override async Task OnActivateAsync()
        {
            VisualObject newObject = VisualObject.CreateRandom(this.Id.ToString());

            ActorEventSource.Current.ActorMessage(this, "StateCheck {0}", (await this.StateManager.ContainsStateAsync(StatePropertyName)).ToString());

            VisualObject result = await this.StateManager.GetOrAddStateAsync <VisualObject>(StatePropertyName, newObject);

            this.jsonString = result.ToJson();

            // ACTOR MOVEMENT REFRESH
            this.updateTimer = this.RegisterTimer(this.MoveObject, null, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(10));
            return;
        }
        protected override async Task OnActivateAsync()
        {
            VisualObject newObject = VisualObject.CreateRandom(this.Id.ToString());

            ActorEventSource.Current.ActorMessage(this, "StateCheck {0}", (await this.StateManager.ContainsStateAsync(StatePropertyName)).ToString());

            VisualObject result = await this.StateManager.GetOrAddStateAsync<VisualObject>(StatePropertyName, newObject);

            this.jsonString = result.ToJson();

            // ACTOR MOVEMENT REFRESH
            this.updateTimer = this.RegisterTimer(this.MoveObject, null, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(10));
            return;
        }
Beispiel #31
0
        public Task RegisterTimerAsync(int delayInSecond)
        {
            m_delayInSecond = delayInSecond;
            this.StateManager.SetStateAsync <int>("m_delayInSecond", m_delayInSecond);
            m_tc.TrackEvent($"RegisterTimerAsync - {this.GetActorId().ToString()}, {m_delayInSecond}");
            m_tc.Flush();
            if (m_WorkTimer != null)
            {
                UnregisterTimer(m_WorkTimer);
                m_WorkTimer = null;
            }

            m_WorkTimer = RegisterTimer(doWorkInTimerAsync, null, TimeSpan.FromSeconds(delayInSecond), TimeSpan.FromSeconds(delayInSecond));
            return(Task.FromResult <int>(0));
        }
Beispiel #32
0
        /// <summary>
        /// Starts the dispatcher with the given actor.
        /// </summary>
        /// <remarks>If the method has already been called previously, this new call will silently fail.</remarks>
        /// <param name="actor">The actor to run on.</param>
        /// <exception cref="ArgumentException">The specified actor is null.</exception>
        internal static void Run(IActor actor)
        {
            Enforce.ArgumentNotNull(actor, "actor");

            // Double-check pattern (1)
            if (m_actor != null)
                return;

            lock (m_syncLock)
            {
                // Double-check pattern (2)
                if (m_actor != null)
                    return;

                m_actor = actor;
                m_oneSecondTimer = actor.GetTimer(OnOneSecondTimerTick, 1000, true);
            }
        }
        protected override async Task OnActivateAsync()
        {
            try
            {
                await this.StateManager.TryAddStateAsync<Dictionary<int, ProductStockTrend>>("ProductStockTrends", new Dictionary<int, ProductStockTrend>());

                TimeSpan startDelay = TimeSpan.Parse(ConfigurationHelper.ReadValue("AppSettings", "PredictionTimerStartDelay"));
                TimeSpan interval = TimeSpan.Parse(ConfigurationHelper.ReadValue("AppSettings", "PredictionTimerInterval"));

                if (!int.TryParse(ConfigurationHelper.ReadValue("AppSettings", "PredictionNotificationAttempts"), out this.notificationAttempts))
                {
                    this.notificationAttempts = 10;
                }

                // register timer to regularly check for updates
                this.notificationTimer = this.RegisterTimer(
                    this.RunNotificationAsync,
                    null,
                    startDelay,
                    interval
                    );

                this.mlClient = AzureMlClientFactory.CreateClient();

                await base.OnActivateAsync();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, nameof(this.OnActivateAsync));
                throw;
            }
        }
Beispiel #34
0
        /// <summary>
        /// Shutdowns the dispatcher.
        /// </summary>
        internal static void Shutdown()
        {

            if (m_oneSecondTimer == null)
                return;

            m_oneSecondTimer.Stop();
            m_oneSecondTimer = null;
        }