public GuaranteedDeliveryActor(ActorSelection target,
                                       object message,
                                       int maxRetries,
                                       TimeSpan messageTimeout)
        {
            _target         = target;
            _message        = message;
            _maxRetries     = maxRetries;
            _messageTimeout = messageTimeout;

            Receive <ReceiveTimeout>(_ =>
            {
                if (_retryCount >= _maxRetries)
                {
                    throw new TimeoutException("Unable to deliver the message to the target in the specified number of retries");
                }
                else
                {
                    _target.Tell(_message);
                    _retryCount++;
                }
            });

            Receive <Ack>(_ =>
            {
                SetReceiveTimeout(null);
                Context.Stop(Self);
            });
        }
        public void BindIsland(Config config)
        {
            string systemName = config.GetString("akka.remote.system-name");
            string hostname   = config.GetString("akka.remote.dot-netty.tcp.hostname");
            string port       = config.GetString("akka.remote.system-port");

            //var selection = Context.ActorSelection("akka.tcp://[email protected]:2552/user/actorName");
            var hostActorPath = $"akka.tcp://{systemName}@{hostname}:{port}/user/island-router";

            ActorSelection selection = Context.ActorSelection(hostActorPath);

            try
            {
                IslandProvider = selection.ResolveOne(TimeSpan.FromSeconds(3)).Result;

                //IslandProvider.Tell(new Identify(_guid), Self);
                IslandProvider.Tell(new BindIslandMessage(), Self);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"Island {Self.Path} binded to host {IslandProvider.Path.ToStringWithoutAddress()}");
                Console.ForegroundColor = ConsoleColor.White;
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Bind error to {hostActorPath} \n {ex.Message}");
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
Exemple #3
0
        /// <summary>
        /// Handle VehicleExitRegistered message.
        /// </summary>
        /// <param name="msg">The message to handle.</param>
        private void Handle(VehicleExitRegistered msg)
        {
            _exitTimestamp = msg.Timestamp;

            // check speed limit
            int speedingViolation = DetermineSpeedingViolation();

            // log exit
            if (speedingViolation > 0)
            {
                FluentConsole.Red.Line($"{_color} {_brand} '{msg.VehicleId}' exited at {msg.Timestamp.ToString("HH:mm:ss.ffffff")}" +
                                       $"(avg speed {_avgSpeedInKmh} km/h - {speedingViolation} km/h over speed-limit (after correction))");

                // register speeding violation
                _cjcaActor = Context.ActorSelection("/user/cjcaactor");
                var rsv = new RegisterSpeedingViolation(_vehicleId, _roadInfo.RoadId, speedingViolation);
                _cjcaActor.Tell(rsv);
            }
            else
            {
                FluentConsole.Yellow.Line($"{_color} {_brand} '{msg.VehicleId}' exited at {msg.Timestamp.ToString("HH:mm:ss.ffffff")}" +
                                          $"(avg speed {_avgSpeedInKmh} km/h)");
            }

            Self.Tell(new Shutdown());
        }
 public void Setup()
 {
     _timeout        = TimeSpan.FromMinutes(1);
     _system         = ActorSystem.Create("system");
     _echo           = _system.ActorOf(Props.Create(() => new EchoActor()), "echo");
     _actorSelection = _system.ActorSelection("/user/echo");
 }
        public DomainBus()
        {
            _system = ActorSystem.Create("LocalSystem");
            var config = _system.Settings.Config;

            _domain = _system.ActorSelection(config.GetString("akka.actor.address.entry"));
        }
 private void MainWindow_Loaded(object sender, RoutedEventArgs e)
 {
     system      = ActorSystem.Create("MyClientSystem");
     serverActor = system.ActorSelection("akka.tcp://TestServer@localhost:8081/user/MyServerActor");
     uiActor     = system.ActorOf(Props.Create(() => new UIActor(this.textBox)), "MyClient");
     clientActor = system.ActorOf(Props.Create(() => new ClientActor(serverActor, uiActor)), Guid.NewGuid().ToString());
 }
Exemple #7
0
 /// <summary>
 /// Broadcast message by ActorSelection
 /// </summary>
 /// <param name="message"></param>
 /// <param name="targetSelection"></param>
 /// <param name="priority"></param>
 protected SimulationMessage(object message, ActorSelection targetSelection, Priority priority = Priority.Medium)
 {
     Key             = Guid.NewGuid();
     Message         = message;
     TargetSelection = targetSelection;
     Priority        = priority;
 }
Exemple #8
0
        private static void Main(string[] args)
        {
            var pageSize  = args != null && args.Length > 0 ? int.Parse(args[0] ?? "200") : 500;
            var pageCount = args != null && args.Length > 0 ? int.Parse(args[1] ?? "1000") : 3;

            var system = ActorSystem.Create("ras");

            _actorSelector = system.ActorSelection("akka.tcp://[email protected]:5888/user/api");

            Console.WriteLine("Execution started at {0}", DateTime.Now.ToLongTimeString());
            //Console.WriteLine("Setup EventStore");
            //EventStoreLoader.SetupEventStore();
            //var eventWriter = new EventWriter("Payments");

            try
            {
                using (var conn = new SqlConnection(ConnectionString))
                {
                    conn.Open();
                    for (var i = 0; i < pageCount; i++)
                    {
                        var res = ReadExistingEventsFromDbWithParams(pageSize, i, conn);
                        //res.ForEach(r => eventWriter.WriteEvent(r.Message, ((MessageType)r.MessageType).ToString()));
                        SendEvents(res);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Execution completed at {0}", DateTime.Now.ToLongTimeString());
            Console.ReadLine();
        }
        public TagReporter(NameValueCollection appSettings)
        {
            _client         = new WebClient();
            _reportEndpoint = new UriBuilder(appSettings["TargetBase"] + appSettings["TargetReports"]);
            _zoneEndpoint   = new UriBuilder(appSettings["TargetBase"] + appSettings["TargetLocations"]);
            _logger         = Context.ActorSelection("/user/Logger");
            _marshaller     = new XmlMarshaller();
            _counter        = 0;
            _statusMessage  = "Current Counter is {0}";

            if (appSettings["HttpsCertificates"].Equals("ignore"))
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }
            }
            ;

            Receive <AmqpMessage>(
                message =>
            {
                var postData = _marshaller.MarshallToReport(message.Zone, message.Epc);
                _counter    += 1;
                ForwardToTarget(postData, _reportEndpoint);
            });
            Receive <ZoneMap>(
                zoneMap =>
            {
                var payload = _marshaller.MarshallToLocations(zoneMap.Zones.Select(z => z.Name).ToList());
                ForwardToTarget(payload, _zoneEndpoint);
            });
            Receive <string>(message => Sender.Tell(String.Format(_statusMessage, _counter)));
        }
        private void Handle(TakeProductMsg msg)
        {
#warning  // test if item exists / create one if not

            ActorSelection itemActor = Context.ActorSelection(ActorSelectionPaths.BasketItem(msg.BasketId, msg.ProductId));
            itemActor.Tell(msg);
        }
        public GuaranteedDeliveryActor(ActorSelection actorSelection, object message, int maxRetries,
                                       TimeSpan messageTimeout)
        {
            _target         = actorSelection;
            _message        = message;
            _maxRetries     = maxRetries;
            _messageTimeout = messageTimeout;

            Receive <ReceiveTimeout>(_ =>
            {
                // Circuit breaker implementation
                if (_retryCount >= _maxRetries)
                {
                    throw new TimeoutException("Unable to deliver the message to the target in the specified " +
                                               "number of retires");
                }
                else
                {
                    _target.Tell(_message);
                    _retryCount++;
                }
            });

            Receive <AckMessage>(_ =>
            {
                SetReceiveTimeout(null); // Cancela la recepción de ReceiveTimeout message después de x tiempo
                Context.Stop(Self);      // Matamos al actor puesto que el receptor del mensaje le ha contestado correctamente
                                         // y su función termina
            });
        }
Exemple #12
0
        private static void TellMessagesToRemoteActor(ActorSelection lamp)
        {
            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.UnPlug());
            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.PressPowerButton());
            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.PlugIn());

            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.PlugIn());
            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.PressPowerButton());

            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.PlugIn());

            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.PressPowerButton());
            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.PressPowerButton());
            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.PressPowerButton());
            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.PressPowerButton());

            lamp.Tell(new LampActor.QueryState());
            lamp.Tell(new LampActor.UnPlug());
            lamp.Tell(new LampActor.QueryState());
        }
