public static async Task CreateInventory( [ActivityTrigger] string username, [OrchestrationClient] IDurableOrchestrationClient client, [Queue(Global.QUEUE)] IAsyncCollector <string> console, ILogger logger) { logger.LogInformation("Create inventory for user {user}", username); var inventoryList = _inventoryMaker.MakeNewInventory(); var id = username.AsEntityIdFor <InventoryList>(); await client.SignalEntityAsync <IInventoryListOperations>(id, operation => operation.New(inventoryList)); foreach (var item in inventoryList) { id = username.AsEntityIdFor <Inventory>(item.Name); await client.SignalEntityAsync <IInventoryOperations>(id, operation => operation.New(item.Name)); if (item.IsTreasure) { await client.SignalEntityAsync <IInventoryOperations>(id, operation => operation.SetTreasure()); } } await console.AddAsync($"A {inventoryList[0].Name} and {inventoryList[1].Name} have been added for user {username}!"); logger.LogInformation("Create {item} and {secondItem} for {user} successful", inventoryList[0].Name, inventoryList[1].Name, username); }
public static async Task <bool> KillUser( [ActivityTrigger] string username, [OrchestrationClient] IDurableOrchestrationClient client, [Queue(Global.QUEUE)] IAsyncCollector <string> console, ILogger logger) { logger.LogInformation("Kill user: {user}", username); var user = await client.ReadUserEntityAsync <User>(username); if (!user.EntityExists) { throw new Exception($"KillUser: User {username} not found!"); } await client.SignalEntityAsync <IUserOperations>( username.AsEntityIdFor <User>(), operation => operation.Kill()); await client.SignalEntityAsync( UserCounter.Id, UserCounter.UserDone); await console.AddAsync($"Unfortunately user {username} died from waiting too long!"); logger.LogInformation("KillUser {user} successful", username); return(true); }
public static async Task PlaceMonsterInRoom( [ActivityTrigger] string username, [OrchestrationClient] IDurableOrchestrationClient client, [Queue(Global.QUEUE)] IAsyncCollector <string> console, ILogger logger) { logger.LogInformation("Placing monster in room for {user}", username); var room = await username.GetEntityForUserOrThrow <Room>(client); var monster = await username.GetEntityForUserOrThrow <Monster>(client); logger.LogInformation("Found monster {monster} to place in room {room} for user {user}", monster.Name, room.Name, username); await client.SignalEntityAsync <IMonsterOperations>( username.AsEntityIdFor <Monster>(), operation => operation.SetRoom(room.Name)); await client.SignalEntityAsync <IRoomOperations>( username.AsEntityIdFor <Room>(), operation => operation.SetMonster(monster.Name)); logger.LogInformation("Placing monster {monster} in room {room} for user {user} successful.", monster.Name, room.Name, username); await console.AddAsync($"{username} notices a {monster.Name} in {room.Name}."); }
public static async Task PlaceInventoryInRoom( [ActivityTrigger] string username, [OrchestrationClient] IDurableOrchestrationClient client, [Queue(Global.QUEUE)] IAsyncCollector <string> console, ILogger logger) { logger.LogInformation("Placing inventory in room for {user}", username); var inventoryNames = await username.GetEntityForUserOrThrow <InventoryList>(client); var inventoryList = await inventoryNames.DeserializeListForUserWithClient(username, client); var inventory = inventoryList .Where(i => !i.IsTreasure) .Select(i => i).First(); var room = await username.GetEntityForUserOrThrow <Room>(client); logger.LogInformation("Found weapon {inventory} and room {room} for user {user}", inventory.Name, room.Name, username); await client.SignalEntityAsync <IInventoryOperations>( username.AsEntityIdFor <Inventory>(inventory.Name), operation => operation.SetRoom(room.Name)); await client.SignalEntityAsync <IRoomOperations>( username.AsEntityIdFor <Room>(), operation => operation.AddInventory(inventory.Name)); logger.LogInformation("Place treasure for user {user} successful."); await console.AddAsync($"{username} sees a {inventory.Name} inside the room!"); }
public async Task AuthorizeHttp(AuthorizeHttpInput input, ILogger log) { this.State.KeyAuthz = input.KeyAuthz; this.State.EntityId = input.EntityId; this.State.AuthorizationLocation = input.AuthorizationLocation; this.SaveState(); await starter.SignalEntityAsync(input.EntityId, nameof(AcmeContextActor.ValidateAuthorization), new ValidateAuthorizationInput { AuthorizationLocation = input.AuthorizationLocation, UseDns = false, OrchestratorId = input.OrchestratorId }); }
public static async Task <IActionResult> NewUser( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, [Queue(Global.QUEUE)] IAsyncCollector <string> console, [OrchestrationClient] IDurableOrchestrationClient starter, ILogger log) { log.LogInformation("NewUser called."); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); string name = data?.name; if (string.IsNullOrWhiteSpace(name)) { await console.AddAsync("An attempt to create a user with no name was made."); return(new BadRequestObjectResult("User name is required.")); } var userCheck = await starter.ReadUserEntityAsync <User>(name); if (userCheck.EntityExists) { await console.AddAsync($"Attempt to add duplicate user {name} failed."); return(new BadRequestObjectResult("Duplicate username is not allowed.")); } // create the user here var id = name.AsEntityIdFor <User>(); await starter.SignalEntityAsync <IUserOperations>( id, user => user.New(name)); await starter.SignalEntityAsync( UserCounter.Id, UserCounter.NewUser); await starter.StartNewAsync(nameof(NewUserParallelFunctions.RunUserParallelWorkflow), name); log.LogInformation("Started new parallel workflow for user {user}", name); await starter.StartNewAsync(nameof(MonitorFunctions.UserMonitorWorkflow), name); log.LogInformation("Started new monitor workflow for user {user}", name); return(new OkResult()); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest request, [OrchestrationClient] IDurableOrchestrationClient entityClient, TraceWriter log) { var code = request.Query["code"]; var state = request.Query["state"]; var error = request.Query["error"]; var errorDescription = request.Query["error_description"]; var clientId = Environment.GetEnvironmentVariable("LinkedInClientId", EnvironmentVariableTarget.Process); var clientSecret = Environment.GetEnvironmentVariable("LinkedInClientSecret", EnvironmentVariableTarget.Process); var redirectUri = RedirectUri.Generate(request); var accessToken = await _proxy.AccessToken(code, redirectUri, clientId, clientSecret); var me = await _proxy.Me(accessToken.AccessToken); var userData = new UserData { PersonId = me.PersonId, AccessToken = accessToken.AccessToken, Expires = accessToken.Expires }; var entityId = new EntityId(nameof(User), state); await entityClient.SignalEntityAsync(entityId, "", userData, "default"); return(new OkObjectResult("Done - you can close ths window")); }
public static async Task userUpdated( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "providers/DotNetDevOps.LetsEncrypt/challenges/{token}")] HttpRequestMessage req, [OrchestrationClient] IDurableOrchestrationClient starter, string token, ILogger log) { await starter.SignalEntityAsync(new EntityId("Authorization", token), nameof(AuthorizationActor.AuthorizationCompleted)); }
public static Task ClearVotes( [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "votes")] HttpRequest req, [OrchestrationClient] IDurableOrchestrationClient client, ILogger log) { return(client.SignalEntityAsync(DefaultEntityId, "clear", "")); }
public static async Task <IActionResult> HttpTrigger( [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpTriggerArgs args, [OrchestrationClient] IDurableOrchestrationClient durableOrchestrationClient, ILogger log) { // 'orchestrationId = DeviceId' > tricky stuff, make sure the orchestrationId is deterministic but also unique and has now weird characters var orchestrationId = args.DeviceId; var status = await durableOrchestrationClient.GetStatusAsync(orchestrationId); // Maybe do this from within the Orchestrator var entity = new EntityId(nameof(DeviceEntity), args.DeviceId); await durableOrchestrationClient.SignalEntityAsync(entity, "UpdateLastCommunicationDateTime"); switch (status?.RuntimeStatus) { case OrchestrationRuntimeStatus.Running: case OrchestrationRuntimeStatus.Pending: case OrchestrationRuntimeStatus.ContinuedAsNew: await durableOrchestrationClient.RaiseEventAsync(orchestrationId, "MessageReceived", null); break; default: await durableOrchestrationClient.StartNewAsync(nameof(WaitingOrchestrator), orchestrationId, new OrchestratorArgs { DeviceId = args.DeviceId }); break; } log.LogInformation("Started orchestration with ID = '{orchestrationId}'.", orchestrationId); var response = durableOrchestrationClient.CreateHttpManagementPayload(orchestrationId); return(new OkObjectResult(response)); }
public static async Task CreateRoom( [ActivityTrigger] string username, [OrchestrationClient] IDurableOrchestrationClient client, [Queue(Global.QUEUE)] IAsyncCollector <string> console, ILogger logger) { logger.LogInformation("Create room for user {user}", username); var room = _roomMaker.GetNewRoom(); var id = username.AsEntityIdFor <Room>(); await client.SignalEntityAsync <IRoomOperations>(id, operation => operation.New(room.Name)); await client.SignalEntityAsync <IRoomOperations>(id, operation => operation.SetDescription(room.Description)); await console.AddAsync($"{room.Name} has been prepared for {username}!"); logger.LogInformation("Creation of {room} for user {user} successful", room.Name, username); }
public static async Task <IActionResult> SendMail( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "mail/send")] MailMessage message, [OrchestrationClient] IDurableOrchestrationClient client) { await client.SignalEntityAsync(new EntityId(nameof(MailEntity), Guid.NewGuid().ToString()), "Send", message); return(new OkResult()); }
public static async Task <IActionResult> ResendMail( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "mail/resend/{id}")] HttpRequest req, string id, [OrchestrationClient] IDurableOrchestrationClient client) { await client.SignalEntityAsync(new EntityId(nameof(MailEntity), id), "Resend"); return(new OkResult()); }
public static Task IncrementVote( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "votes/{choice}/incr")] HttpRequest req, [OrchestrationClient] IDurableOrchestrationClient client, string choice, ILogger log) { if (!VotingEntity.Choices.Contains(choice)) { throw new ArgumentException($"{choice} is not a valid choice"); } return(client.SignalEntityAsync(DefaultEntityId, "incr", choice)); }
public static async Task PlaceInventoryOnMonster( [ActivityTrigger] string username, [OrchestrationClient] IDurableOrchestrationClient client, [Queue(Global.QUEUE)] IAsyncCollector <string> console, ILogger logger) { logger.LogInformation("Placing inventory on monster for {user}", username); var inventoryNames = await username.GetEntityForUserOrThrow <InventoryList>(client); var inventoryList = await inventoryNames.DeserializeListForUserWithClient(username, client); var inventory = inventoryList .Where(i => i.IsTreasure) .Select(i => i).First(); var monster = await username.GetEntityForUserOrThrow <Monster>(client); logger.LogInformation("Found treasure {inventory} for monster {monster} and user {user}", inventory.Name, monster.Name, username); await client.SignalEntityAsync <IInventoryOperations>( username.AsEntityIdFor <Inventory>(inventory.Name), operation => operation.SetMonster(monster.Name)); await client.SignalEntityAsync <IMonsterOperations>( username.AsEntityIdFor <Monster>(), operation => operation.AddInventory(inventory.Name)); logger.LogInformation("Placing treasure {inventory} on monster {monster} for user {user} successful.", inventory.Name, monster.Name, username); await console.AddAsync($"{username} notices a {monster.Name} with a {inventory.Name}."); }
public static async Task CreateMonster( [ActivityTrigger] string username, [OrchestrationClient] IDurableOrchestrationClient client, [Queue(Global.QUEUE)] IAsyncCollector <string> console, ILogger logger) { logger.LogInformation("Create monster for user {user}", username); var monster = _monsterMaker.GetNewMonster(); var id = username.AsEntityIdFor <Monster>(); await client.SignalEntityAsync <IMonsterOperations>(id, operation => operation.New(monster.Name)); await console.AddAsync($"Look out! {monster.Name} is now stalking {username}!"); logger.LogInformation("Created monster {monster} for user {user} successful", monster.Name, username); }
public static async Task <IActionResult> WebhookReceiver( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "webhook/receiver")] HttpRequest req, [OrchestrationClient] IDurableOrchestrationClient client) { var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var eventPayloads = JsonConvert.DeserializeObject <EventPayload[]>(requestBody); foreach (var payload in eventPayloads) { await client.SignalEntityAsync(new EntityId(nameof(MailEntity), payload.EntityKey), "UpdateStatus", payload.Event); } return(new OkResult()); }
public async Task <IActionResult> FlagFailure( [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "circuit/{circuitId}/failure")] HttpRequest req, string circuitId, [OrchestrationClient] IDurableOrchestrationClient client, ILogger log) { log.LogInformation($"HTTP Trigger for failure fired for circuit {circuitId}"); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var data = JsonConvert.DeserializeObject <FailureRequest>(requestBody); // Set the time the request was processed data.FailureTime = DateTime.UtcNow; await client.SignalEntityAsync(new EntityId(nameof(CircuitEntity), circuitId), nameof(CircuitEntity.AddFailure), data); return(new AcceptedResult()); }
public static async Task GameMonitorWorkflow( [OrchestrationTrigger] IDurableOrchestrationContext context, [OrchestrationClient] IDurableOrchestrationClient client, ILogger logger) { var username = context.GetInput <string>(); logger.LogInformation("Start of game monitor workflow for {user}", username); var monsterKilled = context.WaitForExternalEvent(KILLMONSTER); var treasureFound = context.WaitForExternalEvent(GOTTREASURE); await Task.WhenAll(monsterKilled, treasureFound); await client.SignalEntityAsync( UserCounter.Id, UserCounter.UserDone); await context.CallActivityAsync(nameof(ConsoleFunctions.AddToQueue), $"{username} has won the game!"); logger.LogInformation("User {user} won the game.", username); }
public static async Task PlaceUserInRoom( [ActivityTrigger] string username, [OrchestrationClient] IDurableOrchestrationClient client, [Queue(Global.QUEUE)] IAsyncCollector <string> console, ILogger logger) { logger.LogInformation("Placing user in room for {user}", username); var room = await username.GetEntityForUserOrThrow <Room>(client); logger.LogInformation("Found room {room} for user {username}", room.Name, username); await client.SignalEntityAsync <IUserOperations>( username.AsEntityIdFor <User>(), operation => operation.SetRoom(room.Name)); logger.LogInformation("Placed user {user} in room {room}.", username, room.Name); await console.AddAsync($"{username} looks around: {room.Description}"); }
public static Task Run( [TimerTrigger("*/15 * * * * *")] TimerInfo myTimer, [OrchestrationClient] IDurableOrchestrationClient client) { return(client.SignalEntityAsync(HttpFunctions.DefaultEntityId, "noop", "")); }
public Task Signal(EntityId entityId, string operationName, object operationInput) { return(_client.SignalEntityAsync(entityId, operationName, operationInput)); }
public static async Task <string[]> GetAuthorizationsActivity( [ActivityTrigger] IDurableActivityContext ctx, [OrchestrationClient] IDurableOrchestrationClient starter, ILogger log) { var input = ctx.GetInput <CreateOrderOrchestratorInput>(); var entity = await starter.ReadEntityStateAsync <AcmeContextState>(input.EntityId); var context = new AcmeContext(entity.EntityState.LetsEncryptEndpoint, KeyFactory.FromPem(entity.EntityState.Pem)); var orderCtx = context.Order(new Uri(input.OrderLocation)); var order = await orderCtx.Resource(); if (order.Status == Certes.Acme.Resource.OrderStatus.Invalid || order.Status == Certes.Acme.Resource.OrderStatus.Valid) { //Valid means that its been finalized and we need a new one. throw new Exception("Bad order state"); } var authorizations = await orderCtx.Authorizations(); // var authorizationEntiy = new EntityId("Authorization",input.EntityId.EntityKey); var list = new List <string>(); if (!input.UseDns01Authorization) { foreach (var authorizationCtx in authorizations) { var challengeContext = await authorizationCtx.Http(); await starter.SignalEntityAsync(new EntityId("Authorization", challengeContext.Token), nameof(AuthorizationActor.AuthorizeHttp), new AuthorizeHttpInput { KeyAuthz = challengeContext.KeyAuthz, // Token = challengeContext.Token, OrchestratorId = ctx.InstanceId, AuthorizationLocation = authorizationCtx.Location, EntityId = input.EntityId, }); list.Add(challengeContext.Token); } } else { foreach (var authorizationCtx in authorizations) { var challengeContext = await authorizationCtx.Dns(); var authorization = await authorizationCtx.Resource(); await starter.SignalEntityAsync(new EntityId("Authorization", challengeContext.Token), nameof(AuthorizationActor.AuthorizeDns), new AuthorizeDnsInput { Name = $"_acme-challenge.{authorization.Identifier.Value}", // Token = challengeContext.Token, DnsTxt = context.AccountKey.DnsTxt(challengeContext.Token), AuthorizationLocation = authorizationCtx.Location, OrchestratorId = ctx.InstanceId, EntityId = input.EntityId }); list.Add(challengeContext.Token); } } return(list.ToArray()); // return order; }
private static async Task <IActionResult> GetMethod( IAsyncCollector <string> console, IDurableOrchestrationClient client, string name, string target) { if (string.IsNullOrEmpty(target)) { await console.AddAsync($"User {name} tried to get nothing."); return(new BadRequestObjectResult("Target is required.")); } var room = await name.GetEntityForUserOrThrow <Room>(client); if (room.InventoryList.Contains(target)) { // room loses inventory await client.SignalEntityAsync <IRoomOperations>( name.AsEntityIdFor <Room>(), operation => operation.RemoveInventory(target)); // user gains inventory await client.SignalEntityAsync <IUserOperations>( name.AsEntityIdFor <User>(), operation => operation.AddInventory(target)); // inventory moves to user await client.SignalEntityAsync <IInventoryOperations>( name.AsEntityIdFor <Inventory>(target), operation => operation.SetUser()); var list = await name.GetEntityForUserOrThrow <InventoryList>(client); var inventoryList = await list.DeserializeListForUserWithClient(name, client); var inventory = inventoryList.Where(i => i.Name == target) .Select(i => i).First(); await console.AddAsync($"User {name} successfully grabbed {target}."); if (inventory.IsTreasure) { await console.AddAsync($"User {name} nabbed the treasure."); var gameMonitor = await Global.FindJob( client, DateTime.UtcNow, nameof(MonitorFunctions.GameMonitorWorkflow), name, true, false); if (gameMonitor != null) { await client.RaiseEventAsync(gameMonitor.InstanceId, MonitorFunctions.GOTTREASURE); } } return(new OkResult()); } else { await console.AddAsync($"User {name} tried to get a {target} that wasn't there."); return(new BadRequestObjectResult("Target not found.")); } }
private static async Task <IActionResult> KillMethod( IAsyncCollector <string> console, IDurableOrchestrationClient client, string name, string target, string with, User userCheck) { if (string.IsNullOrEmpty(target)) { await console.AddAsync($"User {name} tried to kill nothing."); return(new BadRequestObjectResult("Target is required.")); } if (string.IsNullOrEmpty(with)) { await console.AddAsync($"User {name} tried to kill {target} with no weapon."); return(new BadRequestObjectResult("With is required.")); } if (!userCheck.InventoryList.Contains(with)) { await console.AddAsync($"User {name} tried to use a non-existing {with}."); return(new BadRequestObjectResult($"User doesn't have {with}")); } var monster = await name.GetEntityForUserOrThrow <Monster>(client); if (!monster.IsAlive) { await console.AddAsync($"User {name} tried to kill an already dead {target}."); return(new BadRequestObjectResult($"{target} is already dead.")); } var monsterInventory = monster.InventoryList[0]; var inventoryNames = await name.GetEntityForUserOrThrow <InventoryList>(client); var room = await name.GetEntityForUserOrThrow <Room>(client); // monster dies await client.SignalEntityAsync <IMonsterOperations>( name.AsEntityIdFor <Monster>(), operation => operation.Kill()); // monster drops inventory, inventory => room await client.SignalEntityAsync <IInventoryOperations>( name.AsEntityIdFor <Inventory>(monsterInventory), operation => operation.SetRoom(room.Name)); // add inventory to room await client.SignalEntityAsync <IRoomOperations>( name.AsEntityIdFor <Room>(), operation => operation.AddInventory(monsterInventory)); await console.AddAsync($"User {name} valiantly killed {target} with {with}."); await console.AddAsync($"User {name} notices {target} dropped a {monsterInventory}."); var gameMonitor = await Global.FindJob( client, DateTime.UtcNow, nameof(MonitorFunctions.GameMonitorWorkflow), name, true, false); if (gameMonitor != null) { await client.RaiseEventAsync(gameMonitor.InstanceId, MonitorFunctions.KILLMONSTER); } return(new OkResult()); }