Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changing the metodology to create HTTP clients to deliver webhooks #59

Merged
merged 3 commits into from
Jan 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Deveel.Webhooks.sln
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Deveel.Webhooks.Receiver.Te
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Deveel.Webhooks.DeliveryResultLogging.Tests", "test\Deveel.Webhooks.DeliveryResultLogging.Tests\Deveel.Webhooks.DeliveryResultLogging.Tests.csproj", "{DDD9A4CB-AA5E-4C0B-87F3-CDC24F6A8DA0}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "util", "util", "{6D7A2395-7D23-40E4-91EF-AF4EE5C4EFEB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Deveel.Webhooks.TestHttpClient", "test\Deveel.Webhooks.TestHttpClient\Deveel.Webhooks.TestHttpClient.csproj", "{98547810-98BF-46E6-8C13-2CC2690D145E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -207,6 +211,10 @@ Global
{DDD9A4CB-AA5E-4C0B-87F3-CDC24F6A8DA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DDD9A4CB-AA5E-4C0B-87F3-CDC24F6A8DA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DDD9A4CB-AA5E-4C0B-87F3-CDC24F6A8DA0}.Release|Any CPU.Build.0 = Release|Any CPU
{98547810-98BF-46E6-8C13-2CC2690D145E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{98547810-98BF-46E6-8C13-2CC2690D145E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{98547810-98BF-46E6-8C13-2CC2690D145E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{98547810-98BF-46E6-8C13-2CC2690D145E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -243,6 +251,8 @@ Global
{EBD3DB50-0E90-47C7-9DD8-FBBAC8696CE1} = {07F23FF6-2FE1-4072-BF37-9238E3750AA1}
{4942C858-277D-438D-B822-92055B8E8DF7} = {07F23FF6-2FE1-4072-BF37-9238E3750AA1}
{DDD9A4CB-AA5E-4C0B-87F3-CDC24F6A8DA0} = {07F23FF6-2FE1-4072-BF37-9238E3750AA1}
{6D7A2395-7D23-40E4-91EF-AF4EE5C4EFEB} = {07F23FF6-2FE1-4072-BF37-9238E3750AA1}
{98547810-98BF-46E6-8C13-2CC2690D145E} = {6D7A2395-7D23-40E4-91EF-AF4EE5C4EFEB}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E682A9F5-43D7-4D4C-82EA-953545B8F4DE}
Expand Down
8 changes: 2 additions & 6 deletions src/Deveel.Webhooks.Sender/Deveel.Webhooks.Sender.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,14 @@
<PackageTags>webhooks;webhook;events;event;sender;send;delivery;http</PackageTags>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Polly" Version="7.2.4" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net6.0'">
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="6.0.26" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net7.0'">
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="7.0.15" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="7.0.0" />
</ItemGroup>

Expand Down
20 changes: 18 additions & 2 deletions src/Deveel.Webhooks.Sender/Webhooks/LoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,27 @@ static partial class LoggerExtensions {
public static partial void TraceSendingWebhook(this ILogger logger, string destinationUrl);

[LoggerMessage(EventId = 120328, Level = LogLevel.Debug,
Message = "The webhook has been sent to the receiver '{DestinationUrl}'")]
Message = "The webhook has been sent to the receiver '{DestinationUrl}'")]
public static partial void TraceSuccessfulDelivery(this ILogger logger, string destinationUrl);

[LoggerMessage(EventId = -120329, Level = LogLevel.Debug,
Message = "The webhook has failed to be delivered to the receiver '{DestinationUrl}'")]
Message = "The webhook has failed to be delivered to the receiver '{DestinationUrl}'")]
public static partial void WarnDeliveryFailed(this ILogger logger, string destinationUrl);

[LoggerMessage(EventId = 120330, Level = LogLevel.Debug,
Message = "The webhook has been delivered to the receiver '{DestinationUrl}'")]
public static partial void TraceDeliveryFinished(this ILogger logger, string destinationUrl);

[LoggerMessage(EventId = 120331, Level = LogLevel.Debug,
Message = "Verifying the the receiver '{VerificationUrl}' for the delivery")]
public static partial void TraceVerifyingReceiver(this ILogger logger, string verificationUrl);

[LoggerMessage(EventId = 120332, Level = LogLevel.Debug,
Message = "The receiver '{VerificationUrl}' has been verified for the delivery")]
public static partial void TraceReceiverVerified(this ILogger logger, string verificationUrl);

