public ChildAwareActor(string name) { _child = Context.ActorOf(Props.Create(() => new BlackHoleActor()), name); }
private void InitializeFSM() { When(ClusterSingletonState.Start, e => { if (e.FsmEvent is StartOldestChangedBuffer) { _oldestChangedBuffer = Context.ActorOf(Actor.Props.Create <OldestChangedBuffer>(_settings.Role).WithDispatcher(Context.Props.Dispatcher)); GetNextOldestChange(); return(Stay()); } else if (e.FsmEvent is OldestChangedBuffer.InitialOldestState initialOldestState) { _oldestChangedReceived = true; if (initialOldestState.Oldest.Equals(_selfUniqueAddress) && initialOldestState.SafeToBeOldest) { // oldest immediately return(GoToOldest()); } else if (initialOldestState.Oldest.Equals(_selfUniqueAddress)) { return(GoTo(ClusterSingletonState.BecomingOldest).Using(new BecomingOldestData(null))); } else { return(GoTo(ClusterSingletonState.Younger).Using(new YoungerData(initialOldestState.Oldest))); } } return(null); }); When(ClusterSingletonState.Younger, e => { if (e.FsmEvent is OldestChangedBuffer.OldestChanged oldestChanged && e.StateData is YoungerData youngerData) { _oldestChangedReceived = true; if (oldestChanged.Oldest.Equals(_selfUniqueAddress)) { Log.Info("Younger observed OldestChanged: [{0} -> myself]", youngerData.Oldest?.Address); switch (youngerData.Oldest) { case null: return(GoToOldest()); case UniqueAddress prev when _removed.ContainsKey(prev): return(GoToOldest()); case UniqueAddress prev: Peer(prev.Address).Tell(HandOverToMe.Instance); return(GoTo(ClusterSingletonState.BecomingOldest).Using(new BecomingOldestData(prev))); } } else { Log.Info("Younger observed OldestChanged: [{0} -> {1}]", youngerData.Oldest?.Address, oldestChanged.Oldest?.Address); GetNextOldestChange(); return(Stay().Using(new YoungerData(oldestChanged.Oldest))); } }
protected DurableBase() { commands = new List <Handler>(); events = new List <Handler>(); journalReader = Context.ActorOf(Props.Create <JournalReader>(), "reader"); }
public DeviceManager(string id) { _id = id; _isActive = true; devices = new Dictionary <string, IActorRef>(); #region Forward Receive <DevicePhysicalStarted>(msg => Forward(msg.Source.Source, msg)); Receive <DevicePhysicalDisconnected>(msg => Forward(msg.Source.Source, msg)); Receive <DevicePhysicalSended>(msg => Forward(msg.Source.Source, msg)); Receive <DevicePhysicalSet>(msg => Forward(msg.Source.Source, msg)); Receive <DevicePhysicalSetMsg>(msg => Context.Parent.Tell(msg)); #endregion #region Gateway Receive <DevicePhysicalCreated>(msg => { devices.TryGetValue(msg.Source.Source, out var device); if (device == null) { device = Context.ActorOf(Device.Props(msg.Source.Source)); devices.Add(msg.Source.Source, device); Context.TellOrc(new DeviceStatus(msg.Source)); Context.TellOrc(new PhysicalSetEnd()); } }); Receive <DevicePhysicalDroped>(msg => { devices.Remove(msg.Source.Source); Context.TellOrc(new PhysicalSetEnd()); }); Receive <GatewayPhysicalDisconnected>(msg => { _isActive = false; TellOrcForAllDevice(id => new DeviceDisconnected(new DeviceInfo(id, _id))); Context.TellOrc(new PhysicalSetEnd()); }); Receive <GatewayPhysicalStarted>(msg => { _isActive = true; _Ip = msg.Ip; TellOrcForAllDevice(id => new DeviceStarted(new DeviceInfo(id, _id), msg.Ip)); Context.Parent.Tell(new GatewayPhysicalSetMsg(msg.Source, _value)); Context.TellOrc(new PhysicalSetEnd()); }); Receive <GatewayPhysicalSended>(msg => { _value = msg.Value; _isActive = true; Context.TellOrc(new PhysicalSetEnd()); }); Receive <GatewayPhysicalSet>(msg => { Context.Parent.Tell(msg.GatewayPhysicalSetMsg); Context.TellOrc(new PhysicalSetEnd()); }); Receive <RequiredId>(msg => Sender.Tell(_id)); #endregion Receive <GatewayGetPhysical>(msg => { var devicesPhysical = new List <DevicePhysical>(); foreach (var device in devices) { devicesPhysical.Add(device.Value.Ask <DevicePhysical>(new DeviceGetPhysical()).Result); } Sender.Tell(new GatewayPhysical(_id, _value, _isActive, devicesPhysical.ToArray())); }); }
public BarrierCoordinatorSupervisor(ActorRef testActor) { _testActor = testActor; _barrier = Context.ActorOf(Props.Create <BarrierCoordinator>()); }
private void ReceivedInitEliteDangerous(ConnectorManagerMessage.InitEliteDangerous message) { log.Info("Initializing Elite Dangerous Connector"); this.edConnector = Context.ActorOf(Props.Create(() => new EliteDangerous.ConnectorActor(this.env, this.config, this.uiMessenger)), "cn-ed"); this.edConnector.Tell(new EliteDangerous.ConnectorMessage.Init()); }
private void HandleReplayMessages(ReplayMessages message) { var replyTo = _isReplayFilterEnabled ? Context.ActorOf(ReplayFilter.Props(message.PersistentActor, _replayFilterMode, _replayFilterWindowSize, _replayFilterMaxOldWriters, _replayDebugEnabled)) : message.PersistentActor; var context = Context; var eventStream = Context.System.EventStream; var readHighestSequenceNrFrom = Math.Max(0L, message.FromSequenceNr - 1); var promise = new TaskCompletionSource <long>(); _breaker.WithCircuitBreaker(() => ReadHighestSequenceNrAsync(message.PersistenceId, readHighestSequenceNrFrom)) .ContinueWith(t => { if (!t.IsFaulted && !t.IsCanceled) { var highSequenceNr = t.Result; var toSequenceNr = Math.Min(message.ToSequenceNr, highSequenceNr); if (toSequenceNr <= 0L || message.FromSequenceNr > toSequenceNr) { promise.SetResult(highSequenceNr); } else { // Send replayed messages and replay result to persistentActor directly. No need // to resequence replayed messages relative to written and looped messages. // not possible to use circuit breaker here ReplayMessagesAsync(context, message.PersistenceId, message.FromSequenceNr, toSequenceNr, message.Max, p => { if (!p.IsDeleted) // old records from pre 1.0.7 may still have the IsDeleted flag { foreach (var adaptedRepresentation in AdaptFromJournal(p)) { replyTo.Tell(new ReplayedMessage(adaptedRepresentation), ActorRefs.NoSender); } } }) .ContinueWith(replayTask => { if (!replayTask.IsFaulted && !replayTask.IsCanceled) { promise.SetResult(highSequenceNr); } else { promise.SetException(replayTask.IsFaulted ? TryUnwrapException(replayTask.Exception) : new OperationCanceledException("ReplayMessagesAsync canceled, possibly due to timing out.")); } }, _continuationOptions); } } else { promise.SetException(t.IsFaulted ? TryUnwrapException(t.Exception) : new OperationCanceledException("ReadHighestSequenceNrAsync canceled, possibly due to timing out.")); } }, _continuationOptions); promise.Task .ContinueWith(t => !t.IsFaulted ? new RecoverySuccess(t.Result) as IJournalResponse : new ReplayMessagesFailure(TryUnwrapException(t.Exception)), _continuationOptions) .PipeTo(replyTo) .ContinueWith(t => { if (!t.IsFaulted && CanPublish) { eventStream.Publish(message); } }, _continuationOptions); }
public CNNFeedActor() { int toProcess = 0; int processed = 0; IActorRef proc = Context.ActorOf <CNNItemActor>(); List <string> feeds = new List <string>() { "http://rss.cnn.com/rss/cnn_us.rss", "http://rss.cnn.com/rss/cnn_world.rss", "http://rss.cnn.com/rss/cnn_topstories.rss", "http://rss.cnn.com/rss/money_latest.rss", "http://rss.cnn.com/rss/cnn_allpolitics.rss", "http://rss.cnn.com/rss/cnn_latest.rss", "http://rss.cnn.com/rss/money_news_companies.rss", "http://rss.cnn.com/rss/money_news_international.rss", "http://rss.cnn.com/rss/cnn_tech.rss" }; string currentFeed = feeds.First(); Receive <processedCNN>(r => { processed++; if (processed >= toProcess) { if (currentFeed == feeds.Last()) { Console.WriteLine("+++CNN Processed"); currentFeed = feeds.First(); Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromMinutes(1), Self, new CNNUS.processedCNN(), Self); } else { var cur = feeds.IndexOf(currentFeed); currentFeed = feeds[cur + 1]; Self.Tell(new CNNUS.processCNN()); } } }); Receive <processCNN>(c => { toProcess = 0; processed = 0; string xml = ""; var feed = currentFeed.Substring(currentFeed.LastIndexOf("/") + 1); Console.WriteLine("CNN - Downloading data - " + feed); try { WebClient wc = new WebClient(); xml = wc.DownloadString(currentFeed); } catch (Exception ex) { Console.WriteLine("CNN -- Couldn't download data!!"); } if (string.IsNullOrWhiteSpace(xml)) { Self.Tell(new processedCNN()); } else { XDocument xdoc = XDocument.Parse(xml); var items = xdoc.Root.Elements().Elements("item").ToList(); toProcess = items.Count(); foreach (var item in items) { proc.Tell(new processCNNItem() { item = item }); } } }); }
public IActorRef ActorOf(Action <IActorDsl> config, string name = null) { var props = Props.Create(() => new Act(config)); return(Context.ActorOf(props, name)); }
protected override void PreStart() { //_githubWorker = Context.ActorOf(Props.Create(() => new GithubWorkerActor(GithubClientFactory.GetClient))); _githubWorker = Context.ActorOf(Props.Create(() => new GithubWorkerActor(GithubClientFactory.GetClient)) .WithRouter(new RoundRobinPool(10))); }
public PlaybackActor() { _logger = Context.GetLogger(); Context.ActorOf <UserCoordinatorActor>("UserCoordinator"); Context.ActorOf <PlaybackStatisticsActor>("PlaybackStatistics"); }
public StoppingStrategySupervisor(IActorRef testProbe) { _crashingActor = Context.ActorOf(Props.Create(() => new CrashingActor(testProbe)), "CrashingActor"); }
public MyRemoteActor(ManualResetEventSlim childCreatedEvent) { var child = Context.ActorOf <SomeActor>("child"); childCreatedEvent.Set(); }
private void CreateMachines(int machineNumber, long time) { Logger.Log(LogLevel.Warn, "Creating Maschine No: {arg} !", new object[] { machineNumber }); Machines.Add(Context.ActorOf(MachineAgent.Props(_SimulationContext, time), "Maschine_" + machineNumber), true); }
protected override void PreStart() { _githubWorker = Context.ActorOf(Props.Create(() => new GithubWorkerActor(GithubClientFactory.GetClient))); }
private void Forward(OrderMessage message) { var target = Context.ActorOf <OrderReceiveActor>(); target.Forward(message); }
private void ReceivedInitEdsm(ConnectorManagerMessage.InitEdsm message) { log.Info("Initializing the EDSM Connector"); this.edsmConnector = Context.ActorOf(Props.Create(() => new Edsm.ConnectorActor(this.env, this.config, this.uiMessenger)), "cn-edsm"); this.edsmConnector.Tell(new Edsm.ConnectorMessage.Init()); }
protected override void PreStart() { _pubSubActor = Context.ActorOf(Context.DI().Props <PubSubActor>(), $"{nameof(PubSubActor)}"); _fileCopyManager = Context.ActorOf(Context.DI().Props <FileCopyManager>(), $"{nameof(FileCopyManager)}"); _repeatActionManager = Context.ActorOf(Context.DI().Props <RepeatActionManager>(), $"{nameof(RepeatActionManager)}"); }
protected override void PreStart() { writer = Context.ActorOf(Props.Create(() => new WriterActor())); base.PreStart(); }
private void Ready() { _log.Debug("AggregateRootCoordinatorActor entering Ready state"); Receive <IAccountMessage>(msg => { //forward on if (!_accountWorkerRefs.ContainsKey(msg.AccountId)) { var accountProjection = Context.ActorOf(Props.Create <AccountProjection>(msg.AccountId)); var parms = new AggregateRootCreationParameters( msg.AccountId, new List <IActorRef>() { _accountIndexProjection, accountProjection }, snapshotThreshold: 5, receiveTimeout: TimeSpan.FromMinutes(2) ); //register our projection _registry.Tell(new RegisterProjection(msg.AccountId, accountProjection)); _accountWorkerRefs.Add(msg.AccountId, Context.ActorOf(Props.Create <AccountActor>(parms), "aggregates(account)" + msg.AccountId.ToString())); _log.Debug("Account:{0}, Added to Agg Root Coordinator Cache", msg.AccountId); } _accountWorkerRefs[msg.AccountId].Forward(msg); }); Receive <PassivateMessage>(msg => { _log.Debug("Account:{0}, timed out, due to inactivity", msg.Id); var actorToUnload = Context.Sender; actorToUnload.GracefulStop(TimeSpan.FromSeconds(10)).ContinueWith((success) => { if (success.Result) { _accountWorkerRefs.Remove(msg.Id); _log.Debug("Account:{0}, removed", msg.Id); } else { _log.Warning("Account:{0}, failed to removed", msg.Id); } }); // the time between the above and below lines, we need to intercept messages to the child that is being // removed from memory - how to do this? //task.Wait(); // dont block thread, use pipeto instead? }); Receive <GetProjection>(msg => { _log.Debug("GetProjection requested ", msg.Key); _registry.Forward(msg); }); Receive <GetIndexProjection>(msg => { _log.Debug("GetIndexProjection requested ", msg.Key); _registry.Forward(msg); }); }
protected override void PreStart() { _tcpScanner = Context.ActorOf(Props.Create(() => new TcpPortMonitoringActor(Self, _settings)), "portMonitor"); Context.Watch(_tcpScanner); }
public TestResultsRequestActor() { TestResultsRouter = Context.ActorOf(Props.Create <TestRunCoordinator>().WithRouter(FromConfig.Instance), "TestResultCaches"); Receive <TestsResultRequest>(x => HandleTestsResultRequest(x)); }
public PlaybackActor() { Context.ActorOf(Props.Create <UserCoordinatorActor>(), "UserCoordinator"); Context.ActorOf(Props.Create <PlaybackStatisticsActor>(), "PlaybackStatistics"); }
protected override void PreStart() { _coordinator = Context.ActorOf(Props.Create(() => new GithubCoordinatorActor()), ActorPaths.GithubCoordinatorActor.Name); base.PreStart(); }
private void StartAnalysis(StartAnalysisRequest request) { var firstDayOfSprint = _currentIterationInfoOptions.Value.StartDate.Date == DateTime.Now.Date; // There is another function that runs when it is the first day of the sprint! if (firstDayOfSprint) { Context.Stop(Self); Sender.Tell(new AnalysisCompleteResponse()); } var lastDayOfSprint = _currentIterationInfoOptions.Value.FinishDate.Date == DateTime.Now.Date; var currentIterationWorkItems = _workItemsRetriever.GetWorkItems(IterationTimeFrame.Current); var pendingPullRequests = _pullRequestsRetriever.GetPullRequests(); // Creating the subordinate actors. var estimateWorkItemActor = Context.ActorOf(Context.DI().Props <EstimateWorkItemsActor>(), "estimate-work-item-actor"); var descriptiveTitleActor = Context.ActorOf(Context.DI().Props <DescriptiveTitleActor>(), "descriptive-title-actor"); var activateWorkItemActor = Context.ActorOf(Context.DI().Props <ActivateWorkItemActor>(), "activate-work-item-actor"); var descriptionActor = Context.ActorOf(Context.DI().Props <DescriptionActor>(), "description-actor"); var longCodeCompleteActor = Context.ActorOf(Context.DI().Props <LongCodeCompleteActor>(), "long-code-complete-actor"); var greatWorkActor = Context.ActorOf(Context.DI().Props <GreatWorkActor>(), "great-work-actor"); var stillActiveWorkItemsActor = Context.ActorOf(Context.DI().Props <StillActiveWorkItemsActor>(), "still-active-work-items-actor"); var pendingPullRequestsActor = Context.ActorOf(Context.DI().Props <PendingPullRequestsActor>(), "pending-pull-requests-actor"); // Running the actors. var tasks = new List <Task>(); var estimateWorkItemTask = estimateWorkItemActor .Ask <ActorResponse <IReadOnlyList <string> > >(currentIterationWorkItems); tasks.Add(estimateWorkItemTask); var descriptiveTitleTask = descriptiveTitleActor .Ask <ActorResponse <IReadOnlyList <string> > >(currentIterationWorkItems); tasks.Add(descriptiveTitleTask); var activeWorkItemTask = activateWorkItemActor .Ask <ActorResponse <IReadOnlyList <string> > >(currentIterationWorkItems); tasks.Add(activeWorkItemTask); var descriptionTask = descriptionActor .Ask <ActorResponse <IReadOnlyList <string> > >(currentIterationWorkItems); tasks.Add(descriptionTask); var longCodeCompleteTask = longCodeCompleteActor .Ask <ActorResponse <IReadOnlyList <string> > >(currentIterationWorkItems); tasks.Add(longCodeCompleteTask); var greatWorkTask = greatWorkActor .Ask <ActorResponse <IReadOnlyList <string> > >(currentIterationWorkItems); tasks.Add(greatWorkTask); var dummyStillActiveWorkItemsTask = new Task <ActorResponse <IReadOnlyList <string> > >( () => new ActorResponse <IReadOnlyList <string> >(new List <string>(), false)); dummyStillActiveWorkItemsTask.Start(); var stillActiveWorkItemsTask = lastDayOfSprint ? stillActiveWorkItemsActor.Ask <ActorResponse <IReadOnlyList <string> > >(currentIterationWorkItems) : dummyStillActiveWorkItemsTask; tasks.Add(stillActiveWorkItemsTask); var longPendingPullRequestsTask = pendingPullRequestsActor.Ask <ActorResponse <IReadOnlyList <string> > >(pendingPullRequests); tasks.Add(longPendingPullRequestsTask); // Waiting for all the of the actors to finish their work and return a response back. Task.WaitAll(tasks.ToArray()); // Collecting the results from each actor. var messages = new List <string>(); messages.AddRange(estimateWorkItemTask.Result.Content); messages.AddRange(descriptiveTitleTask.Result.Content); messages.AddRange(descriptionTask.Result.Content); messages.AddRange(activeWorkItemTask.Result.Content); messages.AddRange(stillActiveWorkItemsTask.Result.Content); messages.AddRange(longCodeCompleteTask.Result.Content); messages.AddRange(longPendingPullRequestsTask.Result.Content); // Sending "great work" message when there are no other messages makes the greeting a little awkward // as the greeting asks for completion some work items, but there is none. // todo Improve this as I still want to send the positive feedback even if there is nothing else. if (messages.Any()) { messages.AddRange(greatWorkTask.Result.Content); } // Sending the messages from each actor to the message senders. Using a different message sender if it // is the last day of the sprint. if (lastDayOfSprint) { _lastDayOfCurrentIterationMessageSender.SendMessages(messages).Wait(); } else { _currentIterationMessageSender.SendMessages(messages).Wait(); } Context.Stop(Self); // This is required for stopping the program. Check out the Ask<> calls in the function classes. Sender.Tell(new AnalysisCompleteResponse()); }
protected override void OnReceive(object message) { var createServerFSM = message as CreateServerFSM; if (createServerFSM != null) { var channel = createServerFSM.Channel; var host = (IPEndPoint)channel.RemoteAddress; var name = WebUtility.UrlEncode(host + ":" + host.Port + "-server" + _generation++); var fsm = Context.ActorOf( Props.Create(() => new ServerFSM(Self, channel)).WithDeploy(Deploy.Local), name); _log.Debug("Sending FSM {0} to {1}", fsm, Sender); Sender.Tell(fsm); return; } var nodeInfo = message as NodeInfo; if (nodeInfo != null) { _barrier.Forward(nodeInfo); if (_nodes.ContainsKey(nodeInfo.Name)) { if (_initialParticipants > 0) { foreach (var ni in _nodes.Values) { ni.FSM.Tell(new ToClient <BarrierResult>(new BarrierResult("initial startup", false))); } _initialParticipants = 0; } nodeInfo.FSM.Tell(new ToClient <BarrierResult>(new BarrierResult("initial startup", false))); } else { _nodes = _nodes.Add(nodeInfo.Name, nodeInfo); if (_initialParticipants <= 0) { nodeInfo.FSM.Tell(new ToClient <Done>(Done.Instance)); } else if (_nodes.Count == _initialParticipants) { foreach (var ni in _nodes.Values) { ni.FSM.Tell(new ToClient <Done>(Done.Instance)); } _initialParticipants = 0; } if (_addrInterest.ContainsKey(nodeInfo.Name)) { foreach (var a in _addrInterest[nodeInfo.Name]) { a.Tell(new ToClient <AddressReply>(new AddressReply(nodeInfo.Name, nodeInfo.Addr))); } _addrInterest = _addrInterest.Remove(nodeInfo.Name); } } } var clientDisconnected = message as ClientDisconnected; if (clientDisconnected != null && clientDisconnected.Name != null) { _nodes = _nodes.Remove(clientDisconnected.Name); _barrier.Forward(clientDisconnected); return; } if (message is IServerOp) { if (message is EnterBarrier) { _barrier.Forward(message); return; } if (message is FailBarrier) { _barrier.Forward(message); return; } var getAddress = message as GetAddress; if (getAddress != null) { var node = getAddress.Node; if (_nodes.ContainsKey(node)) { Sender.Tell(new ToClient <AddressReply>(new AddressReply(node, _nodes[node].Addr))); } else { ImmutableHashSet <IActorRef> existing; _addrInterest = _addrInterest.SetItem(node, (_addrInterest.TryGetValue(node, out existing) ? existing : ImmutableHashSet.Create <IActorRef>() ).Add(Sender)); } return; } if (message is Done) { return; //FIXME what should happen? } } if (message is ICommandOp) { var throttle = message as Throttle; if (throttle != null) { var t = _nodes[throttle.Target]; _nodes[throttle.Node].FSM.Forward(new ToClient <ThrottleMsg>(new ThrottleMsg(t.Addr, throttle.Direction, throttle.RateMBit))); return; } var disconnect = message as Disconnect; if (disconnect != null) { var t = _nodes[disconnect.Target]; _nodes[disconnect.Node].FSM.Forward((new ToClient <DisconnectMsg>(new DisconnectMsg(t.Addr, disconnect.Abort)))); return; } var terminate = message as Terminate; if (terminate != null) { _barrier.Tell(new BarrierCoordinator.RemoveClient(terminate.Node)); _nodes[terminate.Node].FSM.Forward(new ToClient <TerminateMsg>(new TerminateMsg(terminate.ShutdownOrExit))); _nodes = _nodes.Remove(terminate.Node); return; } var remove = message as Remove; if (remove != null) { _barrier.Tell(new BarrierCoordinator.RemoveClient(remove.Node)); return; } } if (message is GetNodes) { Sender.Tell(_nodes.Keys); return; } if (message is GetSockAddr) { Sender.Tell(_connection.LocalAddress); return; } }
public ParentTestActor() { Receive <Start>(s => Context.ActorOf <ChildTestActor>().Tell(s, Sender)); }
protected override void PreStart() { ApiBroadcaster = Context.Child(MasterBroadcastName).Equals(ActorRefs.Nobody) ? Context.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), MasterBroadcastName) : Context.Child(MasterBroadcastName); }
protected override void PreStart() { _designOperationsActorRef = Context.ActorOf(Props.Create(() => new DesignOperationsActor(_modMetadata))); _modStringTableActorRef = Context.ActorOf(Props.Create(() => new ModStringTableActor(_modMetadata))); }
private void AccountOpened(AccountOpenedCommand accountOpenedCommand) { _managedAccounts.Add(accountOpenedCommand.AccountId, Context.ActorOf(Context.System.DI().Props <AccountActor>(), accountOpenedCommand.AccountId.ToString())); }