Exemplo n.º 1
0
 private void RefreshTimer()
 {
     _timeoutCancelable?.Cancel();
     if (_timeoutTimeSpan != null)
     {
         _timeoutCancelable = ScheduleTimeoutMessage(_timeoutTimeSpan.Value);
     }
 }
Exemplo n.º 2
0
        private void ConnectToLobby()
        {
            _connectToLobbyCancellable?.Cancel();

            _connectToLobbyCancellable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(
                TimeSpan.Zero
                , TimeSpan.FromMilliseconds(RejoinLobbyTimeMilliseconds)
                , _playerLobby
                , RequestLobbyJoin.Instance
                , Self);
        }
Exemplo n.º 3
0
        /// <summary>Initializes a new instance of the <see cref="ThrottlerActor"/> class.</summary>
        /// <param name="interval">The interval.</param>
        /// <param name="numberOfMessages">The number of messages.</param>
        public ThrottlerActor(TimeSpan interval, uint numberOfMessages)
        {
            _interval         = interval;
            _numberOfMessages = numberOfMessages;
            Receive <Wrapper <TransformPhoneticTextMessage> >(
                message =>
            {
                InitTimerAndCounter();
                SendMessage(message);

                SetNextState();
            });

            Receive <MessageTimer>(t => { _cancelTimer?.Cancel(); });
        }
Exemplo n.º 4
0
 protected override void PostStop()
 {
     base.PostStop();
     Cluster.Unsubscribe(Self);
     aliveTask?.Cancel();
     refreshTask?.Cancel();
 }
        protected override void PostStop()
        {
            _recurringSnapshotCleanup?.Cancel();
            _recurringMessageSend?.Cancel();

            base.PostStop();
        }
Exemplo n.º 6
0
 protected override void PostStop()
 {
     _cancelable?.Cancel(false);
     _cancelToken?.Cancel(false);
     _cancelToken?.Dispose();
     base.PostStop();
 }
Exemplo n.º 7
0
        private bool Pausing(object message)
        {
            switch (message)
            {
            case Paused _:
                schedule = null;
                if (TotalDemand > 0L)
                {
                    Read();
                    Context.Become(Reading);
                }
                else
                {
                    Context.Become(Waiting);
                }
                return(true);

            case Written w:
                schedule?.Cancel();
                schedule = null;
                if (TotalDemand > 0L)
                {
                    Read();
                    Context.Become(Reading);
                }
                else
                {
                    Context.Become(Waiting);
                }
                return(true);

            default: return(false);
            }
        }
Exemplo n.º 8
0
        protected override void PostStop()
        {
            var self = Self;

            Cluster.Unsubscribe(Self);
            _currentClusterStateTeller?.Cancel(false);
            SystemActors.Mediator.Tell(new Unsubscribe(Topics.Status, self));
        }
Exemplo n.º 9
0
 private void stopWait()
 {
     if (_timeStarted)
     {
         _timeStarted = false;
         _timerTask?.Cancel();
     }
 }
Exemplo n.º 10
0
        public EvenlyThrottlerActor(TimeSpan interval, uint messageCount)
        {
            _interval            = interval;
            _messageCount        = messageCount;
            _messageSendInterval = TimeSpan.FromMilliseconds(_interval.TotalMilliseconds / _messageCount);
            Receive <Wrapper <string> >(
                message =>
            {
                SetTimers();
                SendMessage(message);
                Become(WaitingForTrigerToSendNextMessage);
            });

            Receive <ResetCounterTimer>(h => { _counterTimerCancel?.Cancel(); });

            Receive <MessageTimer>(m => { _messageTimerCancel?.Cancel(); });
        }