[LoggerMessage(EventId = -120333, Level = LogLevel.Error,
Message = "The receiver '{VerificationUrl}' has failed to be verified for the delivery")]
public static partial void LogVerificationFailed(this ILogger logger, Exception error, string verificationUrl);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ public SystemWebhookXmlSerializer(XmlSerializerOptions? options = null) {

/// <inheritdoc/>
public async Task SerializeAsync(Stream utf8Stream, TWebhook webhook, CancellationToken cancellationToken = default) {
if (utf8Stream == null)
throw new ArgumentNullException(nameof(utf8Stream));
ArgumentNullException.ThrowIfNull(utf8Stream, nameof(utf8Stream));

if (!utf8Stream.CanWrite)
throw new ArgumentException("The stream is not writable", nameof(utf8Stream));

Expand Down
6 changes: 0 additions & 6 deletions src/Deveel.Webhooks.Sender/Webhooks/UriExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Deveel.Webhooks {
/// <summary>
/// Extends the <see cref="Uri"/> class with additional
Expand Down
61 changes: 59 additions & 2 deletions src/Deveel.Webhooks.Sender/Webhooks/WebhookDestination.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using System.Threading;

using Polly;
using Polly.Extensions.Http;

namespace Deveel.Webhooks {
// TODO: Find a better name for this class? The reason
// for not calling it 'WebhookReceiver' is to avoid
Expand All @@ -26,6 +31,8 @@ namespace Deveel.Webhooks {
/// including configuration options for the delivery and verification.
/// </remarks>
public sealed class WebhookDestination {
private string name;

/// <summary>
/// Initializes a new instance of the <see cref="WebhookDestination"/> class
/// </summary>
Expand All @@ -39,13 +46,14 @@ public sealed class WebhookDestination {
/// Thrown when the <paramref name="url"/> is not an absolute URI.
/// </exception>
public WebhookDestination(Uri url) {
if (url == null)
throw new ArgumentNullException(nameof(url));
ArgumentNullException.ThrowIfNull(url, nameof(url));

if (!url.IsAbsoluteUri)
throw new ArgumentException($"The '{nameof(url)}' must be an absolute URI.", nameof(url));

Url = url;

name = url.ToString();
}

/// <summary>
Expand Down Expand Up @@ -77,6 +85,18 @@ private static Uri ParseUri(string url) {
/// </summary>
public Uri Url { get; }

/// <summary>
/// Gets or sets the name of the destination,
/// to uniquely identify it in a sender context.
/// </summary>
public string Name {
get => name;
set {
ArgumentNullException.ThrowIfNull(value, nameof(Name));
name = value;
}
}

/// <summary>
/// Gets or sets the options for the verification of the destination
/// </summary>
Expand Down Expand Up @@ -214,6 +234,22 @@ public WebhookDestination WithVerification(Action<WebhookDestinationVerification
return WithVerification(options);
}

/// <summary>
/// Sets the name of the webhook destination.
/// </summary>
/// <param name="name">
/// The name of the destination.
/// </param>
/// <returns>
/// Returns this instance of the <see cref="WebhookDestination"/> with
/// the name set.
/// </returns>
public WebhookDestination WithName(string name) {
ArgumentNullException.ThrowIfNull(name, nameof(name));
Name = name;
return this;
}

/// <summary>
/// Merges the current settings with the default settings
/// from the configuration of a sender service.
Expand All @@ -231,6 +267,7 @@ public WebhookDestination WithVerification(Action<WebhookDestinationVerification
/// </returns>
public WebhookDestination Merge<TWebhook>(WebhookSenderOptions<TWebhook> options) where TWebhook : class {
var result = new WebhookDestination(Url) {
Name = Name,
Sign = Sign,
Headers = new Dictionary<string, string>(),
Format = Format ?? options.DefaultFormat,
Expand Down Expand Up @@ -265,5 +302,25 @@ public WebhookDestination Merge<TWebhook>(WebhookSenderOptions<TWebhook> options

return result;
}

internal IAsyncPolicy<HttpResponseMessage> CreateRetryPolicy(WebhookRetryOptions? retry = null) {
// TODO: Validate that the sum of the retry delays is less than the timeout
var retryCountValue = (Retry?.MaxRetries ?? retry?.MaxRetries) ?? 0;
var sleepValue = (Retry?.MaxDelay ?? retry?.MaxDelay) ?? TimeSpan.FromMilliseconds(300);

// the retry policy
return Policy
.Handle<HttpRequestException>()
.Or<TaskCanceledException>()
.Or<TimeoutException>()
.OrTransientHttpStatusCode()
.WaitAndRetryAsync(retryCountValue, attempt => sleepValue);
}

internal IAsyncPolicy<HttpResponseMessage> CreateTimeoutPolicy(WebhookRetryOptions? retry = null) {
// TODO: Validate that the timeout is not less than the retry timeout
var timeoutValue = (Retry?.Timeout ?? retry?.Timeout) ?? System.Threading.Timeout.InfiniteTimeSpan;
return Policy.TimeoutAsync<HttpResponseMessage>(timeoutValue);
}
}
}
Loading
Loading