Пример #1
0
        private Receive Connected(IActorRef connection)
        {
            connection.Tell(new Tcp.Register(Self));
            connection.Tell(Tcp.Write.Create(MessageSeriliazer.Serialize(Context.System, new Signal.Join(_hub))));

            return message =>
            {
                var received = message as Tcp.Received;
                if (received != null)
                {
                    var messages = MessageSeriliazer.Deserialize(Context.System, received.Data);
                    messages.ForEach(_handler.Tell);
                    return true;
                }
                
                var closed = message as Tcp.ConnectionClosed;
                if (closed != null)
                {
                    _handler.Tell(new Signal.Disconnected());
                    Become(Reconnecting());
                    return true;
                }

                if (Sender == _handler)
                {
                    connection.Tell(WriteObject(new Signal.Broadcast(_hub, message)));
                    return true;
                }

                return false;
            };
        }
        /// <summary>
        ///		Create a new <see cref="ButtonToggler"/> actor.
        /// </summary>
        /// <param name="performanceCountersController">
        ///		The actor that controls the <see cref="PerformanceCounterMonitor"/>s for various performance counters.
        /// </param>
        /// <param name="button">
        ///		The button controlled by the <see cref="ButtonToggler"/>.
        /// </param>
        /// <param name="counterType">
        ///		The type of performance counter represented by the button.
        /// </param>
        /// <param name="isToggled">
        ///		Is the button currently toggled ("On")?
        /// </param>
        public ButtonToggler(IActorRef performanceCountersController, Button button, CounterType counterType, bool isToggled = false)
        {
            if (performanceCountersController == null)
                throw new ArgumentNullException("performanceCountersController");

            if (button == null)
                throw new ArgumentNullException("button");

            if (counterType == CounterType.Unknown)
                throw new ArgumentOutOfRangeException(nameof(counterType), counterType, "Invalid performance counter type.");

            _performanceCountersController = performanceCountersController;
            _button = button;
            _counterType = counterType;
            _isToggled = isToggled;

            Receive<Toggle>(_ =>
            {
                if (Flip())
                {
                    _performanceCountersController.Tell(
                        new WatchCounterValue(_counterType)
                    );
                }
                else
                {
                    _performanceCountersController.Tell(
                        new UnwatchCounterValue(_counterType)
                    );
                }
            });
        }
Пример #3
0
        public Manager(ProgramOptions options)
        {
            this.options = options;
            summary      = new Summary(options.NrRequests);

            Receive <WantWork>(_ => DispatchWork());
            Receive <Result>(r => SaveResult(r));
            Receive <Start>(_ => StartDownloading());

            statusReporter  = Context.ActorOf(Props.Create <StatusReporter>(), "status");
            verboseReporter = options.Verbose ? statusReporter : null;

            verboseReporter?.Tell("Starting up...");
            statusReporter.Tell(summary);

            downloaders = new List <IActorRef>();
            for (var i = 1; i <= options.Concurrency; i++)
            {
                verboseReporter?.Tell($"Starting Downloader #{i}...");
                downloaders.Add(
                    Context.ActorOf(
                        Props.Create <Downloader>(Self, verboseReporter),
                        $"{DownloadAgentPrefix}{i}"
                        )
                    );
            }
        }
Пример #4
0
        public Hub(IActorRef handler)
        {
            _handler = handler;

            Receive<Signal.Join>(join =>
            {
                if (!_clients.TryAdd(Sender, out _clients))
                    return;

                var joined = new Signal.Joined(Sender.Path.Name, Self.Path.Name);
                Self.Tell(new Signal.Broadcast("self", joined));

                _handler.Tell(joined);
            });

            Receive<Signal.Leave>(leave =>
            {
                if (!_clients.TryRemove(Sender, out _clients))
                    return;

                var left = new Signal.Left(Sender.Path.Name, Self.Path.Name);
                Self.Tell(new Signal.Broadcast("self", left));

                _handler.Tell(left);
            });

            Receive<Signal.Broadcast>(broadcast =>
            {
                var message = WriteObject(broadcast.Message);
                foreach (var client in _clients)
                    client.Tell(message);
            });

            ReceiveAny(o => Self.Forward(new Signal.Broadcast("self", o)));
        }
Пример #5
0
        public SignalRBridgeActor(IGameEventsPusher gameEventsPusher, IActorRef gameController)
        {
            _gameEventsPusher = gameEventsPusher;
            _gameController = gameController;

            Receive<JoinGameMessage>(
                message =>
                {
                    _gameController.Tell(message);
                });

            Receive<AttackPlayerMessage>(
                message =>
                {
                    _gameController.Tell(message);
                });

            Receive<PlayerStatusMessage>(
                message =>
                {
                    _gameEventsPusher.PlayerJoined(message.PlayerName, message.Health);
                });

            Receive<PlayerHealthChangedMessage>(
                message =>
                {
                    _gameEventsPusher.UpdatePlayerHealth(message.PlayerName, message.Health);
                });
        }
Пример #6
0
        private Receive Binding(EndPoint endPoint, IActorRef sender)
        {
            Context.System.Tcp().Tell(new Tcp.Bind(Self, endPoint));

            return message =>
            {
                var failed = message as Tcp.CommandFailed;
                if (failed != null)
                {
                    _log.Error($"Could not bind to endpoint {endPoint}. Reason: {failed.Cmd.FailureMessage}");
                    sender.Tell(new Signal.BindingFailed(endPoint, failed.Cmd.FailureMessage.ToString()));
                    Context.Stop(Self);
                    return true;
                }

                var bound = message as Tcp.Bound;
                if (bound != null)
                {
                    _log.Info($"Listening on {bound.LocalAddress}");
                    sender.Tell(new Signal.Bound(endPoint));
                    Become(Bound);
                    return true;
                }

                Stash.Stash();
                return true;
            };

        }
