elsa-core/src/modules/Elsa.Http/Activities/SendHttpRequestBase.cs

300 lines
13 KiB
C#
Raw Normal View History

using System.Net;
using System.Net.Http.Headers;
using Elsa.Extensions;
using Elsa.Http.ContentWriters;
Add a more generic UIHandler to customize how inputAttributes can be handle by UI (#4688) * add a more generic UIHandler to customize how inputAttributes can be handle by the ui * Add IPropertyUIHandlerResolver and update PropertyUIHandlerResolver Introduced a new interface, IPropertyUIHandlerResolver, to resolve UI options for a property. Refactored PropertyUIHandlerResolver to implement this interface and removed the unnecessary partial class structure. Also, cleaned up some unnecessary usings in various files for better code organization. * Refactor variable name and description in InputDescriptor The 'uISpecifications' variable in the InputDescriptor model is renamed to 'uiSpecifications' for better readability. Additionally, the associated comment was revised to explain that the dictionary is used by the UI. * "Refactor codebase for improved organization and cleaner architecture" The codebase has been significantly refactored, moving several classes to more appropriate namespaces for improved organization and cleaner architecture. This includes shifting UI hint handlers, activities, and memory-related components, amongst others. The changes should improve code readability and maintainability, but as this is a broad refactoring effort, thorough regression testing is advised. * Add CheckList UIHint with associated handler and provider This update introduces a new UIHint called CheckList to the Elsa.Workflows.Core. This includes the necessary handler and provider classes. The handler is registered in the WorkflowsFeature.cs, and the CheckList UIHint key has been added to the InputUIHints.cs. Various associated files have been created in both the Elsa.Api.Client and Elsa.Workflows.Core project to support this new UIHint. --------- Co-authored-by: Jérémie DEVILLARD <jdevillard@users.noreply.github.com> Co-authored-by: Sipke Schoorstra <sipkeschoorstra@outlook.com>
2023-12-26 17:56:29 +00:00
using Elsa.Http.UIHints;
using Elsa.Workflows;
using Elsa.Workflows.Attributes;
using Elsa.Workflows.UIHints;
using Elsa.Workflows.Models;
Optimize Workflow Execution and Messaging (#5243) * Add conditional index triggers in workflow populator The trigger indexing in the workflow populator is now conditional. A boolean parameter has been added to the PopulateStoreAsync and AddAsync methods to determine whether to index triggers or not. Additionally, some code cleanups and refactoring have been made for efficient and cleaner code. * Update method call in DefaultWorkflowRegistry The method `AddAsync` in `DefaultWorkflowRegistry` has been updated to include a new first parameter set to true. This change aligns with recent modifications to the `AddAsync` method signature, ensuring proper function execution. * Add new branch triggers to GitHub workflow The updated GitHub workflow now includes triggers for branches with 'feat/*', 'enh/*', 'perf/*', 'hotfix/*', and 'chore/*' prefixes. This is to ensure that the workflow runs not only for the main, feature, issue, bug, enhancement, patch, and fix branches, but also on all new branches, improving coverage and visibility on all changes. * Add FindByIdAsync method to WorkflowInstanceManager This commit introduces a new method, FindByIdAsync, to the WorkflowInstanceManager service. This method fetches a WorkflowInstance using its Id. Also, an interface declaration for the new method is added to IWorkflowInstanceManager. * Refactor workflow definitions and add indexTriggers parameter The code for creating workflow definition filters has been refactored for brevity. Additionally, two sets of overloaded methods named `PopulateStoreAsync` and `AddAsync` were added to "IWorkflowDefinitionStorePopulator" and implemented in "DefaultWorkflowDefinitionStorePopulator". These methods allow specifying whether triggers should be indexed. * Refactor WorkflowDefinitionActivity code The refactoring is focused on an improved way of finding and passing ActivityDescriptor within WorkflowDefinitionActivity class. Previously, the service provider was passed to the DeclareInputAsVariables and DeclareOutputAsVariables methods, leading to a less readable and harder to maintain code. Now, we pass the ActivityDescriptor directly, making the code easier to understand and modify. * Update PolymorphicObjectConverter exception handling Fixes have been applied to the PolymorphicObjectConverter by adding the handling of TargetException. Additionally, the System.Reflection namespace has been included, and the addSetMethod invocation for the HashSet has been streamlined for better readability and performance. * Remove unnecessary whitespace in PersistWorkflowExecutionLogMiddleware This change simply removes an unneeded line of whitespace in the corresponding Middleware file. This change is consistent with the goal of maintaining clean and easy-to-read code. * Refactor MassTransitWorkflowDispatcher and add new methods Systematic refactor of the MassTransitWorkflowDispatcher class which initially focused on restructuring the DispatchAsync methods. New methods have been added that deal specifically with triggering and bookmarking workflows thus enhancing the readability of the code while also improving its autonomous function. The logging for non-found workflows has been improved as well. * Update event handler names in Workflow cache eviction Evicting the cache prior to triggers being indexed fixes a bug where publishing workflow changes would not result in new triggers being found. * Update Async calls and mark obsolete messages The commit adjusts calls to AddAsync in DefaultWorkflowRegistry and DispatchAsync in DefaultWorkflowInbox to improve readability. Also, it marks DispatchResumeWorkflows and DispatchTriggerWorkflows in the Elsa.MassTransit.Messages namespace as obsolete, indicating their pending removal in future releases. * Refactor workflow dispatch code to a separate method The changes remove duplication and improve readability by extracting the code responsible for dispatching a workflow into a separate method called DispatchWorkflowAsync. This method creates a workflow instance, gets the send endpoint, and then sends the message. * Refactor exception handling in PolymorphicObjectConverter This commit simplifies the two separate catch blocks for NotSupportedException and TargetException into a single block using the new 'or' pattern in C#. It also makes minor adjustments to improve the clarity and readability of the code relating to the 'addSetMethod' invocation. * Update src/modules/Elsa.MassTransit/Services/MassTransitWorkflowDispatcher.cs Co-authored-by: raymonddenhaan <155616759+raymonddenhaan@users.noreply.github.com> * Fix an attempt to dispatch bookmark ID instead of workflow instance ID The MassTransitWorkflowDispatcher.cs file is updated to improve readability and clarity. This includes changing the way bookmark and trigger filter objects are initialized, by breaking down the single-line initialization into multiple lines. Additionally, some logic has been updated in the DispatchBookmarksAsync function for better handling of workflow instance properties and input merging. * Add logging to SendHttpRequestBase The SendHttpRequestBase activity in the Elsa.Http module is updated to utilize the ILogger service. This extension enables the capture of HttpRequestException and TaskCanceledException events and logs their warnings, providing insight into potential issues during HTTP request sending. --------- Co-authored-by: raymonddenhaan <155616759+raymonddenhaan@users.noreply.github.com>
2024-04-18 23:06:52 +00:00
using Microsoft.Extensions.Logging;
using Polly;
using HttpHeaders = Elsa.Http.Models.HttpHeaders;
namespace Elsa.Http;
/// <summary>
/// Base class for activities that send HTTP requests.
/// </summary>
2023-09-22 09:13:23 +00:00
[Output(IsSerializable = false)]
public abstract class SendHttpRequestBase : Activity<HttpResponseMessage>
{
/// <inheritdoc />
protected SendHttpRequestBase(string? source = default, int? line = default) : base(source, line)
{
}
2023-10-12 12:20:15 +00:00
/// <summary>
/// The URL to send the request to.
/// </summary>
[Input] public Input<Uri?> Url { get; set; } = default!;
/// <summary>
/// The HTTP method to use when sending the request.
/// </summary>
[Input(
Description = "The HTTP method to use when sending the request.",
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
Options = new[]
{
"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"
},
DefaultValue = "GET",
Add a more generic UIHandler to customize how inputAttributes can be handle by UI (#4688) * add a more generic UIHandler to customize how inputAttributes can be handle by the ui * Add IPropertyUIHandlerResolver and update PropertyUIHandlerResolver Introduced a new interface, IPropertyUIHandlerResolver, to resolve UI options for a property. Refactored PropertyUIHandlerResolver to implement this interface and removed the unnecessary partial class structure. Also, cleaned up some unnecessary usings in various files for better code organization. * Refactor variable name and description in InputDescriptor The 'uISpecifications' variable in the InputDescriptor model is renamed to 'uiSpecifications' for better readability. Additionally, the associated comment was revised to explain that the dictionary is used by the UI. * "Refactor codebase for improved organization and cleaner architecture" The codebase has been significantly refactored, moving several classes to more appropriate namespaces for improved organization and cleaner architecture. This includes shifting UI hint handlers, activities, and memory-related components, amongst others. The changes should improve code readability and maintainability, but as this is a broad refactoring effort, thorough regression testing is advised. * Add CheckList UIHint with associated handler and provider This update introduces a new UIHint called CheckList to the Elsa.Workflows.Core. This includes the necessary handler and provider classes. The handler is registered in the WorkflowsFeature.cs, and the CheckList UIHint key has been added to the InputUIHints.cs. Various associated files have been created in both the Elsa.Api.Client and Elsa.Workflows.Core project to support this new UIHint. --------- Co-authored-by: Jérémie DEVILLARD <jdevillard@users.noreply.github.com> Co-authored-by: Sipke Schoorstra <sipkeschoorstra@outlook.com>
2023-12-26 17:56:29 +00:00
UIHint = InputUIHints.DropDown
)]
public Input<string> Method { get; set; } = new("GET");
/// <summary>
/// The content to send with the request. Can be a string, an object, a byte array or a stream.
/// </summary>
[Input(Description = "The content to send with the request. Can be a string, an object, a byte array or a stream.")]
public Input<object?> Content { get; set; } = default!;
/// <summary>
/// The content type to use when sending the request.
/// </summary>
[Input(
Description = "The content type to use when sending the request.",
Add a more generic UIHandler to customize how inputAttributes can be handle by UI (#4688) * add a more generic UIHandler to customize how inputAttributes can be handle by the ui * Add IPropertyUIHandlerResolver and update PropertyUIHandlerResolver Introduced a new interface, IPropertyUIHandlerResolver, to resolve UI options for a property. Refactored PropertyUIHandlerResolver to implement this interface and removed the unnecessary partial class structure. Also, cleaned up some unnecessary usings in various files for better code organization. * Refactor variable name and description in InputDescriptor The 'uISpecifications' variable in the InputDescriptor model is renamed to 'uiSpecifications' for better readability. Additionally, the associated comment was revised to explain that the dictionary is used by the UI. * "Refactor codebase for improved organization and cleaner architecture" The codebase has been significantly refactored, moving several classes to more appropriate namespaces for improved organization and cleaner architecture. This includes shifting UI hint handlers, activities, and memory-related components, amongst others. The changes should improve code readability and maintainability, but as this is a broad refactoring effort, thorough regression testing is advised. * Add CheckList UIHint with associated handler and provider This update introduces a new UIHint called CheckList to the Elsa.Workflows.Core. This includes the necessary handler and provider classes. The handler is registered in the WorkflowsFeature.cs, and the CheckList UIHint key has been added to the InputUIHints.cs. Various associated files have been created in both the Elsa.Api.Client and Elsa.Workflows.Core project to support this new UIHint. --------- Co-authored-by: Jérémie DEVILLARD <jdevillard@users.noreply.github.com> Co-authored-by: Sipke Schoorstra <sipkeschoorstra@outlook.com>
2023-12-26 17:56:29 +00:00
UIHandler = typeof(HttpContentTypeOptionsProvider),
UIHint = InputUIHints.DropDown
)]
public Input<string?> ContentType { get; set; } = default!;
/// <summary>
/// The Authorization header value to send with the request.
/// </summary>
/// <example>Bearer {some-access-token}</example>
[Input(Description = "The Authorization header value to send with the request. For example: Bearer {some-access-token}", Category = "Security")]
public Input<string?> Authorization { get; set; } = default!;
/// <summary>
/// A value that allows to add the Authorization header without validation.
/// </summary>
[Input(Description = "A value that allows to add the Authorization header without validation.", Category = "Security")]
public Input<bool> DisableAuthorizationHeaderValidation { get; set; } = default!;
/// <summary>
/// The headers to send along with the request.
/// </summary>
[Input(
Description = "The headers to send along with the request.",
UIHint = InputUIHints.JsonEditor,
Category = "Advanced"
)]
public Input<HttpHeaders?> RequestHeaders { get; set; } = new(new HttpHeaders());
/// <summary>
/// Indicates whether resiliency mechanisms should be enabled for the HTTP request.
/// </summary>
public Input<bool> EnableResiliency { get; set; } = default!;
Merge 3.0.1 (#4759) * Update packages.yml for version 3.0.1 The packages.yml workflow file has been updated to target the v3.0.1 branch instead of main. The version also has been updated from 3.0.0 to 3.0.1 in the version prediction logic. Hotfix tags usage has been removed. * Update git branch for commit verification in workflow The Github workflow's step for verifying commits' existence has been updated. Instead of searching in the 'origin/main' branch, the workflow now checks in the 'origin/v3.0.1' branch. This modification ensures compatibility and consistency with the version being used. * Update Elsa.Studio package versions The Elsa.Studio and Elsa.Studio.Login.BlazorWasm packages in the Elsa.ServerAndStudio.Web and Elsa.Studio.Web projects have been updated from version 3.0.0-preview.177 to the stable version 3.0.0. This is to ensure we're using the stable and reliable versions of these packages in our projects. * Add background execution to activities and update HTTP requests Significantly enhanced the capabilities of background execution of activities. Included a change in activity type of "SendHttpRequest" from 'Task' to 'Action'. Introduced new classes for handling outcomes of context in background execution. Made some necessary adjustments to HTTP Request Task to handle sending HTTP requests from a background task. Updated several middleware classes to align with these modifications. * Add background execution handling to activity context This commit adds the ability to manage the background execution state directly within the activity execution context. This includes adding methods to set and verify the background execution state, and modifying the existing code to use these new methods. A method for handling activity scheduling during background execution has also been started, but its implementation is not finished yet. The HTTP Request activities were updated accordingly to reflect these changes. * Add scheduling function for background activities This commit achieves two main goals. Firstly, it introduces two new classes called ScheduledActivity and ScheduledActivityOptions to store scheduled activities' information. Secondly, it modifies how activities are executed in the background by capturing the scheduling information as a serializable format and storing it in the workflow execution context properties dictionary. This change allows the workflow execution context to resume the activity execution context. * Refactor HTTP request handling by removing SendHttpRequestTask SendHttpRequestTask was deleted and its functionality was merged into SendHttpRequestBase. This consolidation led to the addition of StatusCode and ResponseHeaders output fields in SendHttpRequestBase. Another change includes the update in FlowSendHttpRequest to indicate that it's no longer deprecated. Also, HttpHeaders class was extended to accommodate HttpResponseHeaders objects. The consolidation was done to streamline the HTTP request handling process. * Update GitHub Actions workflow for new release The GitHub Actions workflow configuration has been updated to target the '3.0.1' branch instead of 'main'. Furthermore, the preview version set in the workflow has been updated to '3.0.1-preview', changing from the previous '3.0.0-preview'. * Update branch verification in GitHub workflow The GitHub workflow configuration has been updated to verify that the commit exists in the branch 'origin/3.0.1' instead of 'origin/main'. This is done during the automated package generation process. * New options to control retry logic for transient failures (#4750) * Add an option to control the number of automatic retries for transient failures. * Add SleepDurationProvider option for ElsaClientBuilderOptions --------- Co-authored-by: admin <admin@admin.com> * Add IExecuteWorkflowApi interface and refine retry policy configuration A new interface, IExecuteWorkflowApi, was created to handle execution and dispatch of workflow definitions. This breaks down functionalities previously present in IWorkflowDefinitionsApi. Also, the retry policy configuration for HTTP requests has been refactored. Instead of hardcoding retry settings, now a delegate method can be optionally passed to customize the behavior. This makes it more flexible and shifts the responsibility of configuring retry policies to the client. * Add option for synchronous broadcast in WorkflowInbox This update introduces a new option to control synchronicity when broadcasting messages in the WorkflowInbox. The 'BroadcastWorkflowInboxMessageOptions' class allows the developer to specify whether the broadcasting will occur synchronously or asynchronously. The update also includes a new Endpoint and Workflow for demonstration and testing of this functionality. * Update FastEndpoints packages to version 5.21.2 The current commit updates the version of all FastEndpoints packages from 5.20.1.7-beta to 5.21.2 in the 'Elsa.Api.Common' project. This ensures we are using the most recent stable release of these packages. #4747 * Add decimal check in PolymorphicObjectConverter In the PolymorphicObjectConverter class, the check for primitive types and specific object types was updated to include decimal. Fixes #4714 * Refactor Dapper workflow and update migrations Modified the store service to optimize the SaveManyAsync method by converting input to list only once. Also, enhanced deletion query in the store service to enable usage of different primary keys. Made changes in the Dapper migrations, replacing "NodeId" with "ActivityNodeId". * Update workflow to use main branch and version 3.1.0 The workflow has been updated to work with updates on the 'main' branch rather than the 'v3.0.1' branch. Also, the version number for the 'VERSION' variable in preview mode has been updated to 3.1.0 from 3.0.1. * Remove unnecessary Elsa Server activities Deleted sample files: DataSourceActivity, MyEndpoint, and MyEventWorkflow from the Elsa Server Web bundle as part of our ongoing codebase optimization strategy. These files were no longer required and their removal simplifies our code structure. * Update package workflow to reference v3.0.1 The GitHub actions workflow has been updated to pull from branch v3.0.1 instead of main. This change affects the commit verification and version setting steps, now using version 3.0.1-preview in the workflow process. * Update Elsa.Studio packages to version 3.0.1-preview.196 This commit involves updating the versions of `Elsa.Studio`, `Elsa.Studio.Core.BlazorWasm`, and `Elsa.Studio.Login.BlazorWasm` packages in `Elsa.ServerAndStudio.Web.csproj` and `ElsaStudioWebAssembly.csproj` files to 3.0.1-preview.196. This update will incorporate the new changes and improvements included in this newer version. * Update Elsa.Studio package versions The Elsa.Studio and Elsa.Studio.Login.BlazorWasm package versions have been updated in the Elsa.Studio.Web project. Both package versions have been upgraded from 3.0.0 to 3.0.1-preview.196. * Remove unused Workflow models and simplify AddStorageDriver method The commit removes BackgroundExecutionOutcome and BackgroundExecutionResult models from Elsa.Workflows.Core, as they are no longer in use. Additionally, it simplifies the AddStorageDriver extension method in ModuleExtensions.cs, now it directly adds the service as an implementation of the IStorageDriver interface. * Remove unnecessary dependencies in DefaultBackgroundActivityInvoker Dependencies on IBookmarksPersister and IWorkflowStateExtractor have been removed in the DefaultBackgroundActivityInvoker.cs file. Additionally, an unused `using` statement for Elsa.Workflows.Helpers has been eliminated. This commit aims to declutter the code and increase its maintainability by eliminating unnecessary dependencies. --------- Co-authored-by: Night Wu <lofrank@outlook.com> Co-authored-by: admin <admin@admin.com>
2024-01-06 16:26:25 +00:00
/// <summary>
/// The HTTP response status code
/// </summary>
[Output(Description = "The HTTP response status code")]
public Output<int> StatusCode { get; set; } = default!;
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
/// <summary>
/// The parsed content, if any.
/// </summary>
[Output(Description = "The parsed content, if any.")]
public Output<object?> ParsedContent { get; set; } = default!;
Merge 3.0.1 (#4759) * Update packages.yml for version 3.0.1 The packages.yml workflow file has been updated to target the v3.0.1 branch instead of main. The version also has been updated from 3.0.0 to 3.0.1 in the version prediction logic. Hotfix tags usage has been removed. * Update git branch for commit verification in workflow The Github workflow's step for verifying commits' existence has been updated. Instead of searching in the 'origin/main' branch, the workflow now checks in the 'origin/v3.0.1' branch. This modification ensures compatibility and consistency with the version being used. * Update Elsa.Studio package versions The Elsa.Studio and Elsa.Studio.Login.BlazorWasm packages in the Elsa.ServerAndStudio.Web and Elsa.Studio.Web projects have been updated from version 3.0.0-preview.177 to the stable version 3.0.0. This is to ensure we're using the stable and reliable versions of these packages in our projects. * Add background execution to activities and update HTTP requests Significantly enhanced the capabilities of background execution of activities. Included a change in activity type of "SendHttpRequest" from 'Task' to 'Action'. Introduced new classes for handling outcomes of context in background execution. Made some necessary adjustments to HTTP Request Task to handle sending HTTP requests from a background task. Updated several middleware classes to align with these modifications. * Add background execution handling to activity context This commit adds the ability to manage the background execution state directly within the activity execution context. This includes adding methods to set and verify the background execution state, and modifying the existing code to use these new methods. A method for handling activity scheduling during background execution has also been started, but its implementation is not finished yet. The HTTP Request activities were updated accordingly to reflect these changes. * Add scheduling function for background activities This commit achieves two main goals. Firstly, it introduces two new classes called ScheduledActivity and ScheduledActivityOptions to store scheduled activities' information. Secondly, it modifies how activities are executed in the background by capturing the scheduling information as a serializable format and storing it in the workflow execution context properties dictionary. This change allows the workflow execution context to resume the activity execution context. * Refactor HTTP request handling by removing SendHttpRequestTask SendHttpRequestTask was deleted and its functionality was merged into SendHttpRequestBase. This consolidation led to the addition of StatusCode and ResponseHeaders output fields in SendHttpRequestBase. Another change includes the update in FlowSendHttpRequest to indicate that it's no longer deprecated. Also, HttpHeaders class was extended to accommodate HttpResponseHeaders objects. The consolidation was done to streamline the HTTP request handling process. * Update GitHub Actions workflow for new release The GitHub Actions workflow configuration has been updated to target the '3.0.1' branch instead of 'main'. Furthermore, the preview version set in the workflow has been updated to '3.0.1-preview', changing from the previous '3.0.0-preview'. * Update branch verification in GitHub workflow The GitHub workflow configuration has been updated to verify that the commit exists in the branch 'origin/3.0.1' instead of 'origin/main'. This is done during the automated package generation process. * New options to control retry logic for transient failures (#4750) * Add an option to control the number of automatic retries for transient failures. * Add SleepDurationProvider option for ElsaClientBuilderOptions --------- Co-authored-by: admin <admin@admin.com> * Add IExecuteWorkflowApi interface and refine retry policy configuration A new interface, IExecuteWorkflowApi, was created to handle execution and dispatch of workflow definitions. This breaks down functionalities previously present in IWorkflowDefinitionsApi. Also, the retry policy configuration for HTTP requests has been refactored. Instead of hardcoding retry settings, now a delegate method can be optionally passed to customize the behavior. This makes it more flexible and shifts the responsibility of configuring retry policies to the client. * Add option for synchronous broadcast in WorkflowInbox This update introduces a new option to control synchronicity when broadcasting messages in the WorkflowInbox. The 'BroadcastWorkflowInboxMessageOptions' class allows the developer to specify whether the broadcasting will occur synchronously or asynchronously. The update also includes a new Endpoint and Workflow for demonstration and testing of this functionality. * Update FastEndpoints packages to version 5.21.2 The current commit updates the version of all FastEndpoints packages from 5.20.1.7-beta to 5.21.2 in the 'Elsa.Api.Common' project. This ensures we are using the most recent stable release of these packages. #4747 * Add decimal check in PolymorphicObjectConverter In the PolymorphicObjectConverter class, the check for primitive types and specific object types was updated to include decimal. Fixes #4714 * Refactor Dapper workflow and update migrations Modified the store service to optimize the SaveManyAsync method by converting input to list only once. Also, enhanced deletion query in the store service to enable usage of different primary keys. Made changes in the Dapper migrations, replacing "NodeId" with "ActivityNodeId". * Update workflow to use main branch and version 3.1.0 The workflow has been updated to work with updates on the 'main' branch rather than the 'v3.0.1' branch. Also, the version number for the 'VERSION' variable in preview mode has been updated to 3.1.0 from 3.0.1. * Remove unnecessary Elsa Server activities Deleted sample files: DataSourceActivity, MyEndpoint, and MyEventWorkflow from the Elsa Server Web bundle as part of our ongoing codebase optimization strategy. These files were no longer required and their removal simplifies our code structure. * Update package workflow to reference v3.0.1 The GitHub actions workflow has been updated to pull from branch v3.0.1 instead of main. This change affects the commit verification and version setting steps, now using version 3.0.1-preview in the workflow process. * Update Elsa.Studio packages to version 3.0.1-preview.196 This commit involves updating the versions of `Elsa.Studio`, `Elsa.Studio.Core.BlazorWasm`, and `Elsa.Studio.Login.BlazorWasm` packages in `Elsa.ServerAndStudio.Web.csproj` and `ElsaStudioWebAssembly.csproj` files to 3.0.1-preview.196. This update will incorporate the new changes and improvements included in this newer version. * Update Elsa.Studio package versions The Elsa.Studio and Elsa.Studio.Login.BlazorWasm package versions have been updated in the Elsa.Studio.Web project. Both package versions have been upgraded from 3.0.0 to 3.0.1-preview.196. * Remove unused Workflow models and simplify AddStorageDriver method The commit removes BackgroundExecutionOutcome and BackgroundExecutionResult models from Elsa.Workflows.Core, as they are no longer in use. Additionally, it simplifies the AddStorageDriver extension method in ModuleExtensions.cs, now it directly adds the service as an implementation of the IStorageDriver interface. * Remove unnecessary dependencies in DefaultBackgroundActivityInvoker Dependencies on IBookmarksPersister and IWorkflowStateExtractor have been removed in the DefaultBackgroundActivityInvoker.cs file. Additionally, an unused `using` statement for Elsa.Workflows.Helpers has been eliminated. This commit aims to declutter the code and increase its maintainability by eliminating unnecessary dependencies. --------- Co-authored-by: Night Wu <lofrank@outlook.com> Co-authored-by: admin <admin@admin.com>
2024-01-06 16:26:25 +00:00
/// <summary>
/// The response headers that were received.
/// </summary>
[Output(Description = "The response headers that were received.")]
public Output<HttpHeaders?> ResponseHeaders { get; set; } = default!;
/// <inheritdoc />
protected override async ValueTask ExecuteAsync(ActivityExecutionContext context)
{
await TrySendAsync(context);
}
/// <summary>
/// Handles the response.
/// </summary>
protected abstract ValueTask HandleResponseAsync(ActivityExecutionContext context, HttpResponseMessage response);
/// <summary>
/// Handles an exception that occurred while sending the request.
/// </summary>
protected abstract ValueTask HandleRequestExceptionAsync(ActivityExecutionContext context, HttpRequestException exception);
2023-10-12 12:20:15 +00:00
/// <summary>
/// Handles <see cref="TaskCanceledException"/> that occurred while sending the request.
/// </summary>
protected abstract ValueTask HandleTaskCanceledExceptionAsync(ActivityExecutionContext context, TaskCanceledException exception);
private async Task TrySendAsync(ActivityExecutionContext context)
{
Optimize Workflow Execution and Messaging (#5243) * Add conditional index triggers in workflow populator The trigger indexing in the workflow populator is now conditional. A boolean parameter has been added to the PopulateStoreAsync and AddAsync methods to determine whether to index triggers or not. Additionally, some code cleanups and refactoring have been made for efficient and cleaner code. * Update method call in DefaultWorkflowRegistry The method `AddAsync` in `DefaultWorkflowRegistry` has been updated to include a new first parameter set to true. This change aligns with recent modifications to the `AddAsync` method signature, ensuring proper function execution. * Add new branch triggers to GitHub workflow The updated GitHub workflow now includes triggers for branches with 'feat/*', 'enh/*', 'perf/*', 'hotfix/*', and 'chore/*' prefixes. This is to ensure that the workflow runs not only for the main, feature, issue, bug, enhancement, patch, and fix branches, but also on all new branches, improving coverage and visibility on all changes. * Add FindByIdAsync method to WorkflowInstanceManager This commit introduces a new method, FindByIdAsync, to the WorkflowInstanceManager service. This method fetches a WorkflowInstance using its Id. Also, an interface declaration for the new method is added to IWorkflowInstanceManager. * Refactor workflow definitions and add indexTriggers parameter The code for creating workflow definition filters has been refactored for brevity. Additionally, two sets of overloaded methods named `PopulateStoreAsync` and `AddAsync` were added to "IWorkflowDefinitionStorePopulator" and implemented in "DefaultWorkflowDefinitionStorePopulator". These methods allow specifying whether triggers should be indexed. * Refactor WorkflowDefinitionActivity code The refactoring is focused on an improved way of finding and passing ActivityDescriptor within WorkflowDefinitionActivity class. Previously, the service provider was passed to the DeclareInputAsVariables and DeclareOutputAsVariables methods, leading to a less readable and harder to maintain code. Now, we pass the ActivityDescriptor directly, making the code easier to understand and modify. * Update PolymorphicObjectConverter exception handling Fixes have been applied to the PolymorphicObjectConverter by adding the handling of TargetException. Additionally, the System.Reflection namespace has been included, and the addSetMethod invocation for the HashSet has been streamlined for better readability and performance. * Remove unnecessary whitespace in PersistWorkflowExecutionLogMiddleware This change simply removes an unneeded line of whitespace in the corresponding Middleware file. This change is consistent with the goal of maintaining clean and easy-to-read code. * Refactor MassTransitWorkflowDispatcher and add new methods Systematic refactor of the MassTransitWorkflowDispatcher class which initially focused on restructuring the DispatchAsync methods. New methods have been added that deal specifically with triggering and bookmarking workflows thus enhancing the readability of the code while also improving its autonomous function. The logging for non-found workflows has been improved as well. * Update event handler names in Workflow cache eviction Evicting the cache prior to triggers being indexed fixes a bug where publishing workflow changes would not result in new triggers being found. * Update Async calls and mark obsolete messages The commit adjusts calls to AddAsync in DefaultWorkflowRegistry and DispatchAsync in DefaultWorkflowInbox to improve readability. Also, it marks DispatchResumeWorkflows and DispatchTriggerWorkflows in the Elsa.MassTransit.Messages namespace as obsolete, indicating their pending removal in future releases. * Refactor workflow dispatch code to a separate method The changes remove duplication and improve readability by extracting the code responsible for dispatching a workflow into a separate method called DispatchWorkflowAsync. This method creates a workflow instance, gets the send endpoint, and then sends the message. * Refactor exception handling in PolymorphicObjectConverter This commit simplifies the two separate catch blocks for NotSupportedException and TargetException into a single block using the new 'or' pattern in C#. It also makes minor adjustments to improve the clarity and readability of the code relating to the 'addSetMethod' invocation. * Update src/modules/Elsa.MassTransit/Services/MassTransitWorkflowDispatcher.cs Co-authored-by: raymonddenhaan <155616759+raymonddenhaan@users.noreply.github.com> * Fix an attempt to dispatch bookmark ID instead of workflow instance ID The MassTransitWorkflowDispatcher.cs file is updated to improve readability and clarity. This includes changing the way bookmark and trigger filter objects are initialized, by breaking down the single-line initialization into multiple lines. Additionally, some logic has been updated in the DispatchBookmarksAsync function for better handling of workflow instance properties and input merging. * Add logging to SendHttpRequestBase The SendHttpRequestBase activity in the Elsa.Http module is updated to utilize the ILogger service. This extension enables the capture of HttpRequestException and TaskCanceledException events and logs their warnings, providing insight into potential issues during HTTP request sending. --------- Co-authored-by: raymonddenhaan <155616759+raymonddenhaan@users.noreply.github.com>
2024-04-18 23:06:52 +00:00
var logger = (ILogger)context.GetRequiredService(typeof(ILogger<>).MakeGenericType(GetType()));
var httpClientFactory = context.GetRequiredService<IHttpClientFactory>();
var httpClient = httpClientFactory.CreateClient(nameof(SendHttpRequestBase));
var cancellationToken = context.CancellationToken;
var resiliencyEnabled = EnableResiliency.GetOrDefault(context, () => false);
try
{
var response = await SendRequestAsync();
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
var parsedContent = await ParseContentAsync(context, response);
Merge 3.0.1 (#4759) * Update packages.yml for version 3.0.1 The packages.yml workflow file has been updated to target the v3.0.1 branch instead of main. The version also has been updated from 3.0.0 to 3.0.1 in the version prediction logic. Hotfix tags usage has been removed. * Update git branch for commit verification in workflow The Github workflow's step for verifying commits' existence has been updated. Instead of searching in the 'origin/main' branch, the workflow now checks in the 'origin/v3.0.1' branch. This modification ensures compatibility and consistency with the version being used. * Update Elsa.Studio package versions The Elsa.Studio and Elsa.Studio.Login.BlazorWasm packages in the Elsa.ServerAndStudio.Web and Elsa.Studio.Web projects have been updated from version 3.0.0-preview.177 to the stable version 3.0.0. This is to ensure we're using the stable and reliable versions of these packages in our projects. * Add background execution to activities and update HTTP requests Significantly enhanced the capabilities of background execution of activities. Included a change in activity type of "SendHttpRequest" from 'Task' to 'Action'. Introduced new classes for handling outcomes of context in background execution. Made some necessary adjustments to HTTP Request Task to handle sending HTTP requests from a background task. Updated several middleware classes to align with these modifications. * Add background execution handling to activity context This commit adds the ability to manage the background execution state directly within the activity execution context. This includes adding methods to set and verify the background execution state, and modifying the existing code to use these new methods. A method for handling activity scheduling during background execution has also been started, but its implementation is not finished yet. The HTTP Request activities were updated accordingly to reflect these changes. * Add scheduling function for background activities This commit achieves two main goals. Firstly, it introduces two new classes called ScheduledActivity and ScheduledActivityOptions to store scheduled activities' information. Secondly, it modifies how activities are executed in the background by capturing the scheduling information as a serializable format and storing it in the workflow execution context properties dictionary. This change allows the workflow execution context to resume the activity execution context. * Refactor HTTP request handling by removing SendHttpRequestTask SendHttpRequestTask was deleted and its functionality was merged into SendHttpRequestBase. This consolidation led to the addition of StatusCode and ResponseHeaders output fields in SendHttpRequestBase. Another change includes the update in FlowSendHttpRequest to indicate that it's no longer deprecated. Also, HttpHeaders class was extended to accommodate HttpResponseHeaders objects. The consolidation was done to streamline the HTTP request handling process. * Update GitHub Actions workflow for new release The GitHub Actions workflow configuration has been updated to target the '3.0.1' branch instead of 'main'. Furthermore, the preview version set in the workflow has been updated to '3.0.1-preview', changing from the previous '3.0.0-preview'. * Update branch verification in GitHub workflow The GitHub workflow configuration has been updated to verify that the commit exists in the branch 'origin/3.0.1' instead of 'origin/main'. This is done during the automated package generation process. * New options to control retry logic for transient failures (#4750) * Add an option to control the number of automatic retries for transient failures. * Add SleepDurationProvider option for ElsaClientBuilderOptions --------- Co-authored-by: admin <admin@admin.com> * Add IExecuteWorkflowApi interface and refine retry policy configuration A new interface, IExecuteWorkflowApi, was created to handle execution and dispatch of workflow definitions. This breaks down functionalities previously present in IWorkflowDefinitionsApi. Also, the retry policy configuration for HTTP requests has been refactored. Instead of hardcoding retry settings, now a delegate method can be optionally passed to customize the behavior. This makes it more flexible and shifts the responsibility of configuring retry policies to the client. * Add option for synchronous broadcast in WorkflowInbox This update introduces a new option to control synchronicity when broadcasting messages in the WorkflowInbox. The 'BroadcastWorkflowInboxMessageOptions' class allows the developer to specify whether the broadcasting will occur synchronously or asynchronously. The update also includes a new Endpoint and Workflow for demonstration and testing of this functionality. * Update FastEndpoints packages to version 5.21.2 The current commit updates the version of all FastEndpoints packages from 5.20.1.7-beta to 5.21.2 in the 'Elsa.Api.Common' project. This ensures we are using the most recent stable release of these packages. #4747 * Add decimal check in PolymorphicObjectConverter In the PolymorphicObjectConverter class, the check for primitive types and specific object types was updated to include decimal. Fixes #4714 * Refactor Dapper workflow and update migrations Modified the store service to optimize the SaveManyAsync method by converting input to list only once. Also, enhanced deletion query in the store service to enable usage of different primary keys. Made changes in the Dapper migrations, replacing "NodeId" with "ActivityNodeId". * Update workflow to use main branch and version 3.1.0 The workflow has been updated to work with updates on the 'main' branch rather than the 'v3.0.1' branch. Also, the version number for the 'VERSION' variable in preview mode has been updated to 3.1.0 from 3.0.1. * Remove unnecessary Elsa Server activities Deleted sample files: DataSourceActivity, MyEndpoint, and MyEventWorkflow from the Elsa Server Web bundle as part of our ongoing codebase optimization strategy. These files were no longer required and their removal simplifies our code structure. * Update package workflow to reference v3.0.1 The GitHub actions workflow has been updated to pull from branch v3.0.1 instead of main. This change affects the commit verification and version setting steps, now using version 3.0.1-preview in the workflow process. * Update Elsa.Studio packages to version 3.0.1-preview.196 This commit involves updating the versions of `Elsa.Studio`, `Elsa.Studio.Core.BlazorWasm`, and `Elsa.Studio.Login.BlazorWasm` packages in `Elsa.ServerAndStudio.Web.csproj` and `ElsaStudioWebAssembly.csproj` files to 3.0.1-preview.196. This update will incorporate the new changes and improvements included in this newer version. * Update Elsa.Studio package versions The Elsa.Studio and Elsa.Studio.Login.BlazorWasm package versions have been updated in the Elsa.Studio.Web project. Both package versions have been upgraded from 3.0.0 to 3.0.1-preview.196. * Remove unused Workflow models and simplify AddStorageDriver method The commit removes BackgroundExecutionOutcome and BackgroundExecutionResult models from Elsa.Workflows.Core, as they are no longer in use. Additionally, it simplifies the AddStorageDriver extension method in ModuleExtensions.cs, now it directly adds the service as an implementation of the IStorageDriver interface. * Remove unnecessary dependencies in DefaultBackgroundActivityInvoker Dependencies on IBookmarksPersister and IWorkflowStateExtractor have been removed in the DefaultBackgroundActivityInvoker.cs file. Additionally, an unused `using` statement for Elsa.Workflows.Helpers has been eliminated. This commit aims to declutter the code and increase its maintainability by eliminating unnecessary dependencies. --------- Co-authored-by: Night Wu <lofrank@outlook.com> Co-authored-by: admin <admin@admin.com>
2024-01-06 16:26:25 +00:00
var statusCode = (int)response.StatusCode;
var responseHeaders = new HttpHeaders(response.Headers);
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
context.Set(Result, response);
context.Set(ParsedContent, parsedContent);
Merge 3.0.1 (#4759) * Update packages.yml for version 3.0.1 The packages.yml workflow file has been updated to target the v3.0.1 branch instead of main. The version also has been updated from 3.0.0 to 3.0.1 in the version prediction logic. Hotfix tags usage has been removed. * Update git branch for commit verification in workflow The Github workflow's step for verifying commits' existence has been updated. Instead of searching in the 'origin/main' branch, the workflow now checks in the 'origin/v3.0.1' branch. This modification ensures compatibility and consistency with the version being used. * Update Elsa.Studio package versions The Elsa.Studio and Elsa.Studio.Login.BlazorWasm packages in the Elsa.ServerAndStudio.Web and Elsa.Studio.Web projects have been updated from version 3.0.0-preview.177 to the stable version 3.0.0. This is to ensure we're using the stable and reliable versions of these packages in our projects. * Add background execution to activities and update HTTP requests Significantly enhanced the capabilities of background execution of activities. Included a change in activity type of "SendHttpRequest" from 'Task' to 'Action'. Introduced new classes for handling outcomes of context in background execution. Made some necessary adjustments to HTTP Request Task to handle sending HTTP requests from a background task. Updated several middleware classes to align with these modifications. * Add background execution handling to activity context This commit adds the ability to manage the background execution state directly within the activity execution context. This includes adding methods to set and verify the background execution state, and modifying the existing code to use these new methods. A method for handling activity scheduling during background execution has also been started, but its implementation is not finished yet. The HTTP Request activities were updated accordingly to reflect these changes. * Add scheduling function for background activities This commit achieves two main goals. Firstly, it introduces two new classes called ScheduledActivity and ScheduledActivityOptions to store scheduled activities' information. Secondly, it modifies how activities are executed in the background by capturing the scheduling information as a serializable format and storing it in the workflow execution context properties dictionary. This change allows the workflow execution context to resume the activity execution context. * Refactor HTTP request handling by removing SendHttpRequestTask SendHttpRequestTask was deleted and its functionality was merged into SendHttpRequestBase. This consolidation led to the addition of StatusCode and ResponseHeaders output fields in SendHttpRequestBase. Another change includes the update in FlowSendHttpRequest to indicate that it's no longer deprecated. Also, HttpHeaders class was extended to accommodate HttpResponseHeaders objects. The consolidation was done to streamline the HTTP request handling process. * Update GitHub Actions workflow for new release The GitHub Actions workflow configuration has been updated to target the '3.0.1' branch instead of 'main'. Furthermore, the preview version set in the workflow has been updated to '3.0.1-preview', changing from the previous '3.0.0-preview'. * Update branch verification in GitHub workflow The GitHub workflow configuration has been updated to verify that the commit exists in the branch 'origin/3.0.1' instead of 'origin/main'. This is done during the automated package generation process. * New options to control retry logic for transient failures (#4750) * Add an option to control the number of automatic retries for transient failures. * Add SleepDurationProvider option for ElsaClientBuilderOptions --------- Co-authored-by: admin <admin@admin.com> * Add IExecuteWorkflowApi interface and refine retry policy configuration A new interface, IExecuteWorkflowApi, was created to handle execution and dispatch of workflow definitions. This breaks down functionalities previously present in IWorkflowDefinitionsApi. Also, the retry policy configuration for HTTP requests has been refactored. Instead of hardcoding retry settings, now a delegate method can be optionally passed to customize the behavior. This makes it more flexible and shifts the responsibility of configuring retry policies to the client. * Add option for synchronous broadcast in WorkflowInbox This update introduces a new option to control synchronicity when broadcasting messages in the WorkflowInbox. The 'BroadcastWorkflowInboxMessageOptions' class allows the developer to specify whether the broadcasting will occur synchronously or asynchronously. The update also includes a new Endpoint and Workflow for demonstration and testing of this functionality. * Update FastEndpoints packages to version 5.21.2 The current commit updates the version of all FastEndpoints packages from 5.20.1.7-beta to 5.21.2 in the 'Elsa.Api.Common' project. This ensures we are using the most recent stable release of these packages. #4747 * Add decimal check in PolymorphicObjectConverter In the PolymorphicObjectConverter class, the check for primitive types and specific object types was updated to include decimal. Fixes #4714 * Refactor Dapper workflow and update migrations Modified the store service to optimize the SaveManyAsync method by converting input to list only once. Also, enhanced deletion query in the store service to enable usage of different primary keys. Made changes in the Dapper migrations, replacing "NodeId" with "ActivityNodeId". * Update workflow to use main branch and version 3.1.0 The workflow has been updated to work with updates on the 'main' branch rather than the 'v3.0.1' branch. Also, the version number for the 'VERSION' variable in preview mode has been updated to 3.1.0 from 3.0.1. * Remove unnecessary Elsa Server activities Deleted sample files: DataSourceActivity, MyEndpoint, and MyEventWorkflow from the Elsa Server Web bundle as part of our ongoing codebase optimization strategy. These files were no longer required and their removal simplifies our code structure. * Update package workflow to reference v3.0.1 The GitHub actions workflow has been updated to pull from branch v3.0.1 instead of main. This change affects the commit verification and version setting steps, now using version 3.0.1-preview in the workflow process. * Update Elsa.Studio packages to version 3.0.1-preview.196 This commit involves updating the versions of `Elsa.Studio`, `Elsa.Studio.Core.BlazorWasm`, and `Elsa.Studio.Login.BlazorWasm` packages in `Elsa.ServerAndStudio.Web.csproj` and `ElsaStudioWebAssembly.csproj` files to 3.0.1-preview.196. This update will incorporate the new changes and improvements included in this newer version. * Update Elsa.Studio package versions The Elsa.Studio and Elsa.Studio.Login.BlazorWasm package versions have been updated in the Elsa.Studio.Web project. Both package versions have been upgraded from 3.0.0 to 3.0.1-preview.196. * Remove unused Workflow models and simplify AddStorageDriver method The commit removes BackgroundExecutionOutcome and BackgroundExecutionResult models from Elsa.Workflows.Core, as they are no longer in use. Additionally, it simplifies the AddStorageDriver extension method in ModuleExtensions.cs, now it directly adds the service as an implementation of the IStorageDriver interface. * Remove unnecessary dependencies in DefaultBackgroundActivityInvoker Dependencies on IBookmarksPersister and IWorkflowStateExtractor have been removed in the DefaultBackgroundActivityInvoker.cs file. Additionally, an unused `using` statement for Elsa.Workflows.Helpers has been eliminated. This commit aims to declutter the code and increase its maintainability by eliminating unnecessary dependencies. --------- Co-authored-by: Night Wu <lofrank@outlook.com> Co-authored-by: admin <admin@admin.com>
2024-01-06 16:26:25 +00:00
context.Set(StatusCode, statusCode);
context.Set(ResponseHeaders, responseHeaders);
await HandleResponseAsync(context, response);
}
2023-10-12 12:20:15 +00:00
catch (HttpRequestException e)
{
Optimize Workflow Execution and Messaging (#5243) * Add conditional index triggers in workflow populator The trigger indexing in the workflow populator is now conditional. A boolean parameter has been added to the PopulateStoreAsync and AddAsync methods to determine whether to index triggers or not. Additionally, some code cleanups and refactoring have been made for efficient and cleaner code. * Update method call in DefaultWorkflowRegistry The method `AddAsync` in `DefaultWorkflowRegistry` has been updated to include a new first parameter set to true. This change aligns with recent modifications to the `AddAsync` method signature, ensuring proper function execution. * Add new branch triggers to GitHub workflow The updated GitHub workflow now includes triggers for branches with 'feat/*', 'enh/*', 'perf/*', 'hotfix/*', and 'chore/*' prefixes. This is to ensure that the workflow runs not only for the main, feature, issue, bug, enhancement, patch, and fix branches, but also on all new branches, improving coverage and visibility on all changes. * Add FindByIdAsync method to WorkflowInstanceManager This commit introduces a new method, FindByIdAsync, to the WorkflowInstanceManager service. This method fetches a WorkflowInstance using its Id. Also, an interface declaration for the new method is added to IWorkflowInstanceManager. * Refactor workflow definitions and add indexTriggers parameter The code for creating workflow definition filters has been refactored for brevity. Additionally, two sets of overloaded methods named `PopulateStoreAsync` and `AddAsync` were added to "IWorkflowDefinitionStorePopulator" and implemented in "DefaultWorkflowDefinitionStorePopulator". These methods allow specifying whether triggers should be indexed. * Refactor WorkflowDefinitionActivity code The refactoring is focused on an improved way of finding and passing ActivityDescriptor within WorkflowDefinitionActivity class. Previously, the service provider was passed to the DeclareInputAsVariables and DeclareOutputAsVariables methods, leading to a less readable and harder to maintain code. Now, we pass the ActivityDescriptor directly, making the code easier to understand and modify. * Update PolymorphicObjectConverter exception handling Fixes have been applied to the PolymorphicObjectConverter by adding the handling of TargetException. Additionally, the System.Reflection namespace has been included, and the addSetMethod invocation for the HashSet has been streamlined for better readability and performance. * Remove unnecessary whitespace in PersistWorkflowExecutionLogMiddleware This change simply removes an unneeded line of whitespace in the corresponding Middleware file. This change is consistent with the goal of maintaining clean and easy-to-read code. * Refactor MassTransitWorkflowDispatcher and add new methods Systematic refactor of the MassTransitWorkflowDispatcher class which initially focused on restructuring the DispatchAsync methods. New methods have been added that deal specifically with triggering and bookmarking workflows thus enhancing the readability of the code while also improving its autonomous function. The logging for non-found workflows has been improved as well. * Update event handler names in Workflow cache eviction Evicting the cache prior to triggers being indexed fixes a bug where publishing workflow changes would not result in new triggers being found. * Update Async calls and mark obsolete messages The commit adjusts calls to AddAsync in DefaultWorkflowRegistry and DispatchAsync in DefaultWorkflowInbox to improve readability. Also, it marks DispatchResumeWorkflows and DispatchTriggerWorkflows in the Elsa.MassTransit.Messages namespace as obsolete, indicating their pending removal in future releases. * Refactor workflow dispatch code to a separate method The changes remove duplication and improve readability by extracting the code responsible for dispatching a workflow into a separate method called DispatchWorkflowAsync. This method creates a workflow instance, gets the send endpoint, and then sends the message. * Refactor exception handling in PolymorphicObjectConverter This commit simplifies the two separate catch blocks for NotSupportedException and TargetException into a single block using the new 'or' pattern in C#. It also makes minor adjustments to improve the clarity and readability of the code relating to the 'addSetMethod' invocation. * Update src/modules/Elsa.MassTransit/Services/MassTransitWorkflowDispatcher.cs Co-authored-by: raymonddenhaan <155616759+raymonddenhaan@users.noreply.github.com> * Fix an attempt to dispatch bookmark ID instead of workflow instance ID The MassTransitWorkflowDispatcher.cs file is updated to improve readability and clarity. This includes changing the way bookmark and trigger filter objects are initialized, by breaking down the single-line initialization into multiple lines. Additionally, some logic has been updated in the DispatchBookmarksAsync function for better handling of workflow instance properties and input merging. * Add logging to SendHttpRequestBase The SendHttpRequestBase activity in the Elsa.Http module is updated to utilize the ILogger service. This extension enables the capture of HttpRequestException and TaskCanceledException events and logs their warnings, providing insight into potential issues during HTTP request sending. --------- Co-authored-by: raymonddenhaan <155616759+raymonddenhaan@users.noreply.github.com>
2024-04-18 23:06:52 +00:00
logger.LogWarning(e, "An error occurred while sending an HTTP request");
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
context.AddExecutionLogEntry("Error", e.Message, payload: new
{
e.StackTrace
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
});
context.JournalData.Add("Error", e.Message);
await HandleRequestExceptionAsync(context, e);
}
catch (TaskCanceledException e)
{
Optimize Workflow Execution and Messaging (#5243) * Add conditional index triggers in workflow populator The trigger indexing in the workflow populator is now conditional. A boolean parameter has been added to the PopulateStoreAsync and AddAsync methods to determine whether to index triggers or not. Additionally, some code cleanups and refactoring have been made for efficient and cleaner code. * Update method call in DefaultWorkflowRegistry The method `AddAsync` in `DefaultWorkflowRegistry` has been updated to include a new first parameter set to true. This change aligns with recent modifications to the `AddAsync` method signature, ensuring proper function execution. * Add new branch triggers to GitHub workflow The updated GitHub workflow now includes triggers for branches with 'feat/*', 'enh/*', 'perf/*', 'hotfix/*', and 'chore/*' prefixes. This is to ensure that the workflow runs not only for the main, feature, issue, bug, enhancement, patch, and fix branches, but also on all new branches, improving coverage and visibility on all changes. * Add FindByIdAsync method to WorkflowInstanceManager This commit introduces a new method, FindByIdAsync, to the WorkflowInstanceManager service. This method fetches a WorkflowInstance using its Id. Also, an interface declaration for the new method is added to IWorkflowInstanceManager. * Refactor workflow definitions and add indexTriggers parameter The code for creating workflow definition filters has been refactored for brevity. Additionally, two sets of overloaded methods named `PopulateStoreAsync` and `AddAsync` were added to "IWorkflowDefinitionStorePopulator" and implemented in "DefaultWorkflowDefinitionStorePopulator". These methods allow specifying whether triggers should be indexed. * Refactor WorkflowDefinitionActivity code The refactoring is focused on an improved way of finding and passing ActivityDescriptor within WorkflowDefinitionActivity class. Previously, the service provider was passed to the DeclareInputAsVariables and DeclareOutputAsVariables methods, leading to a less readable and harder to maintain code. Now, we pass the ActivityDescriptor directly, making the code easier to understand and modify. * Update PolymorphicObjectConverter exception handling Fixes have been applied to the PolymorphicObjectConverter by adding the handling of TargetException. Additionally, the System.Reflection namespace has been included, and the addSetMethod invocation for the HashSet has been streamlined for better readability and performance. * Remove unnecessary whitespace in PersistWorkflowExecutionLogMiddleware This change simply removes an unneeded line of whitespace in the corresponding Middleware file. This change is consistent with the goal of maintaining clean and easy-to-read code. * Refactor MassTransitWorkflowDispatcher and add new methods Systematic refactor of the MassTransitWorkflowDispatcher class which initially focused on restructuring the DispatchAsync methods. New methods have been added that deal specifically with triggering and bookmarking workflows thus enhancing the readability of the code while also improving its autonomous function. The logging for non-found workflows has been improved as well. * Update event handler names in Workflow cache eviction Evicting the cache prior to triggers being indexed fixes a bug where publishing workflow changes would not result in new triggers being found. * Update Async calls and mark obsolete messages The commit adjusts calls to AddAsync in DefaultWorkflowRegistry and DispatchAsync in DefaultWorkflowInbox to improve readability. Also, it marks DispatchResumeWorkflows and DispatchTriggerWorkflows in the Elsa.MassTransit.Messages namespace as obsolete, indicating their pending removal in future releases. * Refactor workflow dispatch code to a separate method The changes remove duplication and improve readability by extracting the code responsible for dispatching a workflow into a separate method called DispatchWorkflowAsync. This method creates a workflow instance, gets the send endpoint, and then sends the message. * Refactor exception handling in PolymorphicObjectConverter This commit simplifies the two separate catch blocks for NotSupportedException and TargetException into a single block using the new 'or' pattern in C#. It also makes minor adjustments to improve the clarity and readability of the code relating to the 'addSetMethod' invocation. * Update src/modules/Elsa.MassTransit/Services/MassTransitWorkflowDispatcher.cs Co-authored-by: raymonddenhaan <155616759+raymonddenhaan@users.noreply.github.com> * Fix an attempt to dispatch bookmark ID instead of workflow instance ID The MassTransitWorkflowDispatcher.cs file is updated to improve readability and clarity. This includes changing the way bookmark and trigger filter objects are initialized, by breaking down the single-line initialization into multiple lines. Additionally, some logic has been updated in the DispatchBookmarksAsync function for better handling of workflow instance properties and input merging. * Add logging to SendHttpRequestBase The SendHttpRequestBase activity in the Elsa.Http module is updated to utilize the ILogger service. This extension enables the capture of HttpRequestException and TaskCanceledException events and logs their warnings, providing insight into potential issues during HTTP request sending. --------- Co-authored-by: raymonddenhaan <155616759+raymonddenhaan@users.noreply.github.com>
2024-04-18 23:06:52 +00:00
logger.LogWarning(e, "An error occurred while sending an HTTP request");
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
context.AddExecutionLogEntry("Error", e.Message, payload: new
{
e.StackTrace
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
});
context.JournalData.Add("Cancelled", true);
await HandleTaskCanceledExceptionAsync(context, e);
}
return;
async Task<HttpResponseMessage> SendRequestAsync()
{
if (resiliencyEnabled)
{
var pipeline = BuildResiliencyPipeline(context);
return await pipeline.ExecuteAsync(async ct => await SendRequestAsyncCore(ct), cancellationToken);
}
return await SendRequestAsyncCore();
}
async Task<HttpResponseMessage> SendRequestAsyncCore(CancellationToken ct = default)
{
var request = PrepareRequest(context);
return await httpClient.SendAsync(request, ct);
}
}
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
private async Task<object?> ParseContentAsync(ActivityExecutionContext context, HttpResponseMessage httpResponse)
{
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
var httpContent = httpResponse.Content;
if (!HasContent(httpContent))
return null;
var cancellationToken = context.CancellationToken;
var targetType = ParsedContent.GetTargetType(context);
var contentStream = await httpContent.ReadAsStreamAsync(cancellationToken);
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
var responseHeaders = httpResponse.Headers;
var contentHeaders = httpContent.Headers;
var contentType = contentHeaders.ContentType?.MediaType!;
targetType ??= contentType switch
{
"application/json" => typeof(object),
_ => typeof(string)
};
Add HTTP file download activity and supporting classes (#5608) * Add HTTP file download activity and supporting classes This commit adds a new activity, DownloadHttpFile, which provides the capability to download a file from a specified URL. It introduces supporting classes like HttpFile, FileHttpContentParser, and several extensions methods related to handling HTTP headers and file content. It also contains necessary updates in existing classes to accommodate the new file-download feature. * Add response stream to context in DownloadHttpFile In DownloadHttpFile.cs, context data now includes response content's file stream. Changes to DefaultDownloadableManager.cs simplify the return statement when no provider is found, directly returning an empty array. * Add byte array converter and enhance HTTP file download A new ByteArrayConverter class has been added to Elsa.JavaScript that converts byte arrays to Uint8Arrays. In Elsa.Http, the DownloadHttpFile activity now also stores the downloaded file's content in bytes. In addition, various new type aliases have been added to the Elsa.Http and Elsa.JavaScript modules, making it easier to handle non-string responses and the transfer of data. * Update Elsa.Studio package versions The package versions for Elsa.Studio, Elsa.Studio.Core.BlazorWasm, and Elsa.Studio.Login.BlazorWasm have been updated from 3.2.0-preview.346 to 3.2.0 * Update Jint version and adjust configuration Updated the Jint package version to 4.0.0-preview-644. Also, added the Jint Preview package source in the NuGet configuration. Furthermore, made a change to use ArrayBuffer instead of Uint8Array in ByteArrayConverter.cs to align with the updated Jint version.
2024-06-15 18:31:58 +00:00
var contentHeadersDictionary = contentHeaders.ToDictionary(x => x.Key, x => x.Value.Cast<string?>().ToArray(), StringComparer.OrdinalIgnoreCase);
var responseHeadersDictionary = responseHeaders.ToDictionary(x => x.Key, x => x.Value.Cast<string?>().ToArray(), StringComparer.OrdinalIgnoreCase);
var headersDictionary = contentHeadersDictionary.Concat(responseHeadersDictionary).ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase);
return await context.ParseContentAsync(contentStream, contentType, targetType, headersDictionary, cancellationToken);
}
private static bool HasContent(HttpContent httpContent) => httpContent.Headers.ContentLength > 0;
private HttpRequestMessage PrepareRequest(ActivityExecutionContext context)
{
var method = Method.GetOrDefault(context) ?? "GET";
var url = Url.Get(context);
var request = new HttpRequestMessage(new(method), url);
var headers = context.GetHeaders(RequestHeaders);
var authorization = Authorization.GetOrDefault(context);
var addAuthorizationWithoutValidation = DisableAuthorizationHeaderValidation.GetOrDefault(context);
if (!string.IsNullOrWhiteSpace(authorization))
if (addAuthorizationWithoutValidation)
request.Headers.TryAddWithoutValidation("Authorization", authorization);
else
request.Headers.Authorization = AuthenticationHeaderValue.Parse(authorization);
foreach (var header in headers)
request.Headers.Add(header.Key, header.Value.AsEnumerable());
var contentType = ContentType.GetOrDefault(context);
var content = Content.GetOrDefault(context);
if (contentType != null && content != null)
{
2023-10-12 12:20:15 +00:00
var factories = context.GetServices<IHttpContentFactory>();
var factory = SelectContentWriter(contentType, factories);
request.Content = factory.CreateHttpContent(content, contentType);
}
return request;
}
2023-10-12 12:20:15 +00:00
private IHttpContentFactory SelectContentWriter(string? contentType, IEnumerable<IHttpContentFactory> factories)
{
if (string.IsNullOrWhiteSpace(contentType))
return new JsonContentFactory();
var parsedContentType = new System.Net.Mime.ContentType(contentType);
return factories.FirstOrDefault(httpContentFactory => httpContentFactory.SupportedContentTypes.Any(c => c == parsedContentType.MediaType)) ?? new JsonContentFactory();
}
private ResiliencePipeline<HttpResponseMessage> BuildResiliencyPipeline(ActivityExecutionContext context)
{
var pipelineBuilder = new ResiliencePipelineBuilder<HttpResponseMessage>()
.AddRetry(new()
{
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
.Handle<TimeoutException>() // Specific timeout exception
.Handle<HttpRequestException>(ex => IsTransientStatusCode(ex.StatusCode)) // Network errors or transient HTTP codes
.HandleResult(response => IsTransientStatusCode(response.StatusCode)),
MaxRetryAttempts = 4,
UseJitter = false, // If enabled, adds a random value between -25% and +25% of the calculated Delay, except if BackoffType is Exponential, where a DecorrelatedJitterBackoffV2 formula is used for jitter calculation. That formula is based on Polly.Contrib.WaitAndRetry.
Delay = TimeSpan.FromSeconds(1),
BackoffType = DelayBackoffType.Exponential // Delay * 2^AttemptNumber, e.g. [ 2s, 4s, 8s, 16s ]. Total secs: 2 + 4 + 8 + 16 = 32.
// If BackoffType is Exponential, then the calculated Delay is multiplied by a random value between -25% and +25% of the calculated Delay, except if BackoffType is Exponential, where a DecorrelatedJitterBackoffV2 formula is used for jitter calculation. That formula is based on Polly.Contrib.WaitAndRetry.
})
.AddTimeout(TimeSpan.FromSeconds(60)); // Outer timeout. 32 secs plus grace period of 28 secs for the last attempt.
return pipelineBuilder.Build();
}
// Helper method to identify transient status codes.
private static bool IsTransientStatusCode(HttpStatusCode? statusCode)
{
if (statusCode is null)
{
// No status code -> Assume network failure, worth retrying.
return true;
}
return statusCode.Value switch
{
HttpStatusCode.RequestTimeout => true, // 408
HttpStatusCode.TooManyRequests => true, // 429 (if no Retry-After header is respected)
HttpStatusCode.InternalServerError => true, // 500
HttpStatusCode.BadGateway => true, // 502
HttpStatusCode.ServiceUnavailable => true, // 503
HttpStatusCode.GatewayTimeout => true, // 504
HttpStatusCode.Conflict => true, // 409 - Can be transient in concurrency cases
_ => false // Other errors are not transient
};
}
}