Exemple #13
0
 private static void SendMessagesWithScheduler(ActorSystem system, ActorSelection lamp)
 {
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(1), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(2), lamp, new LampActor.UnPlug(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(3), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(4), lamp, new LampActor.PressPowerButton(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(5), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(6), lamp, new LampActor.PlugIn(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(7), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(8), lamp, new LampActor.PlugIn(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(9), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(10), lamp, new LampActor.PressPowerButton(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(11), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(12), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(13), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(14), lamp, new LampActor.PlugIn(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(15), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(16), lamp, new LampActor.PressPowerButton(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(17), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(18), lamp, new LampActor.PressPowerButton(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(19), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(20), lamp, new LampActor.PressPowerButton(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(21), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(22), lamp, new LampActor.PressPowerButton(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(23), lamp, new LampActor.QueryState(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(24), lamp, new LampActor.UnPlug(), Nobody.Instance);
     system.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(25), lamp, new LampActor.QueryState(), Nobody.Instance);
 }
        public UserFeedbackProcessorActor(ActorSelection remotePersistenceActor)
        {
            _remotePersistenceActor = remotePersistenceActor;

            Receive <TellUserFeedbackMessage>(tellUserFeedback => ProcessTellUserFeedbackMessage(tellUserFeedback));
            Receive <UserFeedbackUpdateMessage>(userFeedbackUpdate => ProcessUserFeedbackUpdateMessage(userFeedbackUpdate));
        }
Exemple #15
0
        public QuerierActor()
        {
            _actorNaServeru = Context.ActorSelection(_adresaServera);

            Receive <Send>(x => Send());
            Receive <Answer>(x => ProcessAnswer(x));
        }
        private void UpdateSupervisorState(Fixture snapshot, bool isFullSnapshot)
        {
            ActorSelection supervisorActor = Context.System.ActorSelection("/user/SupervisorActor");
            MatchStatus    matchStatus;

            supervisorActor.Tell(new UpdateSupervisorStateMsg
            {
                FixtureId       = snapshot.Id,
                Sport           = _resource.Sport,
                Epoch           = snapshot.Epoch,
                CurrentSequence = snapshot.Sequence,
                StartTime       = snapshot.StartTime,
                IsSnapshot      = isFullSnapshot,
                MatchStatus     = Enum.TryParse(snapshot.MatchStatus, out matchStatus)
                    ? (MatchStatus?)matchStatus
                    : null,
                Name          = snapshot.FixtureName,
                CompetitionId = snapshot.Tags.ContainsKey("SSLNCompetitionId")
                    ? snapshot.Tags["SSLNCompetitionId"].ToString()
                    : null,
                CompetitionName = snapshot.Tags.ContainsKey("SSLNCompetitionName")
                    ? snapshot.Tags["SSLNCompetitionName"].ToString()
                    : null,
                LastEpochChangeReason = snapshot.LastEpochChangeReason,
                IsStreaming           = State == StreamListenerState.Streaming,
                IsSuspended           = _fixtureIsSuspended,
                IsErrored             = State == StreamListenerState.Errored,
                Exception             = _erroredException
            });
        }
        /// <summary>
        /// Initialises the object to respond to <see cref="CollectMessage"/> of type <see cref="CollectionType.Memory"/>
        /// </summary>
        public MemoryCollectionActor()
        {
            Receive <CollectMessage>(m => CollectStats(m), m => m.Collect == CollectionType.Memory);

            _output = Program.FindOutput();
            _output.Tell(new SimpleMessage("MemoryCollectionActor created"));
        }
 public ProductActor(Product product, int currentStock)
 {
     _product        = product;
     _stock          = currentStock;
     _backorderActor = Context.ActorSelection("/user/backorder");
     _salesActor     = Context.ActorSelection("/user/sales");
 }
 private void HandleMemberUp(ClusterEvent.IMemberEvent memberUp)
 {
     if (memberUp.Member.HasRole("actor") && AkkaActor == null)
     {
         AkkaActor = Context.ActorSelection(memberUp.Member.Address + "/user/ActorManager");
     }
 }
Exemple #20
0
 public TestsActor()
 {
     //hide all these strings somehow...
     agentListActor = Context.ActorSelection("../AgentList");
     Receive <RunTestsRequest>(HandleRunTestsRequest);
     Receive <CheckoutAndBuildCompleted>(HandleCheckoutAndBuildCompleted);
 }
        protected override void OnReceive(object message)
        {
            string msg = message as String;

            if (String.IsNullOrEmpty(msg))
            {
                // signal that the user needs to supply an input
                consoleWriterActor.Tell(new Messages.NullInputError("Input was blank. Please try again.\n"));

                // tell sender to continue doing its thing (whatever that may be, this actor doesn't care)
                Sender.Tell(new Messages.ContinueProcessing());
            }
            else
            {
                bool isValid = IsFileUri(msg);
                if (isValid)
                {
                    //signal succesful input
                    consoleWriterActor.Tell(new Messages.InputSuccess(string.Format("Starting processing for {0}", msg)));

                    ActorSelection tailCoordinatorActor = Context.ActorSelection("akka://MyActorSystem/user/tailCoordinatorActor");
                    tailCoordinatorActor.Tell(new TailCoordinatorActor.StartTail(msg, consoleWriterActor));
                    Sender.Tell(new Messages.ContinueProcessing());
                }
                else
                {
                    // signal that input was bad
                    consoleWriterActor.Tell(new Messages.ValidationError(string.Format("{0} is not an existing URI on disk.", msg)));

                    // tell sender to continue doing its thing (whatever that may be, this actor doesn't care)
                    Sender.Tell(new Messages.ContinueProcessing());
                }
            }
        }
Exemple #22
0
        public VacationsEmailLoader(VacationsEmailLoaderConfiguration configuration)
        {
            this.configuration   = configuration;
            this.inboxEmailActor = Context.ActorSelection(InboxEmailActorPath);

            this.Self.Tell(LoadInitialState.Instance);
        }
 public PushNotificationsService(
     IActorRefFactory actorsFactory,
     ActorPathsBuilder actorPathsBuilder)
 {
     this.pushNotificationsDevicesActor = actorsFactory.ActorSelection(
         actorPathsBuilder.Get(WellKnownActorPaths.PushNotificationsDevices));
 }
        public PlayerSupervisor(ActorSelection eventWriter)
        {
            _eventWriter = eventWriter;
            Receive <BatterEventMessage>(msg =>
            {
                _eventWriter.Tell(msg);
                var playerActor = Context.Child("batter-" + msg.PlayerId);
                if (playerActor == ActorRefs.Nobody)
                {
                    playerActor = Context.ActorOf(BatterActor.Create(msg.PlayerId), "batter-" + msg.PlayerId);
                }

                playerActor.Tell(msg);
            });

            Receive <EndOfFeed>(msg =>
            {
                _eventWriter.Tell(msg);
                var playerActors = Context.GetChildren();
                foreach (var playerActor in playerActors)
                {
                    playerActor.Tell(msg);
                }
            });
        }
        /// <summary>
        /// Handle SimulatePassingCar message.
        /// </summary>
        /// <param name="msg">The message to handle.</param>
        private void Handle(SimulatePassingCar msg)
        {
            //  simulate car entry
            int            entryLane      = _rnd.Next(1, 4);
            ActorSelection entryCamera    = Context.System.ActorSelection($"/user/entrycam{entryLane}");
            DateTime       entryTimestamp = DateTime.Now;
            VehiclePassed  vehiclePassed  = new VehiclePassed(msg.VehicleId, entryTimestamp);

            entryCamera.Tell(vehiclePassed);

            // simulate car exit
            int            exitLane      = _rnd.Next(1, 4);
            TimeSpan       delay         = TimeSpan.FromSeconds(_rnd.Next(_minExitDelayInS, _maxExitDelayInS) + _rnd.NextDouble());
            DateTime       exitTimestamp = entryTimestamp.Add(delay);
            ActorSelection exitCamera    = Context.System.ActorSelection($"/user/exitcam{entryLane}");

            vehiclePassed = new VehiclePassed(msg.VehicleId, exitTimestamp);
            Context.System.Scheduler.ScheduleTellOnce(delay, exitCamera, vehiclePassed, Self);

            // handle progress
            _carsSimulated++;
            if (_carsSimulated < _numberOfCars)
            {
                SimulatePassingCar simulatePassingCar = new SimulatePassingCar(GenerateRandomLicenseNumber());
                Context.System.Scheduler.ScheduleTellOnce(
                    _rnd.Next(_minEntryDelayInMS, _maxEntryDelayInMS), Self, simulatePassingCar, Self);
            }
            else
            {
                Self.Tell(new Shutdown());
            }
        }
Exemple #26
0
        public OrderIngestionEventHandler()
        {
            _responder = Context.ActorSelection("akka.tcp://order-processor@localhost:8082/user/order-ingestion-actor");

            Receive <OrderIngested>(a =>
            {
                Console.WriteLine($"{a.FulfillmentCenterId} Received order {a.Id}");
                var actor = Context.ActorOf(_consistentHashRouter);
                actor.Tell(a);
            });

            Receive <SubscribeToOrderIngestionEvents>(a =>
            {
                _responder.Tell(new Subscribe(Self));
            });

            _consistentHashRouter = new ConsistentHashingPool(2)
                                    .WithHashMapping(a =>
            {
                if (a is OrderIngested)
                {
                    return(((OrderIngested)a).FulfillmentCenterId);
                }

                return(null);
            }).Props(Props.Create <FCAllocationActor>());
        }
Exemple #27
0
 public ReplicationSource(string endpointId, string logName, string logId, ActorSelection acceptor) : this()
 {
     EndpointId = endpointId;
     LogName    = logName;
     LogId      = logId;
     Acceptor   = acceptor;
 }
Exemple #28
0
 private static IActorRef TryResolveActorSelection(ActorSelection selection)
 {
     return(Task.Run(async() =>
     {
         var counter = 0;
         IActorRef result = null;
         var lastException = new Exception();
         while (result == null && counter < 3)
         {
             try
             {
                 var identity = await selection.Ask <ActorIdentity>(new Identify(null), TimeSpan.FromSeconds(30));
                 if (identity.Subject == null)
                 {
                     throw new Exception("Unable to obtain iactorref of address " + selection.PathString + " even after obtaining a response with identity " + identity + " with message ID : " + identity?.MessageId);
                 }
                 result = identity.Subject;
             }
             catch (Exception e)
             {
                 lastException = e;
                 counter++;
                 await Task.Delay(TimeSpan.FromMilliseconds(500 * counter));
             }
         }
         if (result == null)
         {
             throw lastException;
         }
         return result;
     }).Result);
 }
Exemple #29
0
        protected void _init()
        {
            _log.Debug("加载{0}策略的仓位信息", Desc.Id);
            String path = String.Format("/user/{0}", ConstantsHelper.AKKA_PATH_PERSISTENCE);

            persistenceActor = Context.ActorSelection(path);
            PersistenceRequest req = new PersistenceRequest()
            {
                Type = PersistenceType.FIND, Body = String.Format("from EStrategy where Id={0}", Desc.Id)
            };
            var ret = persistenceActor.Ask <EStrategy>(req, TimeSpan.FromSeconds(1));

            ret.Wait();
            Desc = ret.Result;

            _log.Debug("{0}策略连接交易接口", Desc.Id);
            if (Desc.Trader != null)
            {
                String tpath = String.Format("/user/{0}/{1}", ConstantsHelper.AKKA_PATH_TRADER, Desc.Trader.Id);
                tradeActor = Context.ActorSelection(tpath);
            }
            else
            {
                // 默认的trade actor is /user/trader/ths
                tradeActor = Context.ActorSelection("/user/trader");
            }

            onInit();
        }
 public EntryPointActor()
 {
     Db.CreateTableIfNotExists <ResultMetadata>();
     Db.CreateTableIfNotExists <Failure>();
     MasterActor = getMasterActorRef();
     MasterActor.Tell(new RegisterEntryPointMessage());
 }