Пример #7
0
 public ClientReceiveActor(IActorRef 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));
 }
Пример #8
0
            public WriteAckAdapter(IActorRef replica)
            {
                IActorRef replicator = null;

                Receive <WriteAck>(ack => replicator?.Tell(ack));
                Receive <WriteNack>(ack => replicator?.Tell(ack));
                Receive <DeltaNack>(ack => replicator?.Tell(ack));
                ReceiveAny(msg =>
                {
                    replicator = Sender;
                    replica.Tell(msg);
                });
            }
Пример #9
0
        private static void StressPersistentActor(IActorRef pref, long? failAt, string description)
        {
            if (failAt.HasValue) pref.Tell(new FailAt(failAt.Value));

            var m = new Measure(LoadCycles);
            m.StartMeasure();

            for (int i = 1; i <= LoadCycles; i++) pref.Tell("msg" + i);

            pref.Ask(StopMeasure.Instance, TimeSpan.FromSeconds(100)).Wait();
            var ratio = m.StopMeasure();
            Console.WriteLine("Throughtput: {0} {1} per second", ratio, description);
        }
Пример #10
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");
        }
Пример #11
0
        public FixInterpreterTests()
        {
            var actorSystem = ActorSystem.Create("System");

            var props = Props.Create(() => new FixInterpreterActor(new FakeFixParser()));
            _fixInterpreterActor = actorSystem.ActorOf(props);

            _serverActor = CreateTestProbe("Server");
            _clientActor = CreateTestProbe("Client");

            _fixInterpreterActor.Tell(new FixInterpreterActor.SetServer(_serverActor));
            _fixInterpreterActor.Tell(new FixInterpreterActor.SetClient(_clientActor));
        }
Пример #12
0
        public void Handle(IMessage m)
        {
            if (m.GetType() == typeof(connect))
            {
                (new Thread(() => connect((m as connect).host, (m as connect).port))).Start();
            }
            else if (m.GetType() == typeof(disconnect))
            {
                if (client_.socket.IsConnected())
                {
                    logger_?.Tell(new log("aborting connection", logType.info, verbosity.high));

                    // connect
                    client_.socket.eDisconnect();
                }
            }
            else if (m.GetType() == typeof(connectionStatus))
            {
                if (client_.socket.IsConnected())
                {
                    Sender.Tell(new connectionStatus(true), Self);
                }
            }
            else if (m.GetType() == typeof(historicalDataManager.request))
            {
                if (client_.socket.IsConnected())
                {
                    var temp = (m as historicalDataManager.request);

                    if (temp.correlation != null)
                    {
                        client_.socket.reqHistoricalData(
                            temp.correlation.id,
                            temp.contract,
                            temp.endDatetime.ToString("yyyyMMdd"),
                            temp.duration.ToString(),
                            temp.barSize.ToString(),
                            temp.type.ToString(),
                            temp.useRTH,
                            temp.formatDate,
                            null);
                    }
                }
            }
            else if (m.GetType() == typeof(registration))
            {
                // pass-through
                dispatcher_?.Forward(m);
            }
        }
Пример #13
0
        public HubProxy(IActorRef handler)
        {
            _handler = handler;

            Receive<Signal.Join>(join =>
            {
                Sender.Tell(WriteObject(new Signal.Joined(Sender.Path.Name, Self.Path.Name, true)));

                //Client hasn't received the previous joined message so we don't need to forward it again to the other clients
                if (_clientDictionary.ContainsKey(Sender.Path.Name))
                    return;

                var joined = new Signal.Joined(Sender.Path.Name, Self.Path.Name);
                var joinedSerialized = WriteObject(joined);
                foreach (var client in _clientDictionary.Values)
                    client.Tell(joinedSerialized);

                _handler.Tell(joined);

                _clientDictionary[Sender.Path.Name] = Sender;
            });

            Receive<Signal.Leave>(leave =>
            {
                if (_clientDictionary.ContainsKey(Sender.Path.Name))
                    _clientDictionary.Remove(Sender.Path.Name);

                var left = new Signal.Left(Sender.Path.Name, Self.Path.Name);
                Self.Tell(new Signal.Broadcast("self", left));

                _handler.Tell(left);
            });

            Receive<Signal.Broadcast>(broadcast =>
            {
                var message = WriteObject(broadcast.Message);
                if (broadcast.ClientId == null)
                {
                    foreach (var client in _clientDictionary.Values)
                        client.Tell(message);
                }
                else if (_clientDictionary.ContainsKey(broadcast.ClientId))
                {
                    _clientDictionary[broadcast.ClientId].Tell(message);
                }
            });

            Receive<Signal.ClientBroadcast>(broadcast => _handler.Tell(broadcast));
        }