Exemplo n.º 11
0
        static int Main(string[] args)
        {
            var sqlConnectionString = Environment.GetEnvironmentVariable("SQL_CONNECTION_STR");
            var sqlHostName         = Environment.GetEnvironmentVariable("SQL_HOSTNAME");

            if (string.IsNullOrEmpty(sqlConnectionString) || string.IsNullOrEmpty(sqlHostName))
            {
                Console.WriteLine("ERROR! No SQL Connection String specified. Exiting with code -1");
                return(-1);
            }

            //var hostIp = Dns.GetHostEntry(sqlHostName);
            //sqlConnectionString = sqlConnectionString.Replace("{HOSTNAME}", hostIp.AddressList.First().ToString());
            Console.WriteLine("Connecting to SQL Server via {0}", sqlConnectionString);

            var config = ConfigurationFactory.ParseString(File.ReadAllText("sharding.hocon"));

            var sqlHocon = "akka.persistence.journal.sql-server.connection-string = \"" + sqlConnectionString + "\"" +
                           Environment.NewLine +
                           "akka.persistence.snapshot-store.sql-server.connection-string = \"" + sqlConnectionString +
                           "\"";

            Console.WriteLine("Using SQL Hocon:" + Environment.NewLine + " {0}", sqlHocon);

            var sqlConnectionConfig = ConfigurationFactory.ParseString(sqlHocon)
                                      .WithFallback(config);

            var actorSystem = ActorSystem.Create("ShardFight", sqlConnectionConfig.BootstrapFromDocker().WithFallback(ClusterSharding.DefaultConfig()));

            ICancelable shardTask = null;

            Cluster.Get(actorSystem).RegisterOnMemberUp(() =>
            {
                var sharding            = ClusterSharding.Get(actorSystem);
                IActorRef myShardRegion = sharding.Start("entities", str => Props.Create(() => new PersistentEntityActor(str)),
                                                         ClusterShardingSettings.Create(actorSystem).WithRole("shard"), new FuberMessageExtractor());

                shardTask = actorSystem.Scheduler.Advanced.ScheduleRepeatedlyCancelable(TimeSpan.FromMilliseconds(250),
                                                                                        TimeSpan.FromMilliseconds(250),
                                                                                        () =>
                {
                    myShardRegion.Tell(new FuberEnvelope(ThreadLocalRandom.Current.Next(0, 100000).ToString(), ThreadLocalRandom.Current.Next().ToString()));
                });
            });

            var pbm = PetabridgeCmd.Get(actorSystem);

            pbm.RegisterCommandPalette(ClusterCommands.Instance);         // enable cluster management commands
            pbm.RegisterCommandPalette(ClusterShardingCommands.Instance); //enable cluster.sharding management commands
            pbm.Start();

            actorSystem.WhenTerminated.Wait();
            shardTask?.Cancel(); // should already be cancelled
            return(0);
        }
Exemplo n.º 12
0
        protected override void PostStop()
        {
            ValidateFolderAndSettings?.Cancel(false);
            _watcher?.Dispose();
            var self = Self;

            Context.ActorSelection("/user/DatabaseWatcher").Tell(new UnSubscribeToObjectChanges(self));
            LogToEverything(Context, $"FileSystemWatcher has stopped monitoring {_folderPath.FullName.ToString()}");

            _watcher = null;
            base.PostStop();
        }
Exemplo n.º 13
0
        public ClusterReadinessProbe(ReadinessStatus readinessStatus)
        {
            _readinessStatus = readinessStatus;

            Receive <ReadinessStatus>(s =>
            {
                _readinessStatus = s;
                foreach (var sub in _subscribers)
                {
                    sub.Tell(s);
                }
            });

            Receive <GetCurrentReadiness>(_ => Sender.Tell(_readinessStatus));

            Receive <SubscribeToReadiness>(s =>
            {
                _subscribers.Add(s.Subscriber);
                Context.Watch(s.Subscriber);
                s.Subscriber.Tell(_readinessStatus);
            });

            Receive <UnsubscribeFromReadiness>(u =>
            {
                _subscribers.Remove(u.Subscriber);
                Context.Unwatch(u.Subscriber);
            });

            Receive <Terminated>(t => { _subscribers.Remove(t.ActorRef); });

            Receive <ClusterEvent.UnreachableMember>(r =>
            {
                if (_cluster.State.Unreachable.SetEquals(_cluster.State.Members.Remove(_cluster.SelfMember)))
                {
                    if (_notReadyTask == null)
                    {
                        _notReadyTask = Context.System.Scheduler.ScheduleTellOnceCancelable(TimeSpan.FromSeconds(20),
                                                                                            Self,
                                                                                            new ReadinessStatus(false, "everyone else is unreachable"), ActorRefs.NoSender);
                    }
                }
            });

            Receive <ClusterEvent.ReachableMember>(r =>
            {
                // someone else has become reachable again. Can abort "not ready" task if it was already running
                _notReadyTask?.Cancel();
            });
        }
Exemplo n.º 14
0
 protected override void PostStop()
 {
     try
     {
         _cancelPublishing?.Cancel(false);
         _counter?.Dispose();
     }
     catch
     {
     }
     finally
     {
         base.PostStop();
     }
 }
