Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ private static void AddStripeBilling(WebApplicationBuilder builder, TimeSpan htt
builder.Services.Configure<StripeSettings>(
builder.Configuration.GetSection(StripeSettings.SectionName));
var stripeKey = builder.Configuration.GetSection(StripeSettings.SectionName).Get<StripeSettings>()?.SecretKey;
Stripe.StripeConfiguration.MaxNetworkRetries = 2;
if (!string.IsNullOrEmpty(stripeKey))
{
Stripe.StripeConfiguration.ApiKey = stripeKey;
Expand Down
60 changes: 60 additions & 0 deletions src/Orbit.Infrastructure/Common/HttpRetryPolicy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System.Net;

namespace Orbit.Infrastructure.Common;

/// <summary>
/// Bounded retry for outbound HTTP calls to critical external services. Retries only transient
/// failures (network/timeout exceptions and 408/429/5xx responses) with exponential backoff,
/// giving up after <see cref="MaxRetries"/> retries. Permanent responses (2xx, 4xx other than
/// 408/429) are returned to the caller unretried; user cancellation propagates without a retry.
/// </summary>
public static class HttpRetryPolicy
{
public const int MaxRetries = 2;
public const int BaseDelayMs = 300;

public static bool IsTransient(HttpStatusCode status) =>
status is HttpStatusCode.RequestTimeout
or HttpStatusCode.TooManyRequests
or HttpStatusCode.InternalServerError
or HttpStatusCode.BadGateway
or HttpStatusCode.ServiceUnavailable
or HttpStatusCode.GatewayTimeout;

/// <summary>
/// Invokes <paramref name="send"/>, retrying transient outcomes up to <paramref name="maxRetries"/>
/// times. <paramref name="send"/> must build a fresh request (and content) on each call, since an
/// <see cref="HttpContent"/> can only be sent once. Transient responses are disposed before the
/// next attempt; the caller owns the returned response.
/// </summary>
public static async Task<HttpResponseMessage> SendWithRetryAsync(
Func<Task<HttpResponseMessage>> send,
CancellationToken cancellationToken,
int maxRetries = MaxRetries,
int baseDelayMs = BaseDelayMs)
{
for (var attempt = 0; ; attempt++)

Check warning on line 36 in src/Orbit.Infrastructure/Common/HttpRetryPolicy.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

This loop's stop incrementer updates 'attempt' but the stop condition doesn't test any variables.

Check failure on line 36 in src/Orbit.Infrastructure/Common/HttpRetryPolicy.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

This loop's stop incrementer updates 'attempt' but the stop condition doesn't test any variables.

See more on https://sonarcloud.io/project/issues?id=thomasluizon_orbit-api&issues=AZ9XnsfFC_eeOFJVhdzn&open=AZ9XnsfFC_eeOFJVhdzn&pullRequest=350
{
HttpResponseMessage response;
try
{
response = await send();
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException && attempt < maxRetries)
{
await Task.Delay(baseDelayMs << attempt, cancellationToken);
continue;
}

if (response.IsSuccessStatusCode || !IsTransient(response.StatusCode) || attempt >= maxRetries)
return response;

response.Dispose();
await Task.Delay(baseDelayMs << attempt, cancellationToken);
}
}
}
19 changes: 11 additions & 8 deletions src/Orbit.Infrastructure/Services/GoogleTokenService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.Extensions.Logging;
using Orbit.Domain.Entities;
using Orbit.Domain.Interfaces;
using Orbit.Infrastructure.Common;

namespace Orbit.Infrastructure.Services;

Expand All @@ -13,7 +14,7 @@
ILogger<GoogleTokenService> logger) : IGoogleTokenService
{
public const string HttpClientName = "GoogleOAuth";
private const string GoogleTokenUrl = "https://oauth2.googleapis.com/token";

Check warning on line 17 in src/Orbit.Infrastructure/Services/GoogleTokenService.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

Refactor your code not to use hardcoded absolute paths or URIs.
public async Task<string?> GetValidAccessTokenAsync(User user, CancellationToken ct = default)
{
if (user.GoogleAccessToken is null)
Expand All @@ -39,14 +40,16 @@
try
{
var client = httpClientFactory.CreateClient(HttpClientName);
using var response = await client.PostAsync(GoogleTokenUrl,
new FormUrlEncodedContent(new Dictionary<string, string>
{
["client_id"] = configuration["Google:ClientId"]!,
["client_secret"] = configuration["Google:ClientSecret"]!,
["refresh_token"] = user.GoogleRefreshToken,
["grant_type"] = "refresh_token"
}), ct);
using var response = await HttpRetryPolicy.SendWithRetryAsync(
() => client.PostAsync(GoogleTokenUrl,
new FormUrlEncodedContent(new Dictionary<string, string>
{
["client_id"] = configuration["Google:ClientId"]!,
["client_secret"] = configuration["Google:ClientSecret"]!,
["refresh_token"] = user.GoogleRefreshToken,
["grant_type"] = "refresh_token"
}), ct),
ct);

var body = await response.Content.ReadAsStringAsync(ct);

Expand Down Expand Up @@ -94,7 +97,7 @@
errorCode = errProp.GetString();
}
catch (JsonException)
{

Check warning on line 100 in src/Orbit.Infrastructure/Services/GoogleTokenService.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

Either remove or fill this block of code.
}

if (errorCode is "invalid_grant" or "unauthorized_client")
Expand Down
13 changes: 8 additions & 5 deletions src/Orbit.Infrastructure/Services/ResendContactsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Orbit.Domain.Interfaces;
using Orbit.Infrastructure.Common;

namespace Orbit.Infrastructure.Services;

Expand All @@ -14,12 +15,14 @@ public async Task AddContactAsync(string email, CancellationToken cancellationTo
{
var client = httpClientFactory.CreateClient("Resend");

var content = new StringContent(
JsonSerializer.Serialize(new { email, unsubscribed = false }),
Encoding.UTF8,
"application/json");
var serializedPayload = JsonSerializer.Serialize(new { email, unsubscribed = false });

var response = await client.PostAsync("/contacts", content, cancellationToken);
using var response = await HttpRetryPolicy.SendWithRetryAsync(
() => client.PostAsync(
"/contacts",
new StringContent(serializedPayload, Encoding.UTF8, "application/json"),
cancellationToken),
cancellationToken);

if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Conflict)
{
Expand Down
15 changes: 9 additions & 6 deletions src/Orbit.Infrastructure/Services/ResendEmailService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Microsoft.Extensions.Options;
using Orbit.Application.Common;
using Orbit.Domain.Interfaces;
using Orbit.Infrastructure.Common;
using Orbit.Infrastructure.Configuration;
using Orbit.Infrastructure.Email;

Expand Down Expand Up @@ -44,13 +45,13 @@

var tokens = new Dictionary<string, string>
{
["heading"] = copy.Heading,

Check warning on line 48 in src/Orbit.Infrastructure/Services/ResendEmailService.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

Define a constant instead of using this literal 'heading' 4 times.
["intro"] = copy.Intro,

Check warning on line 49 in src/Orbit.Infrastructure/Services/ResendEmailService.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

Define a constant instead of using this literal 'intro' 4 times.
["code"] = code,
["cta"] = copy.Cta,
["signInUrl"] = signInUrl,
["warning"] = copy.Warning,
["footer"] = copy.Footer,

Check warning on line 54 in src/Orbit.Infrastructure/Services/ResendEmailService.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

Define a constant instead of using this literal 'footer' 4 times.
};

var layout = new EmailLayout(LangCode(isPtBr), copy.Preheader, copy.Footer, LogoUrl, GradientHeader: false);
Expand Down Expand Up @@ -145,7 +146,7 @@
$"<a href=\"{encodedUrl}\" style=\"color: #90A1B9; text-decoration: underline;\">{unsubscribeLabel}</a>";
}

private async Task SendMarketingWithBackoffAsync(string to, string subject, string serializedPayload, CancellationToken cancellationToken)

Check warning on line 149 in src/Orbit.Infrastructure/Services/ResendEmailService.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

Refactor this method to reduce its Cognitive Complexity from 22 to the 15 allowed.
{
if (IsTestAccount(to))
{
Expand Down Expand Up @@ -255,15 +256,17 @@
object payload = replyTo != null
? new { from = _settings.FromEmail, to = new[] { to }, subject, html, text, reply_to = replyTo }
: new { from = _settings.FromEmail, to = new[] { to }, subject, html, text };

var content = new StringContent(
JsonSerializer.Serialize(payload),
Encoding.UTF8,
"application/json");
var serializedPayload = JsonSerializer.Serialize(payload);

try
{
var response = await client.PostAsync("/emails", content, cancellationToken);
using var response = await HttpRetryPolicy.SendWithRetryAsync(
() => client.PostAsync(
"/emails",
new StringContent(serializedPayload, Encoding.UTF8, "application/json"),
cancellationToken),
cancellationToken);

if (response.IsSuccessStatusCode)
{
if (logger.IsEnabled(LogLevel.Information))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orbit.Domain.Interfaces;
using Orbit.Infrastructure.Common;
using Orbit.Infrastructure.Configuration;

namespace Orbit.Infrastructure.Services;
Expand All @@ -21,7 +22,9 @@ public async Task<SignedUpload> CreateSignedUploadAsync(string objectKey, Cancel
var client = httpClientFactory.CreateClient(HttpClientName);

var requestPath = $"/storage/v1/object/upload/sign/{_settings.Bucket}/{objectKey}";
using var response = await client.PostAsync(requestPath, content: null, cancellationToken);
using var response = await HttpRetryPolicy.SendWithRetryAsync(
() => client.PostAsync(requestPath, content: null, cancellationToken),
cancellationToken);

if (!response.IsSuccessStatusCode)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using System.Net;
using FluentAssertions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Orbit.Domain.Entities;
using Orbit.Domain.Interfaces;
using Orbit.Infrastructure.Services;

namespace Orbit.Infrastructure.Tests.Services;

public class GoogleTokenServiceRetryTests
{
private static (GoogleTokenService Sut, SequencedHttpMessageHandler Handler, User User) Build(SequencedHttpMessageHandler handler)
{
var client = new HttpClient(handler);
var factory = Substitute.For<IHttpClientFactory>();
factory.CreateClient(GoogleTokenService.HttpClientName).Returns(client);

var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Google:ClientId"] = "client-id",
["Google:ClientSecret"] = "client-secret",
})
.Build();

var user = User.Create("Google Tester", "google@useorbit.org").Value;
user.SetGoogleTokens("stale-access-token", "refresh-token");

var sut = new GoogleTokenService(factory, configuration, NullLogger<GoogleTokenService>.Instance);
return (sut, handler, user);
}

[Fact]
public async Task RetriesThenSucceeds_OnTransient5xx()
{
var (sut, handler, user) = Build(new SequencedHttpMessageHandler(
SequencedHttpMessageHandler.Status(HttpStatusCode.ServiceUnavailable),
SequencedHttpMessageHandler.Status(HttpStatusCode.OK, "{\"access_token\":\"fresh-access-token\"}")));

var outcome = await sut.TryRefreshAsync(user);

handler.CallCount.Should().Be(2);
outcome.Result.Should().Be(GoogleTokenRefreshResult.Success);
outcome.AccessToken.Should().Be("fresh-access-token");
}

[Fact]
public async Task RetriesThenSucceeds_OnTransportException()
{
var (sut, handler, user) = Build(new SequencedHttpMessageHandler(
SequencedHttpMessageHandler.Throws(),
SequencedHttpMessageHandler.Status(HttpStatusCode.OK, "{\"access_token\":\"fresh-access-token\"}")));

var outcome = await sut.TryRefreshAsync(user);

handler.CallCount.Should().Be(2);
outcome.Result.Should().Be(GoogleTokenRefreshResult.Success);
}

[Fact]
public async Task DoesNotRetry_OnRevokedRefreshToken()
{
var (sut, handler, user) = Build(new SequencedHttpMessageHandler(
SequencedHttpMessageHandler.Status(HttpStatusCode.BadRequest, "{\"error\":\"invalid_grant\"}")));

var outcome = await sut.TryRefreshAsync(user);

handler.CallCount.Should().Be(1);
outcome.Result.Should().Be(GoogleTokenRefreshResult.RefreshTokenInvalid);
}

[Fact]
public async Task GivesUpAfterMaxRetries_OnPersistent5xx()
{
var (sut, handler, user) = Build(new SequencedHttpMessageHandler(
SequencedHttpMessageHandler.Status(HttpStatusCode.InternalServerError, "{}")));

var outcome = await sut.TryRefreshAsync(user);

handler.CallCount.Should().Be(3);
outcome.Result.Should().Be(GoogleTokenRefreshResult.TransientFailure);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System.Net;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Orbit.Infrastructure.Services;

namespace Orbit.Infrastructure.Tests.Services;

public class ResendContactsServiceRetryTests
{
private static (ResendContactsService Sut, SequencedHttpMessageHandler Handler) Build(SequencedHttpMessageHandler handler)
{
var client = new HttpClient(handler) { BaseAddress = new Uri("https://api.resend.com") };
var factory = Substitute.For<IHttpClientFactory>();
factory.CreateClient("Resend").Returns(client);

var sut = new ResendContactsService(factory, NullLogger<ResendContactsService>.Instance);
return (sut, handler);
}

[Fact]
public async Task RetriesThenSucceeds_OnTransient5xx()
{
var (sut, handler) = Build(new SequencedHttpMessageHandler(
SequencedHttpMessageHandler.Status(HttpStatusCode.ServiceUnavailable),
SequencedHttpMessageHandler.Status(HttpStatusCode.Created)));

await sut.AddContactAsync("user@example.com");

handler.CallCount.Should().Be(2);
}

[Fact]
public async Task GivesUpAfterMaxRetries_OnPersistent5xx()
{
var (sut, handler) = Build(new SequencedHttpMessageHandler(
SequencedHttpMessageHandler.Status(HttpStatusCode.InternalServerError)));

await sut.AddContactAsync("user@example.com");

handler.CallCount.Should().Be(3);
}

[Fact]
public async Task DoesNotRetry_OnNonTransient4xx()
{
var (sut, handler) = Build(new SequencedHttpMessageHandler(
SequencedHttpMessageHandler.Status(HttpStatusCode.BadRequest)));

await sut.AddContactAsync("user@example.com");

handler.CallCount.Should().Be(1);
}

[Fact]
public async Task DoesNotRetry_OnDuplicateConflict()
{
var (sut, handler) = Build(new SequencedHttpMessageHandler(
SequencedHttpMessageHandler.Status(HttpStatusCode.Conflict)));

await sut.AddContactAsync("user@example.com");

handler.CallCount.Should().Be(1);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ private ResendContactsService BuildService()
[Fact]
public async Task AddContactAsync_PostsToContactsEndpointWithEmail()
{
_handler.ResponseToReturn = new HttpResponseMessage(HttpStatusCode.Created);
_handler.StatusToReturn = HttpStatusCode.Created;
var service = BuildService();

await service.AddContactAsync("User@Test.com");
Expand All @@ -39,10 +39,8 @@ public async Task AddContactAsync_PostsToContactsEndpointWithEmail()
[Fact]
public async Task AddContactAsync_DuplicateEmailConflict_IsTreatedAsBenignSuccess()
{
_handler.ResponseToReturn = new HttpResponseMessage(HttpStatusCode.Conflict)
{
Content = new StringContent("Contact already exists")
};
_handler.StatusToReturn = HttpStatusCode.Conflict;
_handler.BodyToReturn = "Contact already exists";
var service = BuildService();

var act = () => service.AddContactAsync("user@test.com");
Expand All @@ -54,10 +52,8 @@ public async Task AddContactAsync_DuplicateEmailConflict_IsTreatedAsBenignSucces
[Fact]
public async Task AddContactAsync_ApiFailure_DoesNotThrow()
{
_handler.ResponseToReturn = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("Server error")
};
_handler.StatusToReturn = HttpStatusCode.InternalServerError;
_handler.BodyToReturn = "Server error";
var service = BuildService();

var act = () => service.AddContactAsync("user@test.com");
Expand All @@ -67,7 +63,8 @@ public async Task AddContactAsync_ApiFailure_DoesNotThrow()

private sealed class FakeHttpMessageHandler : HttpMessageHandler
{
public HttpResponseMessage ResponseToReturn { get; set; } = new(HttpStatusCode.OK);
public HttpStatusCode StatusToReturn { get; set; } = HttpStatusCode.OK;
public string BodyToReturn { get; set; } = "";
public HttpRequestMessage? LastRequest { get; private set; }
public string LastRequestBody { get; private set; } = "";

Expand All @@ -78,7 +75,7 @@ protected override async Task<HttpResponseMessage> SendAsync(
if (request.Content is not null)
LastRequestBody = await request.Content.ReadAsStringAsync(cancellationToken);

return ResponseToReturn;
return new HttpResponseMessage(StatusToReturn) { Content = new StringContent(BodyToReturn) };
}
}
}
Loading
Loading