Пример #14
0
        public StockActor(string stockSymbol)
        {
            _stockSymbol = stockSymbol;
            _subscribers = new HashSet<IActorRef>();

            _priceLookupChild = Context.ActorOf(Context.DI().Props<StockPriceLookupActor>());

            Receive<SubscribeToNewStockPricesMessage>(message => _subscribers.Add(message.Subscriber));
            Receive<UnSubscribeFromNewStockPricesMessage>(message => _subscribers.Remove(message.Subscriber));

            Receive<RefreshStockPriceMessage>(message => _priceLookupChild.Tell(message));

            Receive<UpdatedStockPriceMessage>(message =>
            {
                _stockPrice = message.Price;

                var stockPriceMessage = new StockPriceMessage(_stockSymbol, _stockPrice, message.Date);

                foreach (var subscriber in _subscribers)
                {
                    subscriber.Tell(stockPriceMessage);
                }
            });

        }
Пример #15
0
        public ModuleManagerActor(IActorRef uiActor)
        {
            _uiActor = uiActor;
            _modules = new Dictionary<string, IActorRef>();

            Receive<Messages.IncrementerMessage>(x =>
            {
                foreach (var mod in _modules)
                    mod.Value.Tell(x.Data);
            });

            Receive<Messages.InitModuleMessage>(x =>
            {
                _modules[x.Name] = x.ModuleActor;
                _uiActor.Tell(x);
            });

            Receive<Messages.RequestClose>(x =>
            {
                bool result = true;
                foreach (var m in _modules)
                    if (!m.Value.Ask<bool>(x).Result)
                        result = false;
                Sender.Tell(result);
            });
        }
Пример #16
0
        private void Main_Load(object sender, EventArgs e)
        {
            _chartActor = Program.ChartActors.ActorOf(Props.Create(() => new ChartingActor(sysChart, btnPauseResume)), "charting");
            _chartActor.Tell(new ChartingActor.InitializeChart(null)); //no initial series

            _coordinatorActor = Program.ChartActors.ActorOf(Props.Create(() =>
                    new PerformanceCounterCoordinatorActor(_chartActor)), "counters");

            // CPU button toggle actor
            _toggleActors[CounterType.Cpu] = Program.ChartActors.ActorOf(
                Props.Create(() => new ButtonToggleActor(_coordinatorActor, btnCPU, CounterType.Cpu, false))
                    .WithDispatcher("akka.actor.synchronized-dispatcher"));

            // MEMORY button toggle actor
            _toggleActors[CounterType.Memory] = Program.ChartActors.ActorOf(
               Props.Create(() => new ButtonToggleActor(_coordinatorActor, btnMemory, CounterType.Memory, false))
                   .WithDispatcher("akka.actor.synchronized-dispatcher"));

            // DISK button toggle actor
            _toggleActors[CounterType.Disk] = Program.ChartActors.ActorOf(
               Props.Create(() => new ButtonToggleActor(_coordinatorActor, btnDisk, CounterType.Disk, false))
                   .WithDispatcher("akka.actor.synchronized-dispatcher"));

            // Set the CPU toggle to ON so we start getting some data
            _toggleActors[CounterType.Cpu].Tell(new ButtonToggleActor.Toggle());
        }
Пример #17
0
        public ChatConsoleActor(IActorRef userManager, IActorRef chatRoomManager)
        {
            _userManager     = userManager;
            _chatRoomManager = chatRoomManager;
            _commandHandler  = new CommandHandler();

            RegisterEvents();

            Receive <SendConsoleLine>(message =>
            {
                if (_commandHandler.ContainsCommand(message.Text))
                {
                    _commandHandler.HandleCommands(message.Text);
                }
                else
                {
                    _chatRoom?.Tell(new SendMessage(_user, message.Text));
                }
            });

            Receive <UserLoggedIn>(message =>
            {
                _user = message.User;
                Log.Info($"User '{message.User}' logged in.");
            });

            Receive <ChatJoined>(message =>
            {
                _chatRoom = message.ChatRoom;
                Log.Info($"User joined chat '{message.ChatRoom}'.");
            });
        }
Пример #18
0
            public Actor1NonAsync(IActorRef testActor)
            {
                _testActor = testActor;
                Receive<string>(m => { _testActor.Tell(m); });

                Context.ActorOf(Props.Create<Actor2>(), "actor-2");
            }
Пример #19
0
        public Master()
        {
            mapper = Context.ActorOf(
                Props.Create<Mapper>()

                .WithRouter(new RoundRobinPool(NrMappers))
            );
            reducer = Context.ActorOf(
                Props.Create<Reducer>()
                     .WithRouter(new RoundRobinPool(NrReducers))
            );
            aggregator = Context.ActorOf(Props.Create<Aggregator>());

            // 1. forward a string to mapper
            Receive<string>(s => mapper.Tell(s));

            // 2. forward map result to reducer
            Receive<MapResult>(m => reducer.Tell(m));

            // 3. forward reduce result to aggregator
            Receive<ReduceResult>(r => aggregator.Tell(r));

            // allow asking for aggregated result at any time
            Receive<GetResult>(g => aggregator.Forward(g));
        }
        public PerformanceCounterCoordinatorActor(IActorRef chartingActor,
            Dictionary<CounterType, IActorRef> counterActors)
        {
            _counterActors = counterActors;
            _chartingActor = chartingActor;

            Receive<Watch>(watch =>
            {
                if (!_counterActors.ContainsKey(watch.Counter))
                {
                    var counterActor =
                        Context.ActorOf(
                            Props.Create(
                                () =>
                                    new PerformanceCounterActor(watch.Counter.ToString(),
                                        CounterGenerators[watch.Counter])));
                    _counterActors[watch.Counter] = counterActor;
                }

                _chartingActor.Tell(new ChartingActor.AddSeries(CounterSeries[watch.Counter]()));

                _counterActors[watch.Counter].Tell(new SubscribeCounter(watch.Counter, _chartingActor));
            });

            Receive<Unwatch>(unwatch =>
            {
                if (!_counterActors.ContainsKey(unwatch.Counter))
                {
                    return;
                }

                _counterActors[unwatch.Counter].Tell(new UnsubscribeCounter(unwatch.Counter, _chartingActor));
                _chartingActor.Tell(new ChartingActor.RemoveSeries(unwatch.Counter.ToString()));
            });
        }
 public UserSessionActor(User user, IActorRef presence)
 {
     User = user;
     Presence = presence;
     Presence.Tell(new RegisterUser(Self));
     Receives();
 }
