public static async Task AcknowledgeTripViaQueueTrigger( [DurableClient] IDurableClient context, [QueueTrigger("%TripDriversQueue%", Connection = "AzureWebJobsStorage")] TripDriver info, ILogger log) { try { await context.RaiseEventAsync(info.TripCode, Constants.TRIP_DRIVER_ACCEPT_EVENT, info.DriverCode); } catch (Exception ex) { var error = $"AcknowledgeTripViaQueueTrigger failed: {ex.Message}"; log.LogError(error); } }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "start/{functionName}/{value}")] HttpRequestMessage req, [DurableClient] IDurableClient starter, string functionName, string value, ILogger log) { var instanceId = await starter.StartNewAsync(functionName, new { City = value }); log.LogInformation($"Started orchestration with ID = '{instanceId}'."); return(await starter.WaitForCompletionOrCreateCheckStatusResponseAsync(req, instanceId)); //return starter.CreateCheckStatusResponse(req, instanceId); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, methods: "post", Route = "newrfp")] HttpRequestMessage req, [DurableClient] IDurableClient starter, ILogger log) { log.LogInformation("HTTP trigger received for function"); // Function input comes from the request content. object eventData = await req.Content.ReadAsAsync <object>(); string instanceId = await starter.StartNewAsync("RFPNotificationOrchestrator", eventData); log.LogInformation($"Started orchestration with ID = '{instanceId}'."); return(starter.CreateCheckStatusResponse(req, instanceId)); }
public static async Task Run( [BlobTrigger("csv/{id}-{name}.csv", Connection = "challenge06_STORAGE")] Stream myBlob, [DurableClient] IDurableClient entityClient, string name, string id, ILogger log) { // myBlob. log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes"); var entityId = new EntityId("Counter", id); log.LogInformation(name); await entityClient.SignalEntityAsync(entityId, "add", 0); }
public static async Task <IActionResult> CreateInventoryItem( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "store/inventory")] HttpRequest req, [DurableClient] IDurableClient client, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var item = JsonConvert.DeserializeObject <InventoryItem>(requestBody); var target = new EntityId(nameof(InventoryEntity), "onestore"); await client.SignalEntityAsync <IInventory>(target, async x => await x.CreateItemAsync(item)); return(new AcceptedResult()); }
public static async Task <HttpResponseMessage> FanInOut_HttpStart( [HttpTrigger(AuthorizationLevel.Function, methods: "post", Route = "FanInOut/orchestrators/{functionName}")] HttpRequestMessage req, [DurableClient] IDurableClient starter, string functionName, ILogger log) { // Function input comes from the request content. object eventData = await req.Content.ReadAsAsync <object>(); string instanceId = await starter.StartNewAsync(functionName, eventData); log.LogInformation($"Started orchestration with ID = '{instanceId}'."); return(starter.CreateCheckStatusResponse(req, instanceId)); }
public static async Task CreateMonster( [ActivityTrigger] string username, [DurableClient] IDurableClient 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 async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "start/{orchestratorName}/")] HttpRequestMessage req, [DurableClient] IDurableClient orchestrationClient, string orchestratorName, ILogger log) { var orchestratorInput = await req.Content.ReadAsAsync <object>(); var instanceId = await orchestrationClient.StartNewAsync( orchestratorName, orchestratorInput); return(orchestrationClient.CreateCheckStatusResponse(req, instanceId)); }
// Adds 'lastEvent' field to each entity private static IEnumerable <ExpandedOrchestrationStatus> ExpandStatus(this IEnumerable <DurableOrchestrationStatus> orchestrations, IDurableClient client, FilterClause filterClause, HashSet <string> hiddenColumns) { // Deliberately explicitly enumerating orchestrations here, to trigger all GetStatusAsync tasks in parallel. // If just using yield return, they would be started and finished sequentially, one by one. var list = new List <ExpandedOrchestrationStatus>(); foreach (var orchestration in orchestrations) { list.Add(new ExpandedOrchestrationStatus(orchestration, client.GetStatusAsync(orchestration.InstanceId, true, false, false), hiddenColumns)); } return(list); }
protected async Task <DurableOrchestrationStatus> StartOrchestrationAsync( string name, object?input = null, string?instanceId = null) { IDurableClient client = await this.GetDurableClientAsync(); instanceId = await client.StartNewAsync(name, instanceId ?? Guid.NewGuid().ToString("N"), input); TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(10); DurableOrchestrationStatus status = await client.WaitForStartAsync(instanceId, timeout); Assert.NotNull(status); return(status); }
internal static async Task <ICommand> GetCommandAsync(this IDurableClient durableClient, Guid commandId) { if (durableClient is null) { throw new ArgumentNullException(nameof(durableClient)); } var commandStatus = await durableClient .GetStatusAsync(commandId.ToString()) .ConfigureAwait(false); return(commandStatus?.Input?.HasValues ?? false ? commandStatus.Input.ToObject <ICommand>() : null); }
public static async Task <IActionResult> NewUser( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, [Queue(Global.QUEUE)] IAsyncCollector <string> console, [DurableClient] IDurableClient 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 Dequeue( [QueueTrigger(CommandHandler.ProcessorQueue)] QueueMessage commandMessage, [Queue(CommandHandler.ProcessorQueue)] IAsyncCollector <ICommand> commandQueue, [Queue(CommandHandler.MonitorQueue)] IAsyncCollector <string> commandMonitor, [DurableClient] IDurableClient durableClient, ILogger log) { if (commandMessage is null) { throw new ArgumentNullException(nameof(commandMessage)); } if (commandQueue is null) { throw new ArgumentNullException(nameof(commandQueue)); } if (commandMonitor is null) { throw new ArgumentNullException(nameof(commandMonitor)); } if (durableClient is null) { throw new ArgumentNullException(nameof(durableClient)); } if (log is null) { throw new ArgumentNullException(nameof(log)); } try { var command = TeamCloudSerialize.DeserializeObject <ICommand>(commandMessage.Body.ToString()); command.Validate(validatorProvider, throwOnValidationError: true); _ = await ProcessCommandAsync(durableClient, command, commandQueue, commandMonitor, log) .ConfigureAwait(false); } catch (Exception exc) { log.LogError(exc, $"Failed to process queued command: {exc.Message}"); throw; } }
public async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "startandwait/{orchestratorName}")] HttpRequestMessage request, [DurableClient] IDurableClient orchestratorClient, string orchestratorName, ILogger log) { var orchestratorInput = await request.Content.ReadAsAsync <object>(); string instanceId = await orchestratorClient.StartNewAsync( orchestratorName, orchestratorInput); log.LogInformation($"Started Orchestrator with ID = '{instanceId}'..."); var timeoutTime = GetTimeSpan(request, TimeoutQueryStringKey); var retryIntervalTime = GetTimeSpan(request, RetryIntervalQueryStringKey); HttpResponseMessage responseMessage = null; if (timeoutTime == TimeSpan.Zero && retryIntervalTime == TimeSpan.Zero) { // Wait using the default values in the Durable Functions extension (10 sec timeout, 1 sec interval): responseMessage = await orchestratorClient.WaitForCompletionOrCreateCheckStatusResponseAsync( request, instanceId); } if (timeoutTime != TimeSpan.Zero && retryIntervalTime == TimeSpan.Zero) { // Wait until the specified timeoutTime: responseMessage = await orchestratorClient.WaitForCompletionOrCreateCheckStatusResponseAsync( request, instanceId, timeoutTime); } if (timeoutTime != TimeSpan.Zero && retryIntervalTime != TimeSpan.Zero) { // Wait until the specified timeoutTime and check every retryIntervalTime: responseMessage = await orchestratorClient.WaitForCompletionOrCreateCheckStatusResponseAsync( request, instanceId, timeoutTime, retryIntervalTime); } return(responseMessage); }
public Task <IActionResult> DfmGetOrchestrationTabMarkupFunction( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = Globals.ApiRoutePrefix + "/orchestrations('{instanceId}')/custom-tab-markup('{templateName}')")] HttpRequest req, [DurableClient(TaskHub = Globals.HubNameRouteParamName)] IDurableClient defaultDurableClient, string connName, string hubName, string instanceId, string templateName, ILogger log) { return(this.HandleAuthAndErrors(defaultDurableClient, req, connName, hubName, log, async(durableClient) => { var status = await GetInstanceStatusWithHistory(connName, instanceId, durableClient, log); if (status == null) { return new NotFoundObjectResult($"Instance {instanceId} doesn't exist"); } // The underlying Task never throws, so it's OK. var templatesMap = await CustomTemplates.GetTabTemplatesAsync(); string templateCode = templatesMap.GetTemplate(status.GetEntityTypeName(), templateName); if (templateCode == null) { return new NotFoundObjectResult("The specified template doesn't exist"); } try { var fluidTemplate = new FluidParser().Parse(templateCode); var options = new TemplateOptions(); options.MemberAccessStrategy.Register <JObject, object>((obj, fieldName) => obj[fieldName]); options.ValueConverters.Add(x => x is JObject obj ? new ObjectValue(obj) : null); options.ValueConverters.Add(x => x is JValue val ? val.Value : null); string fluidResult = fluidTemplate.Render(new TemplateContext(status, options)); return new ContentResult() { Content = fluidResult, ContentType = "text/html; charset=UTF-8" }; } catch (Exception ex) { return new BadRequestObjectResult(ex.Message); } })); }
public static async Task <IActionResult> StartManyMixedOrchestrations( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, [DurableClient] IDurableClient starter, ILogger log) { if (!int.TryParse(req.Query["count"], out int count) || count < 1) { return(new BadRequestObjectResult("A 'count' query string parameter is required and it must contain a positive number.")); } string initialPrefix = (string)req.Query["prefix"] ?? string.Empty; string finalPrefix = await Common.ScheduleManyInstances(starter, log, nameof(MixedOrchestration), count, initialPrefix); return(new OkObjectResult($"Scheduled {count} orchestrations prefixed with '{finalPrefix}'.")); }
public static async Task <IActionResult> StartManySequences( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, [DurableClient] IDurableClient starter, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); if (!int.TryParse(req.Query["count"], out int count) || count < 1) { return(new BadRequestObjectResult("A 'count' query string parameter is required and it must contain a positive number.")); } string prefix = await Common.ScheduleManyInstances(starter, nameof(HelloSequence), count, log); return(new OkObjectResult($"Scheduled {count} orchestrations prefixed with '{prefix}'.")); }
public async Task <IActionResult> AddHistory( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", "put", "delete", Route = "bins/{binId}")] HttpRequest req, [DurableClient] IDurableClient client, string binId) { var bin = this._helper.GetBin(binId); var history = await this._helper.GetRequestAsync(req); await client.SignalEntityAsync <IBin>(bin, o => o.Add(history)); var nav = BinNavigation.Parse(binId, req.IsHttps, req.Host.ToString()); var result = new JsonObjectContentResult(HttpStatusCode.Accepted, nav); return(result); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "callback/{instanceId}")] HttpRequest request, [DurableClient] IDurableClient durableClient, string instanceId, ILogger log) { var commandResultJson = await request.ReadAsStringAsync().ConfigureAwait(false); var commandResult = JsonConvert.DeserializeObject <ICommandResult>(commandResultJson); await durableClient .RaiseEventAsync(instanceId, commandResult.CommandId.ToString(), commandResult) .ConfigureAwait(false); return(new OkResult()); }
public static async Task <HttpResponseMessage> Start( [HttpTrigger(AuthorizationLevel.Function, methods: "post", Route = "StartSubOrchestrationFanOutFanIn")] HttpRequestMessage req, [DurableClient] IDurableClient starter, ILogger log) { int num = await req.Content.ReadAsAsync <int>(); if (num <= 0) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "A positive integer was expected in the request body.")); } string instanceId = await starter.StartNewAsync("FanOutFanInOrchestration", (object)num); log.LogWarning("Started FanOutFanInOrchestration orchestration with ID = '" + instanceId + "'."); return(starter.CreateCheckStatusResponse(req, instanceId)); }
public static async Task <IActionResult> StartManySequences( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, [DurableClient] IDurableClient starter, ILogger log) { if (!int.TryParse(req.Query["count"], out int count) || count < 1) { return(new BadRequestObjectResult("A 'count' query string parameter is required and it must contain a positive number.")); } string orchestratorName = nameof(ManySequencesOrchestrator); string instanceId = $"{orchestratorName}-{DateTime.UtcNow:yyyyMMdd-hhmmss}"; await starter.StartNewAsync(orchestratorName, instanceId, count); return(starter.CreateCheckStatusResponse(req, instanceId)); }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "appointment-manager")] HttpRequest req, [DurableClient] IDurableClient durableClient, ILogger log) { var clientAppointment = new ClientAppointment { ClientId = Guid.NewGuid(), AppointmentId = Guid.NewGuid(), PhoneNumber = "+00011112222" }; string instanceId = await durableClient.StartNewAsync(nameof(AppointmentSchedulingOrchestrator), clientAppointment); return(durableClient.CreateCheckStatusResponse(req, instanceId)); }
public static async Task <HttpResponseMessage> DeleteCart( [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "mycart")] HttpRequestMessage req, [DurableClient] IDurableClient client, ClaimsPrincipal claimsPrincipal) { var username = claimsPrincipal.FindFirst("name").Value; var entityId = new EntityId("CartEntity", username); var awaiter = client.GetDeletedAwaiter(entityId); await client.SignalEntityAsync <ICartActions>(entityId, x => x.Delete()); await client.CancelTimeoutAsync(entityId); await awaiter.SignalsProcessed(); return(req.CreateResponse(HttpStatusCode.Accepted)); }
public static async Task StartFunctionWithTaskHub( [DurableClient(TaskHub = "%TestTaskHub%")] IDurableClient client, string functionName, string instanceId, object input, TestDurableClient[] clientRef) { DateTime instanceCreationTime = DateTime.UtcNow; instanceId = await client.StartNewAsync(functionName, instanceId, input); clientRef[0] = new TestDurableClient( client, functionName, instanceId, instanceCreationTime); }
public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest request, [DurableClient] IDurableClient client, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); // Extract input from the POST body string requestBody = await new StreamReader(request.Body).ReadToEndAsync(); var commandBody = JsonConvert.DeserializeObject <SteamCommandBody>(requestBody); SteamCommandProcessor processor = new SteamCommandProcessor(commandBody.SteamWebApiKey); var appList = await GetOrSetAppListAsync(client, processor); var responseMessage = await processor.ProcessCommandAsync(commandBody.Command, appList); return(new OkObjectResult(responseMessage)); }
public async Task <IActionResult> HttpStart( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "api/dns-zones")] HttpRequest req, [DurableClient] IDurableClient starter, ILogger log) { if (!User.IsAppAuthorized()) { return(Unauthorized()); } // Function input comes from the request content. var instanceId = await starter.StartNewAsync(nameof(GetDnsZones) + "_" + nameof(Orchestrator)); log.LogInformation($"Started orchestration with ID = '{instanceId}'."); return(await starter.WaitForCompletionOrCreateCheckStatusResponseAsync(req, instanceId, TimeSpan.FromMinutes(1), returnInternalServerErrorOnFailure : true)); }
public static async Task <IActionResult> Increment( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = nameof(Increment))] HttpRequest req, [DurableClient] IDurableClient client) { try { string entityKey = await new StreamReader(req.Body).ReadToEndAsync(); var entityId = new EntityId("Counter", entityKey); await client.SignalEntityAsync(entityId, "add", 1); return(new OkObjectResult($"increment was sent to {entityId}.\n")); } catch (Exception e) { return(new OkObjectResult(e.ToString())); } }
public async Task <HttpResponseMessage> PayrunProcessInOrderOverall_HttpStart( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestMessage req, [DurableClient] IDurableClient starter, ILogger log) { var clientId = (_random.Next(1, 100) % 5 + 1).ToString(); var payrunId = _database.StringIncrement($"client::{clientId}"); var request = new Request { ClientId = clientId, PayrunId = payrunId }; string instanceId = await starter.StartNewAsync(nameof(RunOrchestrator), request); log.LogWarning($"Started orchestration for instance: {instanceId}, client: {clientId}, payrun: {payrunId}."); return(starter.CreateCheckStatusResponse(req, instanceId)); }
public async Task <IActionResult> GetCertificates_HttpStart( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "get-certificates")] HttpRequest req, [DurableClient] IDurableClient starter, ILogger log) { if (!User.Identity.IsAuthenticated) { return(Unauthorized()); } // Function input comes from the request content. string instanceId = await starter.StartNewAsync(nameof(GetCertificates), null); log.LogInformation($"Started orchestration with ID = '{instanceId}'."); return(await starter.WaitForCompletionOrCreateCheckStatusResponseAsync(req, instanceId, TimeSpan.FromMinutes(1))); }
public static async Task <HttpResponseMessage> UserChirpsPost( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "user/{userId}/chirps")] HttpRequestMessage req, [DurableClient] IDurableClient client, ILogger log, string userId) { Authenticate(req, userId); var chirp = new Chirp() { UserId = userId, Timestamp = DateTime.UtcNow, Content = await req.Content.ReadAsStringAsync(), }; await client.SignalEntityAsync <IUserChirps>(userId, x => x.Add(chirp)); return(req.CreateResponse(HttpStatusCode.Accepted, chirp)); }