Exemplo n.º 15
0
 protected override void PostStop()
 {
     try
     {
         _cancelFetching?.Cancel(false);
     }
     catch
     {
         // oh well... on ne se préoccupe pas des autres exceptions
     }
     finally
     {
         base.PostStop();
     }
 }
 protected override void PostStop()
 {
     try
     {
         // terminate the scheduled message
         _cancelPublishing?.Cancel(false);
         // and dispose of the performance counter
         _counter?.Dispose();
     }
     catch
     {
         // ignore any disposal exceptions
     }
     finally
     {
         base.PostStop();
     }
 }
Exemplo n.º 17
0
        private void Terminate(State <TState, TData, TEvent> upcomingState)
        {
            if (_currentState.StopReason == null)
            {
                var reason = upcomingState.StopReason;
                LogTermination(reason);
                foreach (var t in _timers)
                {
                    t.Value.Cancel();
                }
                _timers.Clear();
                _timeoutFuture?.Cancel();
                _currentState = upcomingState;

                var stopEvent = new FSMBase.StopEvent <TState, TData>(reason, _currentState.StateName, _currentState.StateData);
                _terminateEvent(stopEvent);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        ///     Start periodic polling using the specified <see cref="Signal"/>.
        /// </summary>
        /// <param name="pollSignal">
        ///     A <see cref="Signal"/> value indicating the type of polling to perform.
        /// </param>
        void StartPolling(Signal pollSignal)
        {
            _timeoutCancellation?.Cancel();
            _pollCancellation?.Cancel();

            _pollCancellation = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(
                initialDelay: TimeSpan.FromSeconds(1),
                interval: PollPeriod,
                receiver: Self,
                message: pollSignal,
                sender: Self
                );
            _timeoutCancellation = Context.System.Scheduler.ScheduleTellOnceCancelable(
                delay: PollTimeout,
                receiver: Self,
                message: pollSignal,
                sender: Self
                );
        }
Exemplo n.º 19
0
        private async ValueTask TriggerRedelivery()
        {
            if (_nackedMessages.Count == 0)
            {
                _timeout?.Cancel();
                _timeout = null;
                return;
            }

            var messagesToRedeliver = new HashSet <IMessageId>();
            var now = DateTimeHelper.CurrentUnixTimeMillis();

            foreach (var unack in _nackedMessages)
            {
                if (unack.Value < now)
                {
                    var ids = await _unack.Ask <UnAckedChunckedMessageIdSequenceMapCmdResponse>(new UnAckedChunckedMessageIdSequenceMapCmd(UnAckedCommand.Get, new List <IMessageId> {
                        unack.Key
                    }));

                    foreach (var i in ids.MessageIds)
                    {
                        messagesToRedeliver.Add(i);
                    }

                    messagesToRedeliver.Add(unack.Key);
                    _unack.Tell(new UnAckedChunckedMessageIdSequenceMapCmd(UnAckedCommand.Remove, new List <IMessageId> {
                        unack.Key
                    }));
                }
            }

            _log.Info($"Number of Negatively Accked Messages to be Redelivered: {messagesToRedeliver.Count}");
            messagesToRedeliver.ForEach(i => _nackedMessages.Remove(i));
            _consumer.Tell(new OnNegativeAcksSend(messagesToRedeliver));
            _consumer.Tell(new RedeliverUnacknowledgedMessageIds(messagesToRedeliver));

            _timeout = Context.System.Scheduler.ScheduleTellOnceCancelable(TimeSpan.FromMilliseconds(_timerIntervalMs), Self, Trigger.Instance, ActorRefs.NoSender);
        }
Exemplo n.º 20
0
 private void ResetStabilityTimeout()
 {
     _stabilityTask?.Cancel();
     _stabilityTask = Context.System.Scheduler.ScheduleTellOnceCancelable(_stabilityTimeout, Self, StabilityReached.Instance, ActorRefs.NoSender);
 }
Exemplo n.º 21
0
 protected override void PostStop()
 {
     _cancelTimer?.Cancel();
     base.PostStop();
 }
Exemplo n.º 22
0
 protected override void PostStop()
 {
     base.PostStop();
     restartTask?.Cancel();
     consul.Dispose();
 }
Exemplo n.º 23
0
 /// <summary>
 /// TBD
 /// </summary>
 public void Cancel()
 {
     // need a null check here, in case actor is terminated before StartRedeliverTask() is called
     _redeliverScheduleCancelable?.Cancel();
     _redeliverScheduleCancelable = null;
 }
Exemplo n.º 24
0
        private bool Establishing(object message)
        {
            ICancelable connectTimerCancelable = null;

            if (_settings.ReconnectTimeout.HasValue)
            {
                connectTimerCancelable = Context.System.Scheduler.ScheduleTellOnceCancelable(
                    _settings.ReconnectTimeout.Value,
                    Self,
                    ReconnectTimeout.Instance,
                    Self);
            }

            if (message is ClusterReceptionist.Contacts)
            {
                var contacts = (ClusterReceptionist.Contacts)message;

                if (contacts.ContactPoints.Count > 0)
                {
                    _contactPaths = contacts.ContactPoints.Select(ActorPath.Parse).ToImmutableHashSet();
                    _contacts     = _contactPaths.Select(Context.ActorSelection).ToArray();
                    _contacts.ForEach(c => c.Tell(new Identify(null)));
                }

                PublishContactPoints();
            }
            else if (message is ActorIdentity)
            {
                var actorIdentify = (ActorIdentity)message;
                var receptionist  = actorIdentify.Subject;

                if (receptionist != null)
                {
                    _log.Info("Connected to [{0}]", receptionist.Path);
                    ScheduleRefreshContactsTick(_settings.RefreshContactsInterval);
                    SendBuffered(receptionist);
                    Context.Become(Active(receptionist));
                    connectTimerCancelable?.Cancel();
                    _failureDetector.HeartBeat();
                }
                else
                {
                    // ok, use another instead
                }
            }
            else if (message is HeartbeatTick)
            {
                _failureDetector.HeartBeat();
            }
            else if (message is RefreshContactsTick)
            {
                SendGetContacts();
            }
            else if (message is Send)
            {
                var send = (Send)message;
                Buffer(new PublishSubscribe.Send(send.Path, send.Message, send.LocalAffinity));
            }
            else if (message is SendToAll)
            {
                var sendToAll = (SendToAll)message;
                Buffer(new PublishSubscribe.SendToAll(sendToAll.Path, sendToAll.Message));
            }
            else if (message is Publish)
            {
                var publish = (Publish)message;
                Buffer(new PublishSubscribe.Publish(publish.Topic, publish.Message));
            }
            else if (message is ReconnectTimeout)
            {
                _log.Warning("Receptionist reconnect not successful within {0} stopping cluster client", _settings.ReconnectTimeout);
                Context.Stop(Self);
            }
            else
            {
                return(ContactPointMessages(message));
            }

            return(true);
        }
Exemplo n.º 25
0
 /// <summary>
 /// If <paramref name="cancelable"/> is not <c>null</c> it's canceled.
 /// </summary>
 /// <param name="cancelable">The cancelable. Will be canceled if it's not <c>null</c></param>
 public static void CancelIfNotNull(this ICancelable cancelable)
 {
     cancelable?.Cancel();
 }
Exemplo n.º 26
0
 protected override void PostStop()
 {
     _publishPricesTask?.Cancel();
     base.PostStop();
 }
Exemplo n.º 27
0
        private void Working()
        {
            _cancelable = Context.System.Scheduler
                .ScheduleTellRepeatedlyCancelable(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(5), Self, "Hello World!", Self);

            Receive<string>(msg =>
            {
                if (msg == "stop")
                {
                    _cancelable.Cancel();
                    Logger.Info("Scheduler stoped.");
                    Become(Wait);
                }
                else
                {
                    Logger.Trace(msg);
                }
            });
        }
 protected override void PostStop()
 {
     _cancelToken?.Cancel();
     Context.System.EventStream.Unsubscribe(Context.Self);
     base.PostStop();
 }
Exemplo n.º 29
0
 protected override void PostStop()
 {
     _heartbeatInterval?.Cancel();
 }
 private void StreamConnectedMsgHandler(StreamConnectedMsg msg)
 {
     _startStreamingNotResponding?.Cancel();
     _startStreamingNotResponding = null;
 }
Exemplo n.º 31
0
 /// <inheritdoc />
 /// <summary>
 ///     Cancels the pruning task on the scheduler.
 /// </summary>
 protected override void PostStop()
 {
     _pruneTask?.Cancel();
     base.PostStop();
 }