Пример #22
0
        public AggregatorActor(IActorRef presenter)
        {
            var set = new Dictionary<string, Taxi.PositionBearing>();
            Context.System.Scheduler.ScheduleTellRepeatedly(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5), Self,
                "foo", Self);

            Receive<string>(_ =>
            {
                var groups = set.Values.GroupBy(p => new
                {
                    Longitude = 0.5 + (int) p.Longitude,
                    Latitude = 0.5 + (int) p.Latitude
                }).ToList();

                foreach (var group in groups)
                {
                    presenter.Tell(new AggregatedData(group.Count(), group.Key.Latitude, group.Key.Longitude));
                }

                set.Clear();
            });
            Receive<Taxi.PositionBearing>(p =>
            {
                set.Remove(p.Id);
                set.Add(p.Id, p);
            });
        }
Пример #23
0
        public RequestProducer(int numberOfWorkers, string[] uris)
        {
            this.numberOfWorkers = numberOfWorkers;
            this.uris = uris;
            logger = Context.ActorOf<RequestLogger>("consoleLogger");

            Receive<NewWorker>(worker =>
            {
                log.Debug("Adding http request worker: {Worker}", Sender);
                //Console.WriteLine("Adding worker: " + Sender.Path);
                workers.Add(Sender);
                RequestHttpWork(Sender);
            });

            Receive<Result>(worker =>
            {
                logger.Tell(worker);
                RequestHttpWork(Sender);
            });

            Receive<StopGenerationOfRequests>(stop =>
            {
                Task.WaitAll(workerPool.GracefulStop(TimeSpan.FromSeconds(60)), logger.GracefulStop(TimeSpan.FromSeconds(60)));

                Sender.Tell("Done", Self);
            });
        }
        public LineReaderActor(IWriteStuff writer)
        {
            _writer = writer;
            _wordAggregator = Context.ActorOf(WordCountAggregatorActor.Create(writer), "aggregator");

            Receive<ReadLineForCounting>(msg =>
            {
                var cleanFileContents = Regex.Replace(msg.Line, @"[^\u0000-\u007F]", " ");

                var wordArray = cleanFileContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var word in wordArray)
                {
                    var wordCounter = Context.Child(word);
                    if (wordCounter == ActorRefs.Nobody)
                    {
                        wordCounter = Context.ActorOf(WordCounterActor.Create(_writer, _wordAggregator, word), word);
                    }

                    wordCounter.Tell(new CountWord());
                }
            });

            Receive<Complete>(msg =>
            {
                var childCount = -1;    //TODO: doesn't work with 0
                var children = Context.GetChildren();

                foreach (var child in children)
                {
                    child.Tell(new DisplayWordCount());
                    childCount++;
                }
                _wordAggregator.Tell(new TotalWordCount(childCount));
            });
        }
Пример #25
0
        /// <summary>
        /// Handle file processing message.
        /// Actor will count one file.
        /// </summary>
        /// <param name="message"></param>
        public void Handle( FileToProcess message )
        {
            IncrementMessagesReceived();

            lineCount = 0;
            linesProcessed = 0;
            result = 0;
            m_sw.Start();
            fileName = message.FileName;
            router = Context.ActorOf( new RoundRobinPool(8).Props( StringCounterActor.GetProps() ), String.Format( "liner{0}", message.Fileno ) );
            //var router = Context.ActorOf( StringCounterActor.GetProps(), String.Format( "liner{0}", message.Fileno ) );
            try
            {
                foreach ( var line in File.ReadLines( fileName ) )
                {
                    lineCount++;
                    router.Tell( new ProcessLine( line, lineCount ) );
                }
            }
            catch ( Exception ex )
            {
                Sender.Tell( new FailureMessage( ex, Self ) );
            }

            // handle when file is empty
            if ( lineCount == 0 )
            {
                Sender.Tell( new CompletedFile( fileName, result, lineCount, 0 ) );
            }
        }
