public IOrderActor CreateActor(Guid orderId) { var actorId = new ActorId(orderId); return(ActorProxy.Create <IOrderActor>(actorId, this._servicename)); }
private IAssociateActor GetAssociateActor(string associateId) { return(ActorProxy.Create <IAssociateActor>( new ActorId(associateId), new Uri("fabric:/ClarosFlute/AssociateActorService"))); }
public static IGameActor CreateProxy(string id) { return(new GameActorProxy(ActorProxy.Create(new ActorId(id), "GameActor"))); }
public async Task <IEnumerable <int> > Get() { var proxy = ActorProxy.Create <IMainActor>(new ActorId(Guid.NewGuid())); return(await proxy.GetSomeNumbers()); }
/// <summary> /// Starts processing a message in sequential order. If the message parameter is null, /// the method simply starts the sequential processing loop. /// </summary> /// <param name="message">The message to process.</param> /// <returns>True if the operation completes successfully, false otherwise.</returns> public async Task <bool> StartSequentialProcessingAsync(Message message) { // Parameters validation if (string.IsNullOrWhiteSpace(message?.MessageId) || string.IsNullOrWhiteSpace(message.Body)) { throw new ArgumentException($"Parameter {nameof(message)} is null or invalid.", nameof(message)); } var stopwatch = new Stopwatch(); var isSuccess = true; try { // Starts stopwatch stopwatch.Start(); // Logs event ActorEventSource.Current.Message($"Enqueue sequential processing of MessageId=[{message.MessageId}]..."); // Enqueues the message var queueActorProxy = ActorProxy.Create <ICircularQueueActor>(new ActorId(Id.ToString()), queueActorServiceUri); var callwatch = new Stopwatch(); try { callwatch.Start(); await queueActorProxy.EnqueueAsync(message); } catch (Exception) { // Sets success flag to false isSuccess = false; throw; } finally { callwatch.Stop(); ActorEventSource.Current.Dependency("CircularQueueActor", isSuccess, callwatch.ElapsedMilliseconds, isSuccess ? "Succeded" : "Failed", "Actor"); } // Traces metric ActorEventSource.Current.ReceivedMessage(); // Logs event ActorEventSource.Current.Message($"Sequential processing of MessageId=[{message.MessageId}] successfully enqueued."); // Updates internal statistics var longResult = await StateManager.TryGetStateAsync <long>(ReceivedState); if (longResult.HasValue) { await StateManager.SetStateAsync(ReceivedState, longResult.Value + 1); } // Checks if the sequential process is already running // If yes, the method returns immediately. var result = await StateManager.TryGetStateAsync <CancellationTokenSource>(ProcessingState); if (result.HasValue) { ActorEventSource.Current.Message($"WorkerActor=[{Id}] is already processing messages in a sequential order."); return(true); } // Creates a CancellationTokenSource object to eventually stop the long running task var cancellationTokenSource = new CancellationTokenSource(); // Adds the CancellationTokenSource to the actor state await StateManager.TryAddStateAsync(ProcessingState, cancellationTokenSource, cancellationTokenSource.Token); //Sets a reminder to return immediately from the call and rememeber to start the processor actor. await RegisterReminderAsync( Guid.NewGuid().ToString(), null, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(-1)); return(true); } catch (Exception ex) { // Sets success flag to false isSuccess = false; ActorEventSource.Current.Error(ex); return(false); } finally { stopwatch.Stop(); // Logs method duration ActorEventSource.Current.RequestComplete("WorkerStartSequentialProcessingAsync", isSuccess, stopwatch.ElapsedMilliseconds, isSuccess ? "Succeded" : "Failed"); } }
public Task <bool> MakeMoveAsync(ActorId gameId, int x, int y) { var game = ActorProxy.Create <IGame>(gameId, "fabric:/ActorTicTacToeApplication"); return(game.MakeMoveAsync(this.Id.GetLongId(), x, y)); }
static async Task Main(string[] args) { ActorId actorId = new ActorId(Guid.NewGuid().ToString()); // This only creates a proxy object, it does not activate an actor or invoke any methods yet. IFSM actor = ActorProxy.Create <IFSM>(actorId, new Uri("fabric:/ActorFSM/FSMActorService")); Console.WriteLine($"Running actor 1 [{actorId}] through FSM states."); var token = new CancellationToken(); await actor.Assign("Joe", token); await actor.Defer(token); await actor.Assign("Harry", token); await actor.Assign("Fred", token); await actor.Close(token); var actor1Status = await actor.GetStatus(); Console.WriteLine($"Actor 1 [{actorId}] should be closed: {actor1Status.CurrentStatus}"); ActorId actorId2 = new ActorId(Guid.NewGuid().ToString()); IFSM actor2 = ActorProxy.Create <IFSM>(actorId2, new Uri("fabric:/ActorFSM/FSMActorService")); Console.WriteLine($"Running actor 2 [{actorId2}] through FSM states"); await actor2.Assign("Sally", token); await actor2.Defer(token); await actor2.Assign("Sue", token); var actor2Status = await actor2.GetStatus(); Console.WriteLine($"Actor 2 [{actorId2}] should be assigned: {actor2Status.CurrentStatus}"); Console.WriteLine("Waiting for actors to deactivate for 20s (using modified Actor Garbage Collection settings in actor service program.cs)"); await Task.Delay(TimeSpan.FromSeconds(20)); Console.WriteLine("Queury Service Fabric to make sure Actors have been Garbage Collected"); var actorService = ActorServiceProxy.Create(new Uri("fabric:/ActorFSM/FSMActorService"), actorId); ContinuationToken continuationToken = null; IEnumerable <ActorInformation> inactiveActors; do { var queryResult = await actorService.GetActorsAsync(continuationToken, token); inactiveActors = queryResult.Items.Where(x => !x.IsActive); continuationToken = queryResult.ContinuationToken; } while (continuationToken != null); Console.WriteLine("Found the following Inactive actors in the system (should include actors just created):"); foreach (var actorInformation in inactiveActors) { Console.WriteLine($"\t {actorInformation.ActorId}"); } try { //should blow up because joe is in closed state await actor.Assign("Joe", token); } catch (Exception e) { Console.WriteLine($"Actor 1 [{actorId}] should throw exception becuase it is in closed state in the FSM"); } Console.WriteLine($"Actor 2 [{actorId2}] should be able to close in the FSM"); await actor2.Close(token); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); }
public static IVisionActor GetVision(ActorId actorId) { return(ActorProxy.Create <IVisionActor>(actorId, VisionActorUrl)); }
//public static async Task<List<Int64RangePartitionInformation>> GetStateServicePartitionInformationsAsync(string serviceName) //{ // var builder = new ServiceUriBuilder(serviceName); // var serviceUri = builder.ToUri(); // var lst = new List<Int64RangePartitionInformation>(); // foreach (var p in await fabricClient.QueryManager.GetPartitionListAsync(serviceUri)) // { // lst.Add(p.PartitionInformation as Int64RangePartitionInformation); // } // return lst; //} public IUserRegisterActor CreateUserRegisterActor(string userIdCardNo) { var builder = new ServiceUriBuilder(Constants.UserRegisterActorServiceName); return(ActorProxy.Create <IUserRegisterActor>(new ActorId(userIdCardNo), builder.ToUri())); }
public static IArmActor GetArm(ActorId actorId) { return(ActorProxy.Create <IArmActor>(actorId, ArmActorUrl)); }
public static IVisionActor GetVision(long actorId) { return(ActorProxy.Create <IVisionActor>(new ActorId(actorId), VisionActorUrl)); }
public static IArmActor GetArm(long actorId) { return(ActorProxy.Create <IArmActor>(new ActorId(actorId), ArmActorUrl)); }
public async Task ReceiveReminderAsync(string reminderName, byte[] context, TimeSpan dueTime, TimeSpan period) { if (reminderName.Equals(CheckProvision)) { ActorState State = await StateManager.GetStateAsync <ActorState>(StateKey); try { var nodeKey = this.Id.GetStringId();//Subscription/ResourceGroup/clustername/nodename; var queue = await ClusterConfigStore.GetMessageClusterResourceAsync(nodeKey) as ClusterQueueInfo; if (!State.IsInitialized) { var client = new ArmClient(await this.GetConfigurationInfo().GetAccessToken()); if (State.Keys == null || !State.Keys.IsAccessible) { var authRuleResourceId = queue.Properties.ServiceBus.AuthRuleResourceId; State.Keys = await client.ListKeysAsync <ServicebusAuthorizationKeys>(authRuleResourceId, "2015-08-01"); State.Path = queue.Name; } if (!State.Keys.IsAccessible) { Logger.Error("Servicebus keys are not accessible"); return; } // queue.Properties.ServiceBus.ServicebusNamespaceId var ns = NamespaceManager.CreateFromConnectionString(State.Keys.PrimaryConnectionString); if (!await ns.QueueExistsAsync(queue.Name)) { var qd = queue.Properties.QueueDescription; if (qd == null) { Logger.Warn("Servicebus queue do not exist"); return; } var q = new QueueDescription(queue.Name); if (qd.AutoDeleteOnIdle.IsPresent()) { q.AutoDeleteOnIdle = XmlConvert.ToTimeSpan(qd.AutoDeleteOnIdle); } if (qd.DefaultMessageTimeToLive.IsPresent()) { q.DefaultMessageTimeToLive = XmlConvert.ToTimeSpan(qd.DefaultMessageTimeToLive); } if (qd.DuplicateDetectionHistoryTimeWindow.IsPresent()) { q.RequiresDuplicateDetection = true; q.DuplicateDetectionHistoryTimeWindow = XmlConvert.ToTimeSpan(qd.DuplicateDetectionHistoryTimeWindow); } q.EnableBatchedOperations = qd.EnableBatchedOperations; q.EnableDeadLetteringOnMessageExpiration = qd.EnableDeadLetteringOnMessageExpiration; q.EnableExpress = qd.EnableExpress; q.EnablePartitioning = qd.EnablePartitioning; if (qd.ForwardDeadLetteredMessagesTo.IsPresent()) { q.ForwardDeadLetteredMessagesTo = qd.ForwardDeadLetteredMessagesTo; } if (qd.ForwardTo.IsPresent()) { q.ForwardTo = qd.ForwardTo; } await ns.CreateQueueAsync(q); } State.IsInitialized = true; } if (State.IsInitialized) { var ns = NamespaceManager.CreateFromConnectionString(State.Keys.PrimaryConnectionString); var config = this.GetConfigurationInfo(); var sbQueue = await ns.GetQueueAsync(queue.Name); Logger.Info($"Checking Queue information for {sbQueue.Path}, {sbQueue.MessageCount}, {sbQueue.MessageCountDetails.ActiveMessageCount}, {sbQueue.MessageCountDetails.DeadLetterMessageCount}, {sbQueue.MessageCountDetails.ScheduledMessageCount}, {sbQueue.MessageCountDetails.TransferDeadLetterMessageCount}, {sbQueue.MessageCountDetails.TransferMessageCount}"); var parts = nodeKey.Split('/'); var applicationName = new Uri($"fabric:/{parts[parts.Length - 2]}"); var serviceName = new Uri($"fabric:/{parts[parts.Length - 2]}/{parts[parts.Length-1]}"); var vmssManager = ActorProxy.Create <IVmssManagerActor>(new ActorId(string.Join("/", parts.Take(parts.Length - 1)) + "/" + queue.Properties.ListenerDescription.ProcessorNode)); var fabricClient = GetFabricClient(); var primNodes = 0; if (queue.Properties.ListenerDescription.UsePrimaryNode) { var nodes = await fabricClient.QueryManager.GetNodeListAsync(); primNodes = nodes.Aggregate(0, (c, p) => c + (p.NodeType == config.PrimaryScaleSetName ? 1 : 0)); } await vmssManager.ReportQueueMessageCountAsync(Id.GetStringId(), sbQueue.MessageCountDetails.ActiveMessageCount, primNodes); if (sbQueue.MessageCountDetails.ActiveMessageCount > 0 || queue.Properties.ListenerDescription.AlwaysOn) { //Handle Listener Application Deployment var listenerDescription = queue.Properties.ListenerDescription; var apps = await fabricClient.QueryManager.GetApplicationListAsync(applicationName); if (!apps.Any()) { var appTypes = await fabricClient.QueryManager.GetApplicationTypeListAsync(listenerDescription.ApplicationTypeName); if (!appTypes.Any(a => a.ApplicationTypeVersion == listenerDescription.ApplicationTypeVersion)) { Logger.Error("The listener application was not registed with service fabric"); return; } await fabricClient.ApplicationManager.CreateApplicationAsync(new ApplicationDescription { ApplicationName = applicationName, ApplicationTypeName = listenerDescription.ApplicationTypeName, ApplicationTypeVersion = listenerDescription.ApplicationTypeVersion, }); } var registered = await fabricClient.QueryManager.GetServiceListAsync(applicationName, serviceName); if (!registered.Any()) { var serviceType = await fabricClient.QueryManager.GetServiceTypeListAsync(listenerDescription.ApplicationTypeName, listenerDescription.ApplicationTypeVersion, listenerDescription.ServiceTypeName); if (!serviceType.Any()) { Logger.Error("The listener application service type was not registed with service fabric"); return; } try { var listenerConfiguration = new MessageProcessorOptions { ConnectionString = State.Keys.PrimaryConnectionString, QueuePath = sbQueue.Path, }; var placementConstraints = $"NodeTypeName == {queue.Properties.ListenerDescription.ProcessorNode}"; if (queue.Properties.ListenerDescription.UsePrimaryNode) { placementConstraints += " || isPrimary == true"; } await fabricClient.ServiceManager.CreateServiceAsync(new StatelessServiceDescription { ServiceTypeName = listenerDescription.ServiceTypeName, //QueueListenerService.ServiceType, // ServiceFabricConstants.ActorServiceTypes.QueueListenerActorService, ServiceName = serviceName, PartitionSchemeDescription = new UniformInt64RangePartitionSchemeDescription { PartitionCount = queue.Properties.ListenerDescription.PartitionCount, LowKey = Int64.MinValue, HighKey = Int64.MaxValue }, InstanceCount = -1, //One for each node, PlacementConstraints = placementConstraints, // $"NodeTypeName == {queue.Properties.ListenerDescription.ProcessorNode}", ApplicationName = applicationName, InitializationData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(listenerConfiguration)), }); } catch (Exception ex) { Logger.ErrorException("Could not register service for queue", ex); throw; } } } else { if ((DateTimeOffset.UtcNow - (XmlConvert.ToTimeSpan(queue.Properties.ListenerDescription.IdleTimeout))) > sbQueue.AccessedAt) { // await vmssManager.SetCapacityAsync(0); var registered = await fabricClient.QueryManager.GetServiceListAsync(applicationName, serviceName); if (registered.Any()) { await fabricClient.ServiceManager.DeleteServiceAsync(new DeleteServiceDescription(serviceName) { }); } } } } } catch (Exception ex) { Logger.ErrorException("Reminder Error:", ex); throw; } finally { await StateManager.SetStateAsync(StateKey, State); } } }
private IAggregationMapper[] BuildMapperPool(int capacity) { return(Enumerable.Range(0, capacity).Select(s => ActorProxy.Create <IAggregationMapper>(ActorId.CreateRandom())).ToArray()); }
private static void StopParallelProcessingTaskViaActorProxy() { try { // Sets device name used in the ActorId constructor const string workerId = "worker01"; // Creates actor proxy var proxy = ActorProxy.Create <IWorkerActor>(new ActorId(workerId), workerActorServiceUri); Console.WriteLine($" - [{DateTime.Now.ToLocalTime()}] ActorProxy for the [{workerId}] created."); // Enqueues 1 message with 10 steps. Note: the sequential message processing task emulates K steps of H seconds each to process each message. // However, since it runs on a separate task not awaited by the actor ProcessMessageAsync method, // the method itself returns immediately without waiting the the task completion. // This allows the actor to continue to enqueue requests, while processing messages on a separate task. var messageList = CreateMessageList(1, 10); foreach (var message in messageList) { proxy.StartParallelProcessingAsync(message).Wait(); Console.WriteLine( $" - [{DateTime.Now.ToLocalTime()}] Message [{JsonSerializerHelper.Serialize(message)}] sent."); } // Waits a couple of seconds before stopping the sequential message processing Console.WriteLine( $" - [{DateTime.Now.ToLocalTime()}] Wait 5 seconds before stopping the parallel message processing..."); for (var i = 5; i > 0; i--) { Console.WriteLine($" - [{DateTime.Now.ToLocalTime()}] {i}..."); Task.Delay(TimeSpan.FromSeconds(1)).Wait(); } // Stops the sequential message processing Console.WriteLine($" - [{DateTime.Now.ToLocalTime()}] Stopping the parallel message processing..."); proxy.StopParallelProcessingAsync(messageList.First().MessageId).Wait(); while (proxy.IsParallelProcessingRunningAsync(messageList[0].MessageId).Result) { Console.WriteLine( $" - [{DateTime.Now.ToLocalTime()}] Waiting for the parallel message processing task to stop..."); Task.Delay(TimeSpan.FromSeconds(1)).Wait(); } Console.WriteLine( $" - [{DateTime.Now.ToLocalTime()}] Parallel message processing task successfully stopped."); // Retrieves statistics var statistics = proxy.GetProcessingStatisticsAsync().Result; if (statistics == null) { return; } // Prints statistics PrintStatistics(statistics); } catch (Exception ex) { PrintException(ex); } }
private async Task Fetch() { if (HasLastFetchFinished() == false) { return; } var associationsTask = this.StateManager.GetStateAsync <Dictionary <ActorId, AssociateChunkMetaData> >("associations"); var playersTask = this.StateManager.GetStateAsync <Dictionary <ActorId, MinecraftVersion> >("observers"); var initPlayersTask = this.StateManager.GetStateAsync <Dictionary <ActorId, MinecraftVersion> >("initializeObservers"); await Task.WhenAll(associationsTask, playersTask, initPlayersTask); var associations = associationsTask.Result; var players = playersTask.Result; var initPlayers = initPlayersTask.Result; CalculateDistribution(1000, 4096); ActorId[] actorIds = null; if (players.Count != 0) { actorIds = new ActorId[players.Count]; players.Keys.CopyTo(actorIds, 0); } foreach (var pair in associations) { var association = pair.Value; //if no tracking pieces, then recreate... this handle the re-hydrate of the actor if (_tracking.ContainsKey(pair.Key) == false) { var trackingData = new TrackingChunkMetaData() { fidelity = association.fidelity }; _tracking.Add(pair.Key, trackingData); } var tracking = _tracking[pair.Key]; var task = tracking.updateTask; if (task != null) { var response = task.Result; tracking.playerVersion = response.lastPlayersVersion; tracking.blockVersion = response.lastBlockVersion; } if ((association.needInitObservers.Count > 0) || (actorIds.Length > 0)) { var informActor = ActorProxy.Create <InformActor>(pair.Value.informActorId, this.ServiceUri); tracking.updateTask = informActor.InformOfChange(actorIds, association, tracking); } association.needInitObservers.Clear(); //need to save } //convert over... foreach (var pair in initPlayers) { players.Add(pair.Key, pair.Value); } initPlayers.Clear(); //now save everyting var taskSetInit = this.StateManager.SetStateAsync("initializeObservers", initPlayers); var taskSetObserver = this.StateManager.SetStateAsync("observers", players); var taskSetAssociation = this.StateManager.SetStateAsync("associations", associations); await Task.WhenAll(taskSetInit, taskSetObserver, taskSetAssociation); return; }
public Task <bool> JoinGameAsync(ActorId gameId, string playerName) { var game = ActorProxy.Create <IGame>(gameId, "fabric:/ActorTicTacToeApplication"); return(game.JoinGameAsync(this.Id.GetLongId(), playerName)); }
private IIoTActor GetBuildingActorProxy(string BuildingId, string EventHubName, string ServiceBusNS) { ActorId actorId = new ActorId(string.Format(buildingActorIdFormat, BuildingId, EventHubName, ServiceBusNS)); return(ActorProxy.Create <IIoTActor>(actorId, new Uri(buildingActorService))); }
private static ITodoActor GetTodoActorProxy(string email) { return(ActorProxy.Create <ITodoActor>(new ActorId(email))); }
public IGiftMakerElfActor Create(string actorId) { return(ActorProxy.Create <IGiftMakerElfActor>(new ActorId(actorId), FabricUri)); }
/// <summary> /// Updates the configuration for the specified service from its available properties. /// </summary> /// <param name="service"></param> /// <param name="cancellationToken"></param> async Task UpdateMonitor(Service service, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var monitor = ActorProxy.Create <IMonitorActor>(new ActorId(service.ServiceName.ToString())); var options = await monitor.GetConfig() ?? new MonitorConfiguration(); var changed = false; foreach (var property in await GetNamedPropertiesAsync(service.ServiceName, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); var key = property.Metadata.PropertyName; var val = property.GetValue <string>(); if (val == null || string.IsNullOrWhiteSpace(val)) { continue; } if (Regex.Match(key, @"^IisWebFarmMonitor\:Endpoints\.(\w*)\.(\w+)$") is Match m && m.Success && m.Groups.Count == 3) { if (options.Endpoints == null) { options.Endpoints = new Dictionary <string, MonitorEndpointConfiguration>(); } var endpointName = m.Groups[1].Value; var endpoint = options.Endpoints.GetOrAdd(endpointName, _ => new MonitorEndpointConfiguration()); if (endpoint == null) { throw new InvalidOperationException("Unable to find endpoint configuration."); } switch (m.Groups[2].Value) { case nameof(MonitorEndpointConfiguration.ServerName): if (endpoint.ServerName != val) { changed = true; logger.Verbose("Applying ServerName {ServerName} to {ServiceName}:{EndpointName}.", val, service.ServiceName, endpointName); endpoint.ServerName = val; } break; case nameof(MonitorEndpointConfiguration.ServerFarmName): if (endpoint.ServerFarmName != val) { changed = true; logger.Verbose("Applying ServerFarmName {ServerFarmName} to {ServiceName}:{EndpointName}.", val, service.ServiceName, endpointName); endpoint.ServerFarmName = val; } break; case nameof(MonitorEndpointConfiguration.Interval) when TimeSpan.TryParse(val, out var interval): if (endpoint.Interval != interval) { changed = true; logger.Verbose("Applying Interval {Interval} to {ServiceName}:{EndpointName}.", interval, service.ServiceName, endpointName); endpoint.Interval = interval; } break; } } } // save new configuration if (changed) { await monitor.SetConfig(options); } }
private IValidationDPActor GetValidationDPActor() { return(ActorProxy.Create <IValidationDPActor>( ActorId.CreateRandom(), new Uri($"{FabricRuntime.GetActivationContext().ApplicationName}/ValidationDPActorService"))); }
private IUserActor GetUserActor(string userId) { return(ActorProxy.Create <IUserActor>(new ActorId(userId), new Uri("fabric:/Ecommerce/UserActorService"))); }
private IExtractVariablesActor GetExtractActor(string userId) { return(ActorProxy.Create <IExtractVariablesActor>(new ActorId(userId), new Uri("fabric:/EvvosoftVariableEngine/ExtractVariablesActorService"))); }
/// <summary> /// Starts processing a message on a separate task. /// </summary> /// <param name="message">The message to process.</param> /// <returns>True if the operation completes successfully, false otherwise.</returns> public async Task <bool> StartParallelProcessingAsync(Message message) { // Parameters validation if (string.IsNullOrWhiteSpace(message?.MessageId) || string.IsNullOrWhiteSpace(message.Body)) { throw new ArgumentException($"Parameter {nameof(message)} is null or invalid.", nameof(message)); } var stopwatch = new Stopwatch(); var isSuccess = true; try { // Starts stopwatch stopwatch.Start(); // Logs event ActorEventSource.Current.Message($"Start MessageId=[{message.MessageId}] processing..."); // Checks if message processing is already running. // If yes, the method returns immediately. var result = await StateManager.TryGetStateAsync <CancellationTokenSource>(message.MessageId); if (result.HasValue) { ActorEventSource.Current.Message($"WorkerActor=[{Id}] is already processing MessageId=[{message.MessageId}]."); return(true); } // Creates a CancellationTokenSource object to eventually stop the long running task var cancellationTokenSource = new CancellationTokenSource(); // Adds the CancellationTokenSource to the actor state using the messageId as name await StateManager.TryAddStateAsync(message.MessageId, cancellationTokenSource, cancellationTokenSource.Token); // Updates internal statistics var longResult = await StateManager.TryGetStateAsync <long>(ReceivedState, cancellationTokenSource.Token); if (longResult.HasValue) { await StateManager.SetStateAsync(ReceivedState, longResult.Value + 1, cancellationTokenSource.Token); } var actorProxy = ActorProxy.Create <IProcessorActor>(new ActorId(message.MessageId), processorActorServiceUri); var callwatch = new Stopwatch(); try { callwatch.Start(); // Starts the message processing await actorProxy.ProcessParallelMessagesAsync(Id.ToString(), message, cancellationTokenSource.Token); } catch (Exception) { // Sets success flag to false isSuccess = false; throw; } finally { callwatch.Stop(); ActorEventSource.Current.Dependency("ProcessorActor", isSuccess, callwatch.ElapsedMilliseconds, isSuccess ? "Succeded" : "Failed", "Actor"); } // Logs event ActorEventSource.Current.Message($"Parallel processing of MessageId=[{message.MessageId}] successfully started."); // Traces metric ActorEventSource.Current.ReceivedMessage(); return(true); } catch (Exception ex) { // Sets success flag to false isSuccess = false; ActorEventSource.Current.Error(ex); return(false); } finally { stopwatch.Stop(); // Logs method duration ActorEventSource.Current.RequestComplete("WorkerStartParallelProcessingAsync", isSuccess, stopwatch.ElapsedMilliseconds, isSuccess ? "Succeded" : "Failed"); } }
private IReplaceVariablesActor GetReplaceActor(string userId) { return(ActorProxy.Create <IReplaceVariablesActor>(new ActorId(userId), new Uri("fabric:/EvvosoftVariableEngine/ReplaceVariablesActorService"))); }
/// <summary> /// Entry point. /// </summary> /// <param name="args">Arguments.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public static async Task Main(string[] args) { var data = new MyData() { PropertyA = "ValueA", PropertyB = "ValueB", }; // Create an actor Id. var actorId = new ActorId("abc"); // Make strongly typed Actor calls with Remoting. // DemoActor is the type registered with Dapr runtime in the service. var proxy = ActorProxy.Create <IDemoActor>(actorId, "DemoActor"); Console.WriteLine("Making call using actor proxy to save data."); await proxy.SaveData(data); Console.WriteLine("Making call using actor proxy to get data."); var receivedData = await proxy.GetData(); Console.WriteLine($"Received data is {receivedData}."); // Making some more calls to test methods. try { Console.WriteLine("Making calls to an actor method which has no argument and no return type."); await proxy.TestNoArgumentNoReturnType(); } catch (Exception ex) { Console.WriteLine($"ERROR: Got exception while making call to method with No Argument & No Return Type. Exception: {ex}"); } try { await proxy.TestThrowException(); } catch (ActorMethodInvocationException ex) { if (ex.InnerException is NotImplementedException) { Console.WriteLine($"Got Correct Exception from actor method invocation."); } else { Console.WriteLine($"Got Incorrect Exception from actor method invocation. Exception {ex.InnerException}"); } } // Making calls without Remoting, this shows method invocation using InvokeMethodAsync methods, the method name and its payload is provided as arguments to InvokeMethodAsync methods. Console.WriteLine("Making calls without Remoting."); var nonRemotingProxy = ActorProxy.Create(actorId, "DemoActor"); await nonRemotingProxy.InvokeMethodAsync("TestNoArgumentNoReturnType"); await nonRemotingProxy.InvokeMethodAsync("SaveData", data); var res = await nonRemotingProxy.InvokeMethodAsync <MyData>("GetData"); Console.WriteLine("Registering the timer and reminder"); await proxy.RegisterTimer(); await proxy.RegisterReminder(); Console.WriteLine("Waiting so the timer and reminder can be triggered"); await Task.Delay(6000); Console.WriteLine("Making call using actor proxy to get data after timer and reminder triggered"); receivedData = await proxy.GetData(); Console.WriteLine($"Received data is {receivedData}."); Console.WriteLine("Deregistering timer. Timers would any way stop if the actor is deactivated as part of Dapr garbage collection."); await proxy.UnregisterTimer(); Console.WriteLine("Deregistering reminder. Reminders are durable and would not stop until an explicit deregistration or the actor is deleted."); await proxy.UnregisterReminder(); Console.WriteLine("Creating a Bank Actor"); var bank = ActorProxy.Create <IBankActor>(ActorId.CreateRandom(), "DemoActor"); while (true) { var balance = await bank.GetAccountBalance(); Console.WriteLine($"Balance for account '{balance.AccountId}' is '{balance.Balance:c}'."); Console.WriteLine($"Withdrawing '{10m:c}'..."); try { await bank.Withdraw(new WithdrawRequest() { Amount = 10m, }); } catch (ActorMethodInvocationException ex) { Console.WriteLine("Overdraft: " + ex.Message); break; } } }
private static void TestParallelMessageProcessingViaActorProxy() { try { // Sets device name used in the ActorId constructor const string workerId = "worker01"; // Creates actor proxy var proxy = ActorProxy.Create <IWorkerActor>(new ActorId(workerId), workerActorServiceUri); Console.WriteLine($" - [{DateTime.Now.ToLocalTime()}] ActorProxy for the [{workerId}] created."); // Creates N messages var messageList = CreateMessageList(); var taskList = new List <Task>(); Func <string, Task> waitHandler = async messageId => { try { while (await proxy.IsParallelProcessingRunningAsync(messageId)) { Console.WriteLine( $" - [{DateTime.Now.ToLocalTime()}] Waiting for [{messageId}] parallel processing task completion..."); await Task.Delay(TimeSpan.FromSeconds(1)); } Console.WriteLine( $" - [{DateTime.Now.ToLocalTime()}] [{messageId}] Parallel message processing task completed."); } catch (Exception ex) { PrintException(ex); } }; // Start parallel processing foreach (var message in messageList) { if (!proxy.StartParallelProcessingAsync(message).Result) { continue; } taskList.Add(waitHandler(message.MessageId)); Console.WriteLine( $" - [{DateTime.Now.ToLocalTime()}] Message [{JsonSerializerHelper.Serialize(message)}] sent."); } // Wait for message processing completion Task.WaitAll(taskList.ToArray()); Console.WriteLine($" - [{DateTime.Now.ToLocalTime()}] Parallel message processing tasks completed."); // Retrieves statistics var statistics = proxy.GetProcessingStatisticsAsync().Result; if (statistics == null) { return; } // Prints statistics PrintStatistics(statistics); } catch (Exception ex) { PrintException(ex); } }
static void Main(string[] args) { int number_of_device = 10; ////IActor1 actor = ActorProxy.Create<IActor1>(ActorId.CreateRandom(), new Uri("fabric:/Application1/Actor1ActorService")); ////System.Threading.Tasks.Task<string> retval = actor.GetHelloWorldAsync(); ////Console.Write(retval.Result); ////Console.ReadLine(); IThing[] things = new IThing[number_of_device]; for (int i = 1; i <= number_of_device; i++) { ThingData chillerConfigData = new ThingData(); chillerConfigData.ThingMetaData = new ThingMetaData() { ID = i, Name = "Device" + i }; var attributeList = new List <AttributeData>(); chillerConfigData.AttributeDatas = attributeList; AddAttribute(attributeList, chillerConfigData.ThingMetaData.Name, "Temperature", chillerConfigData.ThingMetaData.Name + "Temperature", "Temperature", DataType.Double, "F", 0, CreateTempLimitData()); AddAttribute(attributeList, chillerConfigData.ThingMetaData.Name, "Humidity", chillerConfigData.ThingMetaData.Name + "Humidity", "Humidity", DataType.Double, "%", 0, CreateHumidityLimitData()); AddAttribute(attributeList, chillerConfigData.ThingMetaData.Name, "Pressure", chillerConfigData.ThingMetaData.Name + "Humidity", "Pressure", DataType.Double, "psi", 0, CreatePresureLimitData()); IThing actor1 = ActorProxy.Create <IThing>(new ActorId(chillerConfigData.ThingMetaData.ID), new Uri("fabric:/Application1/ThingActorService")); actor1.SetData(chillerConfigData); things[i - 1] = actor1; } Console.Write("Deplyment is done"); for (int i = 1; i <= number_of_device; i++) { /////IThing actor1 = ActorProxy.Create<IThing>(new ActorId(i), new Uri("fabric:/Application1/ThingActorService")); var actor1 = things[i - 1]; Task <ThingData> model = actor1.GetData(); ThingData data = (ThingData)model.Result; Console.Write(data.ThingMetaData.ID + ":" + data.ThingMetaData.Name + "\n"); } Console.ReadLine(); /* * IThing device1 = ActorProxy.Create<IThing>(new ActorId(1), new Uri("fabric:/Application1/ThingActorService")); * var chiller1 = new Chiller("1", "Device1"); * chiller1.SimulateData(); * var runtimeDatas = chiller1.AttributeRuntimeDatas.Values; * ////Task<bool> retval1 = device1.ProcessEventAsync(runtimeDatas); * ////Console.Write(retval1.Result); * * List<AttributeRuntimeData> attributeRuntimeDatas = new List<AttributeRuntimeData>(); * foreach (var data in chiller1.AttributeRuntimeDatas.Values) * { * attributeRuntimeDatas.Add(data); * } */ ////AttributeRuntimeData attributeRuntime = new AttributeRuntimeData(); ////attributeRuntime.Name = "Temperature"; ////attributeRuntime.dqt = new DataQualityTimestamp() ////{ //// Value = 50, //// Timestamp = DateTime.UtcNow, //// Status = "Good" ////}; //attributeRuntimeDatas.Add(attributeRuntime); ///device1.ProcessEventAsync(attributeRuntimeDatas); ////ISampleScriptActor script = ActorProxy.Create<ISampleScriptActor>(new ActorId(Guid.NewGuid()), new Uri("fabric:/Application1/SampleScriptActorService")); ////while (true) ////{ //// Console.ReadLine(); //// Console.Write(script.GetValueOfB().Result); ////} }
/// <summary> /// Starts processing messages from the work queue in a sequential order. /// </summary> /// <param name="cancellationToken">This CancellationToken is used to stop message processing.</param> /// <returns></returns> public async Task ProcessSequentialMessagesAsync(CancellationToken cancellationToken) { try { Message message; // Creates the proxy to call the queue actor var queueActorProxy = ActorProxy.Create <ICircularQueueActor>(new ActorId(Id.ToString()), queueActorServiceUri); // Creates the proxy to call the worker actor var workerActorProxy = ActorProxy.Create <IWorkerActor>(new ActorId(Id.ToString()), workerActorServiceUri); // The method keeps processing messages from the queue, until the queue is empty while ((message = await queueActorProxy.DequeueAsync()) != null) { try { // Message validation if (string.IsNullOrWhiteSpace(message.MessageId) || string.IsNullOrWhiteSpace(message.Body)) { ActorEventSource.Current.Message("Message Invalid."); continue; } // Create delay variable and assign 1 second as default value var delay = TimeSpan.FromSeconds(1); // Create steps variable and assign 10 as default value var steps = 10; if (message.Properties != null) { // Checks if the message Properties collection contains the delay property if (message.Properties.ContainsKey(DelayProperty)) { if (message.Properties[DelayProperty] is TimeSpan) { // Assigns the property value to the delay variable delay = (TimeSpan)message.Properties[DelayProperty]; } else { var value = message.Properties[DelayProperty] as string; if (value != null) { TimeSpan temp; if (TimeSpan.TryParse(value, out temp)) { delay = temp; } } } } // Checks if the message Properties collection contains the steps property if (message.Properties.ContainsKey(StepsProperty)) { if (message.Properties[StepsProperty] is int) { steps = (int)message.Properties[StepsProperty]; } if (message.Properties[StepsProperty] is long) { // Assigns the property value to the steps variable steps = (int)(long)message.Properties[StepsProperty]; } else { var value = message.Properties[StepsProperty] as string; if (value != null) { int temp; if (int.TryParse(value, out temp)) { steps = temp; } } } } } // NOTE!!!! This section should be replaced by some real computation for (var i = 0; i < steps; i++) { ActorEventSource.Current.Message( $"MessageId=[{message.MessageId}] Body=[{message.Body}] ProcessStep=[{i + 1}]"); try { await Task.Delay(delay, cancellationToken); } catch (TaskCanceledException) { } if (!cancellationToken.IsCancellationRequested) { continue; } // NOTE: If message processing has been cancelled, // the method returns immediately without any result ActorEventSource.Current.Message( $"MessageId=[{message.MessageId}] elaboration has been canceled and sequential message processing stopped."); return; } ActorEventSource.Current.Message( $"MessageId=[{message.MessageId}] has been successfully processed."); for (var n = 1; n <= 3; n++) { try { // Simulates a return value between 1 and 100 var random = new Random(); var returnValue = random.Next(1, 101); var isSuccess = true; var callwatch = new Stopwatch(); try { callwatch.Start(); // Returns result to worker actor await workerActorProxy.ReturnSequentialProcessingAsync(message.MessageId, returnValue); } catch (Exception) { // Sets success flag to false isSuccess = false; throw; } finally { callwatch.Stop(); ActorEventSource.Current.Dependency("WorkerActor", isSuccess, callwatch.ElapsedMilliseconds, isSuccess ? "Succeded" : "Failed", "Actor"); } //Logs event ActorEventSource.Current.Message($"Sequential processing of MessageId=[{message.MessageId}] ReturnValue=[{returnValue}] successfully returned."); break; } catch (FabricTransientException ex) { ActorEventSource.Current.Message(ex.Message); } catch (AggregateException ex) { foreach (var e in ex.InnerExceptions) { ActorEventSource.Current.Message(e.Message); } } catch (Exception ex) { ActorEventSource.Current.Message(ex.Message); } Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).Wait(cancellationToken); } } catch (Exception ex) { ActorEventSource.Current.Error(ex); } } for (var n = 1; n <= 3; n++) { try { // Sets the sequential processing state to false var isSuccess = true; var callwatch = new Stopwatch(); try { callwatch.Start(); await workerActorProxy.CloseSequentialProcessingAsync(false); } catch (Exception) { // Sets success flag to false isSuccess = false; throw; } finally { callwatch.Stop(); ActorEventSource.Current.Dependency("WorkerActor", isSuccess, callwatch.ElapsedMilliseconds, isSuccess ? "Succeded" : "Failed", "Actor"); } ActorEventSource.Current.Message("Closed sequential processing."); return; } catch (FabricTransientException ex) { ActorEventSource.Current.Message(ex.Message); } catch (AggregateException ex) { foreach (var e in ex.InnerExceptions) { ActorEventSource.Current.Message(e.Message); } } catch (Exception ex) { ActorEventSource.Current.Message(ex.Message); throw; } Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).Wait(cancellationToken); } throw new TimeoutException(); } catch (Exception ex) { ActorEventSource.Current.Error(ex); } }