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

fix: Retry configuring Couchbase on HttpIOException #1064

Merged
merged 4 commits into from
Dec 6, 2023
Merged
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
45 changes: 44 additions & 1 deletion src/Testcontainers.Couchbase/CouchbaseBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ private async Task ConfigureCouchbaseAsync(IContainer container, CancellationTok
await WaitStrategy.WaitUntilAsync(() => WaitUntilNodeIsReady.UntilAsync(container), TimeSpan.FromSeconds(2), TimeSpan.FromMinutes(5), ct)
.ConfigureAwait(false);

using (var httpClient = new HttpClient())
using (var httpClient = new HttpClient(new RetryHandler()))
{
httpClient.BaseAddress = new UriBuilder(Uri.UriSchemeHttp, container.Hostname, container.GetMappedPublicPort(MgmtPort)).Uri;

Expand Down Expand Up @@ -540,4 +540,47 @@ public CreateBucketRequest(CouchbaseBucket bucket)
Content = new FormUrlEncodedContent(content);
}
}

/// <summary>
/// An HTTP retry handler that sends an HTTP request until it succeeds.
/// </summary>
/// <remarks>
/// Sending an HTTP request to Couchbase's API sometimes fails with the following
/// error: System.Net.Http.HttpIOException: The response ended prematurely (ResponseEnded).
/// The HTTP status code 504 indicates an issue with the Couchbase backend.
/// It is likely that the API is not yet ready to process HTTP requests.
/// Typically, trying it again resolves the issue.
/// </remarks>
private sealed class RetryHandler : DelegatingHandler
{
private const int MaxRetries = 5;

/// <summary>
/// Initializes a new instance of the <see cref="RetryHandler" /> class.
/// </summary>
public RetryHandler()
: base(new HttpClientHandler())
{
}

/// <inheritdoc />
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
for (var _ = 0; _ < MaxRetries; _++)
{
try
{
return await base.SendAsync(request, cancellationToken)
.ConfigureAwait(false);
}
catch (HttpRequestException)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken)
.ConfigureAwait(false);
}
}

throw new Exception($"Unable to configure Couchbase. The HTTP request '{request.RequestUri}' did not complete successfully.");
}
}
}