Пример #26
0
        private static async void RunFetchLoopAsync(IActorRef publisher, string url, string source)
        {
            await Task.Yield();
            try
            {
                var c = new WebClient();
                while (true)
                {
                    var data = await c.DownloadDataTaskAsync(new Uri(url));
                    var str = Encoding.UTF8.GetString(data);
                    dynamic res = JsonConvert.DeserializeObject(str);
                    //   Console.WriteLine("Downloaded {0}",url);

                    foreach (var bus in res)
                    {
                        string id = bus.ID;
                        double lat = bus.Latitude;
                        double lon = bus.Longitude;

                        publisher.Tell(new Presenter.Position(lon, lat, id, source));
                    }

                    //how long should we wait before polling again?
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }
            catch
            {
                Console.WriteLine("Missing Route {0}", url);
            }
        }
        public ObserveWindowViewModel( string filename, IActorRef tailCoordinator )
        {
            _tailCoordinator = tailCoordinator;
            Filename = filename;
            Title = filename;
            Items = new ReactiveList<String>();

            // start coordinator
            _tailCoordinator.Tell( new TailCoordinatorActor.StartTail( filename, this ) );

            // this is how we can update the viewmodel
            // from the actor.
            Lines = new Subject<String>();
            Lines.ObserveOnDispatcher().Subscribe( item =>
            {
                Items.Add( item );

                if ( Items.Count > 1500 )
                {
                    Items.RemoveAt( 0 );
                }

                SelectedLine = Items.Count - 1;

            } );
        }
Пример #28
0
 public DeadLetterSupressionSpec()
 {
     deadActor = Sys.ActorOf(Props.Create<EchoActor>());
     Watch(deadActor);
     deadActor.Tell(PoisonPill.Instance);
     ExpectTerminated(deadActor);
 }
Пример #29
0
 private void ForwardMessages(BufferedMessages messages, IActorRef recipient)
 {
     messages.ForEach(c =>
     {
         recipient.Tell(c.Key, c.Value);
     });
 }
Пример #30
0
 protected override void PostStop()
 {
     timer.CancelIfNotNull();
     ws_host?.Dispose();
     tcp_listener?.Tell(Tcp.Unbind.Instance);
     base.PostStop();
 }
Пример #31
0
        public GenericDBEntity(string entityType, long id)
        {
            _entityChangeNotificationActor = Context.System.ActorSelection($"/user/EntityChangeNotificationRootActor/{entityType}").ResolveOne(TimeSpan.FromSeconds(1)).Result;

            var entityAssembly = Assembly.GetAssembly(typeof(IModelObject)); // Removed DTOs - ModelObject = ef entity
            var allEntityTypes = entityAssembly.GetTypes().ToList();

            EntityType = allEntityTypes.FirstOrDefault(t => t.Name == entityType);
            Id = id;

            _modelObject = LoadEntityFromDb();

            Receive<UpdateEntityRequest>(message =>
            {
                _undoStack.Push(_modelObject);

                _modelObject = message.GetModelObject();
                SaveModelObject();
                Sender.Tell(_modelObject);
                _entityChangeNotificationActor.Tell(new NotifySubscribersOfEntityChange(this.Id));
            });

            Receive<UndoRequest>(message =>
            {
                if (_undoStack.Count > 0)
                {
                    _modelObject = _undoStack.Pop();
                    SaveModelObject();
                }
                Sender.Tell(_modelObject);
            });
        }
Пример #32
0
        /// <summary>
        /// Creates an instance of the screen.
        /// </summary>
        public ConversationViewModel(IActorRef vmActor, Guid id)
        {
            _vmActor = vmActor;
            Id = id;

            _vmActor.Tell(new ConversationViewModelActor.AssociateWithViewModel(this));
        }
Пример #33
0
        private void Main_Load(object sender, EventArgs e)
        {
            _chartActor = Program.ChartActors.ActorOf(Props.Create(() => new ChartingActor(sysChart, btnPauseResume)), "charting");
            _chartActor.Tell(new ChartingActor.InitializeChart(null));

            _coordinatorActor =
                Program.ChartActors.ActorOf(Props.Create(() => new PerformanceCounterCoordinatorActor(_chartActor)),
                    "counters");

            _toggleActors[CounterType.Cpu] =
                Program.ChartActors.ActorOf(
                    Props.Create(() => new ButtonToggleActor(_coordinatorActor, btnCpu, CounterType.Cpu, false))
                        .WithDispatcher("akka.actor.synchronized-dispatcher"));

            _toggleActors[CounterType.Memory] =
                Program.ChartActors.ActorOf(
                    Props.Create(() => new ButtonToggleActor(_coordinatorActor, btnMemory, CounterType.Memory, false))
                        .WithDispatcher("akka.actor.synchronized-dispatcher"));

            _toggleActors[CounterType.Disk] =
                Program.ChartActors.ActorOf(
                    Props.Create(() => new ButtonToggleActor(_coordinatorActor, btnDisk, CounterType.Disk, false))
                        .WithDispatcher("akka.actor.synchronized-dispatcher"));

            _toggleActors[CounterType.Cpu].Tell(new ButtonToggleActor.Toggle());
        }
Пример #34
0
        static void Main(string[] args)
        {
            var section = (AkkaConfigurationSection)ConfigurationManager.GetSection("akka");
            _system = ActorSystem.Create("test", section.AkkaConfig);

            _coordinator = _system.ActorOf(Props.Create(() => new IdentityActor())
                .WithRouter(FromConfig.Instance), "fred");

            //_coordinator =
            //    _system.ActorOf(Props.Create(() => new IdentityActor()).WithRouter(new ConsistentHashingPool(5000)),
            //        "fred2");

            int routees = _coordinator.Ask<Routees>(new GetRoutees()).Result.Members.Count();
            Console.WriteLine(routees);

            // Lazy wait for the co-ordinator to deploy.
            Thread.Sleep(5000);

            for (int i = 1; i <= 5000; i++)
            {
                for (int x = 1; x <= 4; x++)
                {
                    _coordinator.Tell(new EntityMessage<long>(i));
                }
            }

            Thread.Sleep(500);

            Console.ReadLine();
        }
Пример #35
0
        private static void Main(string[] args)
        {
            system = ActorSystem.Create("fizz-buzz");
            spActor = system.ActorOf(Props.Create<SupervisorActor>(), "sp-actor");
            spActor.Tell("start");

            Console.ReadKey();
        }
Пример #36
0
        public void StartConsensus(UInt160 chainHash, Wallet wallet)
        {
            IActorRef system = GetChainActor(chainHash);

            system?.Tell(new ZoroSystem.StartConsensus {
                Wallet = wallet
            });
        }
Пример #37
0
        private void Handle(DistributedActorTableMessage <TKey> .Remove m)
        {
            IActorRef actor;

            if (_actorMap.TryGetValue(m.Id, out actor) == false)
            {
                _log.Error($"Cannot remove an actor that doesn't exist. (Id={m.Id} Sender={Sender})");
                return;
            }

            _actorMap.Remove(m.Id);
            _actorInverseMap.Remove(actor);
            Context.Unwatch(actor);
            _watchingActorCount -= 1;

            _table?.Tell(new DistributedActorTableMessage <TKey> .Internal.Remove(m.Id));
        }
Пример #38
0
 bool IP2PPlugin.OnP2PMessage(NeoSystem system, Message message)
 {
     if (message.Command == MessageCommand.Transaction)
     {
         consensus?.Tell(message.Payload);
     }
     return(true);
 }
Пример #39
0
 private bool RemoteNode_MessageReceived(NeoSystem system, Message message)
 {
     if (message.Command == MessageCommand.Transaction)
     {
         consensus?.Tell(message.Payload);
     }
     return(true);
 }
Пример #40
0
        private void UpdateProgress(IActorRef actor, Action <double> updateAction, decimal percentageComplete)
        {
            if (null == updateAction)
            {
                return;
            }

            actor?.Tell(new UpdateUIActorMessage.UpdateProgressBar((double)percentageComplete, updateAction));
        }
Пример #41
0
        private void _(PlayMovieMessage message)
        {
            log.Info("Started playing " + message.MovieTitle);
            CurrentlyPlaying = message.MovieTitle;
            log.Info("Replying to sender");

            Sender.Tell(new NowPlayingMessage(CurrentlyPlaying));
            stat?.Tell(message.MovieTitle);
        }
 public void Paused()
 {
     Receive <ToggleQuoteStream>(message => {
         Become(Streaming);
         Self.Tell(new SendRfq());
         _userInterface?.Tell("enabled streaming.");
     });
     // do nothing, we swallow any unprocessed message.
     Receive <SendRfq>(message => { });
 }
Пример #43
0
 protected override void PostStop()
 {
     if (!disconnected)
     {
         tcp?.Tell(Tcp.Close.Instance);
     }
     timer.CancelIfNotNull();
     ws?.Dispose();
     base.PostStop();
 }
 private void Begin()
 {
     Receive <CreateService>(service =>
     {
         var requestType = service.Request.GetType();
         var actor       = Context.ActorOf(Props.Create(() => (ReceiveActor)Activator.CreateInstance(typeof(NewsServiceActor <>).MakeGenericType(requestType), _client)), service.Request.TopHeadlinesRequest.Q);
         actor?.Tell(service.Request);
         _signalRActor?.Tell(new SendNewsServiceActor(actor), Self);
     });
 }
Пример #45
0
        private State <ClusterSingletonState, IClusterSingletonData> GoToHandingOver(IActorRef singleton, bool singletonTerminated, IActorRef handOverTo)
        {
            if (singletonTerminated)
            {
                return(HandleHandOverDone(handOverTo));
            }

            handOverTo?.Tell(HandOverInProgress.Instance);
            singleton.Tell(_terminationMessage);
            return(GoTo(ClusterSingletonState.HandingOver).Using(new HandingOverData(singleton, handOverTo)));
        }
Пример #46
0
            public ConnectionSourceStageLogic(Shape shape, ConnectionSourceStage stage, TaskCompletionSource <StreamTcp.ServerBinding> bindingPromise) : base(shape)
            {
                _stage          = stage;
                _bindingPromise = bindingPromise;

                SetHandler(_stage._out, onPull: () =>
                {
                    // Ignore if still binding
                    _listener?.Tell(new Tcp.ResumeAccepting(1), StageActorRef);
                }, onDownstreamFinish: TryUnbind);
            }
 public JournalCompatActor(string journal, string persistenceId)
 {
     JournalPluginId = journal;
     PersistenceId   = persistenceId;
     Command <SomeEvent>(se => Persist(se, p =>
     {
         events.Add(p);
     }));
     Command <ContainsEvent>(ce => Context.Sender.Tell(events.Any(e => e.Guid == ce.Guid)));
     Command <GetSequenceNr>(gsn =>
                             Context.Sender.Tell(
                                 new CurrentSequenceNr(this.LastSequenceNr)));
     Command <DeleteUpToSequenceNumber>(dc =>
     {
         deleteSubscriber = Context.Sender;
         DeleteMessages(dc.Number);
     });
     Command <DeleteMessagesSuccess>(dms => deleteSubscriber?.Tell(dms));
     Command <DeleteMessagesFailure>(dmf => deleteSubscriber?.Tell(dmf));
     Recover <SomeEvent>(se => events.Add(se));
 }
Пример #48
0
        public void StartNode(UInt160 chainHash, int port = 0, int wsPort = 0, int minDesiredConnections = Peer.DefaultMinDesiredConnections,
                              int maxConnections          = Peer.DefaultMaxConnections, int maxConnectionsPerAddress = Peer.DefaultMaxConnectionsPerAddress)
        {
            IActorRef system = GetChainActor(chainHash);

            system?.Tell(new ZoroSystem.Start
            {
                Port   = port,
                WsPort = wsPort,
                MinDesiredConnections    = minDesiredConnections,
                MaxConnections           = maxConnections,
                MaxConnectionsPerAddress = maxConnectionsPerAddress,
            });
        }
Пример #49
0
        public static RealTimeInventoryFinalResult ProcessAndSendResult(this OperationResult <IRealTimeInventory> result, IRequestMessage requestMessage, Func <IRealTimeInventory, IInventoryServiceCompletedMessage> successResponseCompletedMessage, ILoggingAdapter logger, IRealTimeInventory realTimeInventory, IActorRef sender, IActorRef notificationActorRef, IPerformanceService performanceService)
        {
            logger?.Info(requestMessage.GetType().Name + " Request was " + (!result.IsSuccessful ? " NOT " : "") + " successful.  Current Inventory :  " + realTimeInventory.GetCurrentQuantitiesReport());

            IInventoryServiceCompletedMessage response;

            if (!result.IsSuccessful)
            {
                response = result.ToInventoryOperationErrorMessage(requestMessage.ProductId);
                var message = "Error while trying to " + requestMessage.GetType() + " - The sender of the message is " + sender?.Path + result.Exception.ErrorMessage;
                notificationActorRef?.Tell(message);
                logger?.Error(message, requestMessage, result, realTimeInventory.GetCurrentQuantitiesReport());
            }
            else
            {
                realTimeInventory = result.Data as RealTimeInventory;
                response          = successResponseCompletedMessage(realTimeInventory);
                logger?.Info(response.GetType().Name + " Response was sent back. Current Inventory : " + realTimeInventory.GetCurrentQuantitiesReport() + " - The sender of the message is " + sender.Path);
            }
            sender?.Tell(response);
            notificationActorRef?.Tell(new RealTimeInventoryChangeMessage(realTimeInventory));
            performanceService?.Increment("Completed " + requestMessage.GetType().Name);
            return(new RealTimeInventoryFinalResult(realTimeInventory as RealTimeInventory, response, result));
        }
Пример #50
0
        public RecycleMonitorActor(IRecycleConfiguration recycleConfiguration, IActorRef watched, IActorRef watcher = null)
        {
            _actorRef = watcher;
            Context.Watch(watched);
            var log                  = Context.GetSeriLogger();
            var schedule             = ScheduleCheck(recycleConfiguration.ChildClearPeriod);
            var isWaitingForShutdown = false;
            var lastActivityTime     = BusinessDateTime.UtcNow;;

            log.Debug("Initialized recycle monitor for {actor}, max inactive time {inactive}, check period is {period}",
                      watched,
                      recycleConfiguration.ChildMaxInactiveTime,
                      recycleConfiguration.ChildClearPeriod);

            Receive <Activity>(a =>
            {
                var now          = BusinessDateTime.UtcNow;
                var inactiveTime = now - lastActivityTime;
                lastActivityTime = now;
                log.Debug($"Received activity after {inactiveTime}");
                if (!isWaitingForShutdown)
                {
                    return;
                }
                log.Debug("Rescheduling schecks after receiving activity after shutdown request");

                isWaitingForShutdown = false;
                schedule             = ScheduleCheck(recycleConfiguration.ChildClearPeriod);
            }, a => Sender.Path == watched.Path);
            Receive <Check>(c =>
            {
                var inactivityDuration = BusinessDateTime.UtcNow - lastActivityTime;
                log.Debug($"inactivity duration: {inactivityDuration}");
                if (inactivityDuration > recycleConfiguration.ChildMaxInactiveTime)
                {
                    log.Debug($"Sending graceful shutdown request to {watched} due to inactivity for {inactivityDuration} with max allowed {recycleConfiguration.ChildMaxInactiveTime}");
                    watched.Tell(Shutdown.Request.Instance);
                    isWaitingForShutdown = true;
                }
                schedule = ScheduleCheck(recycleConfiguration.ChildClearPeriod);
            });
            Receive <Terminated>(t =>
            {
                schedule.Cancel();
                _actorRef?.Tell(Shutdown.Complete.Instance);
                Context.Stop(Self);
            }, t => t.ActorRef.Path == watched.Path);
        }
Пример #51
0
        private void SuccessAuthorization(SuccessAuthorize obj)
        {
            state.ChangeState(obj);
            Log.Info($"Success Ecom");

            initiator?.Tell(obj);
            if (state.CurrentState == CardPaymentState._3Ds)
            {
                Become(Wait3Ds);
            }

            if (state.CurrentState == CardPaymentState.Payment)
            {
                Become(WaitPayment);
            }

            Context.Parent.Tell(new CompleteTransaction(state.OperationId)); //todo remove
        }
Пример #52
0
        static void Main(string[] args)
        {
            var myPort    = int.Parse(args[0]);
            var theirPort = int.Parse(args[1]);

            var portConfig = ConfigurationFactory.ParseString($"akka.remote.dot-netty.tcp.port = {myPort}");
            var config     = ConfigurationFactory.ParseString(File.ReadAllText("app.conf")).WithFallback(portConfig);

            using var system = ActorSystem.Create("remote-example", config);

            IActorRef?echo = null;
            var       quit = false;

            while (!quit)
            {
                switch (Menu())
                {
                case '1':
                    echo = system.ActorOf(Props.Create(() => new EchoService()), "echo");
                    Console.WriteLine("Echo service is created locally.");
                    break;

                case '2':
                    var remoteAddress = Address.Parse($"akka.tcp://remote-example@localhost:{theirPort}");
                    echo = system.ActorOf(Props.Create(() => new EchoService())
                                          .WithDeploy(Deploy.None.WithScope(new RemoteScope(remoteAddress))),
                                          "echo");
                    Console.WriteLine("Echo service is created on a remote machine.");
                    break;

                case '3':
                    Console.Write("Input: ");
                    echo?.Tell(Console.ReadLine());
                    break;

                case 'Q':
                    quit = true;
                    break;
                }
            }
            Console.WriteLine("End..");
        }
Пример #53
0
        private State <ClusterSingletonState, IClusterSingletonData> HandleHandOverDone(IActorRef handOverTo)
        {
            var newOldest = handOverTo?.Path.Address;

            Log.Info("Singleton terminated, hand-over done [{0} -> {1}]", _cluster.SelfAddress, newOldest);
            handOverTo?.Tell(HandOverDone.Instance);
            _memberExitingProgress.TrySetResult(Done.Instance);
            if (_removed.ContainsKey(_cluster.SelfUniqueAddress))
            {
                Log.Info("Self removed, stopping ClusterSingletonManager");
                return(Stop());
            }
            else if (handOverTo == null)
            {
                return(GoTo(ClusterSingletonState.Younger).Using(new YoungerData(null)));
            }
            else
            {
                return(GoTo(ClusterSingletonState.End).Using(EndData.Instance));
            }
        }
Пример #54
0
        protected override void OnReceive(object messageArg)
        {
            switch (messageArg)
            {
            case JobRequest request:
                _sender       = Sender;
                _requestCount = new Random().Next(5);
                _cumulResult  = request.Content;
                for (int i = 0; i < _requestCount; i++)
                {
                    if (_backEnds.Any())
                    {
                        _backEnds[i % _backEnds.Count].Tell(new ProcessRequest($"{request.Content}_sub{i}"));
                    }
                }
                break;

            case ProcessAnswer _:
                _requestCount--;
                _cumulResult += $"_{_requestCount}";
                if (_requestCount == 0)
                {
                    _storage?.Tell(new StorageRequest($"{_cumulResult}_store"));
                }
                break;

            case StorageAnswer _:
                _sender.Tell(new JobAnswer($"{_cumulResult}_ok"));
                Context.Stop(Self);
                break;

            default:
                Unhandled(messageArg);
                break;
            }
        }
Пример #55
0
 private void StartDownloading()
 {
     verboseReporter?.Tell("Telling downloaders to start");
     requestor = Sender;
     downloaders.ForEach(d => d.Tell(Start.Instance));
 }
Пример #56
0
 private void HandleMeterReadingReceived(MeterReadingReceived message)
 {
     _deviceActor?.Tell(message);
 }
Пример #57
0
 public void OnPull()
 {
     // Ignore if still binding
     _listener?.Tell(new Tcp.ResumeAccepting(1), StageActorRef);
 }
 protected override void PreRestart(Exception reason, object message)
 {
     _master?.Tell($"failed with {reason.GetType().Name} while processing {message}");
     Context.Stop(Self);
 }
Пример #59
0
 public TestEntity(IActorRef probe)
 {
     probe?.Tell(new Started(Self));
 }
Пример #60
0
        private void DeliverMessage(object message, IActorRef sender)
        {
            if (message is RestartShard restart)
            {
                var shardId = restart.ShardId;
                if (RegionByShard.TryGetValue(shardId, out var regionRef))
                {
                    if (Self.Equals(regionRef))
                    {
                        GetShard(shardId);
                    }
                }
                else
                {
                    if (!ShardBuffers.TryGetValue(shardId, out var buffer))
                    {
                        buffer = ImmutableList <KeyValuePair <object, IActorRef> > .Empty;
                        Log.Debug("Request shard [{0}]", shardId);
                        _coordinator?.Tell(new PersistentShardCoordinator.GetShardHome(shardId));
                    }

                    Log.Debug("Buffer message for shard [{0}]. Total [{1}] buffered messages.", shardId, buffer.Count + 1);
                    ShardBuffers = ShardBuffers.SetItem(shardId, buffer.Add(new KeyValuePair <object, IActorRef>(message, sender)));
                }
            }
            else
            {
                var shardId = ExtractShardId(message);
                if (RegionByShard.TryGetValue(shardId, out var region))
                {
                    if (region.Equals(Self))
                    {
                        var sref = GetShard(shardId);
                        if (Equals(sref, ActorRefs.Nobody))
                        {
                            BufferMessage(shardId, message, sender);
                        }
                        else
                        {
                            if (ShardBuffers.TryGetValue(shardId, out var buffer))
                            {
                                // Since now messages to a shard is buffered then those messages must be in right order
                                BufferMessage(shardId, message, sender);
                                DeliverBufferedMessage(shardId, sref);
                            }
                            else
                            {
                                sref.Tell(message, sender);
                            }
                        }
                    }
                    else
                    {
                        Log.Debug("Forwarding request for shard [{0}] to [{1}]", shardId, region);
                        region.Tell(message, sender);
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(shardId))
                    {
                        Log.Warning("Shard must not be empty, dropping message [{0}]", message.GetType());
                        Context.System.DeadLetters.Tell(message);
                    }
                    else
                    {
                        if (!ShardBuffers.ContainsKey(shardId))
                        {
                            Log.Debug("Request shard [{0}]", shardId);
                            _coordinator?.Tell(new PersistentShardCoordinator.GetShardHome(shardId));
                        }

                        BufferMessage(shardId, message, sender);
                    }
                }
            }
        }