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
4 changes: 4 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
<PrivateAssets>all</PrivateAssets>
</PackageVersion>
<PackageVersion Include="MimeMapping" Version="4.0.0" />
<PackageVersion Include="PolySharp" Version="1.16.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageVersion>
<PackageVersion Include="System.Text.Json" Version="8.0.5" />
<PackageVersion Include="System.Diagnostics.DiagnosticSource" Version="8.0.1" />
<PackageVersion Include="System.IdentityModel.Tokens.Jwt" Version="7.5.1" />
Expand Down
2 changes: 1 addition & 1 deletion packages/Core/.gate-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
},
"updated": "2026-08-14T08:21:47Z",
"coverage": {
"hermeticLine": 97.96
"hermeticLine": 100.00
}
}
25 changes: 25 additions & 0 deletions packages/Core/Core.Tests/Http/DefaultHttpClientFactoryTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using System.Net;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Core.Http;

namespace Core.Tests.Http;

/// <summary>Covers <see cref="DefaultHttpClientFactory"/>: the fallback client built when a consumer hasn't injected one.</summary>
[TestClass]
[TestCategory("Unit")]
public class DefaultHttpClientFactoryTests
{
[TestMethod]
public void Create_ShouldReturnBclDefaultTimeout_GivenNoTimeoutSpecified() =>
DefaultHttpClientFactory.Create().Timeout.Should().Be(TimeSpan.FromSeconds(100));

[TestMethod]
public void Create_ShouldApplyGivenTimeout() =>
DefaultHttpClientFactory.Create(timeout: TimeSpan.FromSeconds(30)).Timeout.Should().Be(TimeSpan.FromSeconds(30));

[TestMethod]
public void Create_ShouldNotThrow_GivenAProxy() =>
FluentActions.Invoking(() => DefaultHttpClientFactory.Create(proxy: new WebProxy("http://localhost:8888"))).Should().NotThrow();
}
111 changes: 111 additions & 0 deletions packages/Core/Core.Tests/Http/RetryExecutorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Core.Http;

namespace Core.Tests.Http;

/// <summary>Covers <see cref="RetryExecutor"/>: retry/backoff policy, cancellation, and single-send behavior when disabled.</summary>
[TestClass]
[TestCategory("Unit")]
public class RetryExecutorTests
{
private static readonly RetryOptions Fast = new() { MaxRetries = 2, BaseDelay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(5) };

[TestMethod]
[DataRow(HttpStatusCode.OK, true)]
[DataRow(HttpStatusCode.ServiceUnavailable, false)]
[DataRow(HttpStatusCode.NotFound, true)]
public async Task SendAsync_ShouldSendOnce_GivenNoRetryNeeded(HttpStatusCode status, bool retriesEnabled)
{
var handler = new StubHandler(_ => new HttpResponseMessage(status));
using var client = new HttpClient(handler);
var response = await RetryExecutor.SendAsync(client, Get, retriesEnabled ? Fast : new RetryOptions());
response.StatusCode.Should().Be(status);
handler.CallCount.Should().Be(1, "success, a non-retryable status, and disabled retries all send exactly once");
}

[TestMethod]
public async Task SendAsync_ShouldRetryUntilSuccess_GivenRetryableStatusThenSuccess()
{
var responses = new Queue<HttpStatusCode>([HttpStatusCode.ServiceUnavailable, HttpStatusCode.ServiceUnavailable, HttpStatusCode.OK]);
var handler = new StubHandler(_ => new HttpResponseMessage(responses.Dequeue()));
using var client = new HttpClient(handler);
var response = await RetryExecutor.SendAsync(client, Get, Fast);
response.StatusCode.Should().Be(HttpStatusCode.OK);
handler.CallCount.Should().Be(3, "a fresh request per attempt is required — HttpRequestMessage can't be sent twice");
}

[TestMethod]
public async Task SendAsync_ShouldReturnLastResponse_GivenRetriesExhausted()
{
var handler = new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
using var client = new HttpClient(handler);
var response = await RetryExecutor.SendAsync(client, Get, Fast);
response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
handler.CallCount.Should().Be(3, "the initial attempt plus MaxRetries retries");
}

[TestMethod]
public async Task SendAsync_ShouldRetryTransportException_GivenTransientFailureThenSuccess()
{
var attempts = 0;
var handler = new StubHandler(_ => ++attempts == 1 ? throw new HttpRequestException("connection reset") : new HttpResponseMessage(HttpStatusCode.OK));
using var client = new HttpClient(handler);
var response = await RetryExecutor.SendAsync(client, Get, Fast);
response.StatusCode.Should().Be(HttpStatusCode.OK);
}

[TestMethod]
public async Task SendAsync_ShouldRethrowTransportException_GivenRetriesExhausted()
{
var handler = new StubHandler(_ => throw new HttpRequestException("connection reset"));
using var client = new HttpClient(handler);
var act = () => RetryExecutor.SendAsync(client, Get, Fast);
await act.Should().ThrowAsync<HttpRequestException>();
handler.CallCount.Should().Be(3);
}

[TestMethod]
public async Task SendAsync_ShouldCapBackoffDelay_GivenDelayExceedsMaxDelay()
{
var handler = new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
using var client = new HttpClient(handler);
var options = new RetryOptions { MaxRetries = 4, BaseDelay = TimeSpan.FromMilliseconds(20), MaxDelay = TimeSpan.FromMilliseconds(25), UseJitter = false };
var stopwatch = Stopwatch.StartNew();
await RetryExecutor.SendAsync(client, Get, options);
stopwatch.Elapsed.Should().BeLessThan(TimeSpan.FromMilliseconds(250), "backoff should be capped at MaxDelay, not grow unbounded");
}

[TestMethod]
public async Task SendAsync_ShouldStopRetrying_GivenCancellationDuringBackoffDelay()
{
using var cts = new CancellationTokenSource();
var handler = new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
using var client = new HttpClient(handler);
var options = new RetryOptions { MaxRetries = 5, BaseDelay = TimeSpan.FromSeconds(30), MaxDelay = TimeSpan.FromSeconds(30) };
var act = () => RetryExecutor.SendAsync(client, Get, options, cts.Token);
cts.CancelAfter(TimeSpan.FromMilliseconds(20));
await act.Should().ThrowAsync<OperationCanceledException>();
handler.CallCount.Should().Be(1, "cancellation fires during the first backoff delay, before a second attempt");
}

private static HttpRequestMessage Get() => new(HttpMethod.Get, "http://localhost/");

private sealed class StubHandler(Func<HttpRequestMessage, HttpResponseMessage> respond) : HttpMessageHandler
{
public int CallCount { get; private set; }

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
this.CallCount++;
return Task.FromResult(respond(request));
}
}
}
6 changes: 5 additions & 1 deletion packages/Core/Core/Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<PropertyGroup>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
Expand All @@ -35,6 +35,10 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="PolySharp">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="System.Diagnostics.DiagnosticSource" />
</ItemGroup>

Expand Down
122 changes: 59 additions & 63 deletions packages/Core/Core/Diagnostics/ActivityExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,80 +1,76 @@
using System;
using System.Diagnostics;

namespace Supabase.Core.Diagnostics
namespace Supabase.Core.Diagnostics;

/// <summary>
/// Null-safe helpers for tagging activities with OpenTelemetry HTTP semantic conventions.
///
/// All members accept a null <see cref="Activity"/> (the result of
/// <see cref="ActivitySource.StartActivity(string, ActivityKind)"/> when nothing is listening)
/// and no-op, so call sites need no listener checks. URLs are recorded through
/// <see cref="UrlSanitizer"/> only — never record a raw URL, query string, token, or other
/// credential as a tag value.
/// </summary>
public static class ActivityExtensions
{
/// <summary>
/// Null-safe helpers for tagging activities with OpenTelemetry HTTP semantic conventions.
///
/// All members accept a null <see cref="Activity"/> (the result of
/// <see cref="ActivitySource.StartActivity(string, ActivityKind)"/> when nothing is listening)
/// and no-op, so call sites need no listener checks. URLs are recorded through
/// <see cref="UrlSanitizer"/> only — never record a raw URL, query string, token, or other
/// credential as a tag value.
/// </summary>
public static class ActivityExtensions
/// <param name="activity">The activity to tag, or null when nothing is listening.</param>
extension(Activity? activity)
{
/// <param name="activity">The activity to tag, or null when nothing is listening.</param>
extension(Activity? activity)
/// <summary>
/// Tags an outgoing HTTP request following OpenTelemetry HTTP client conventions.
/// The URL is sanitized to scheme/host/port/path; the query string is never recorded.
/// </summary>
/// <param name="method">The HTTP method, e.g. <c>POST</c>.</param>
/// <param name="uri">The request URI, sanitized before tagging.</param>
public Activity? SetHttpRequestTags(string method, Uri uri)
{
/// <summary>
/// Tags an outgoing HTTP request following OpenTelemetry HTTP client conventions.
/// The URL is sanitized to scheme/host/port/path; the query string is never recorded.
/// </summary>
/// <param name="method">The HTTP method, e.g. <c>POST</c>.</param>
/// <param name="uri">The request URI, sanitized before tagging.</param>
public Activity? SetHttpRequestTags(string method, Uri uri)
{
if (activity == null)
return null;

activity.SetTag("http.request.method", method);
activity.SetTag("server.address", uri.Host);
if (!uri.IsDefaultPort)
activity.SetTag("server.port", uri.Port);
if (activity == null)
return null;

activity.SetTag("url.full", UrlSanitizer.Sanitize(uri));
return activity;
}
activity.SetTag("http.request.method", method);
activity.SetTag("server.address", uri.Host);
if (!uri.IsDefaultPort)
activity.SetTag("server.port", uri.Port);

/// <summary>
/// Tags the response status code, marking the activity as failed for 4xx/5xx responses.
/// </summary>
/// <param name="statusCode">The HTTP response status code.</param>
public Activity? SetHttpResponseTags(int statusCode)
{
if (activity == null)
return null;
activity.SetTag("url.full", UrlSanitizer.Sanitize(uri));
return activity;
}

activity.SetTag("http.response.status_code", statusCode);
return statusCode >= 400 ? activity.SetErrorTags( statusCode) : activity;
}
/// <summary>
/// Tags the response status code, marking the activity as failed for 4xx/5xx responses.
/// </summary>
/// <param name="statusCode">The HTTP response status code.</param>
public Activity? SetHttpResponseTags(int statusCode)
{
if (activity == null)
return null;

/// <summary>
/// Marks the activity as failed with the exception type as <c>error.type</c>.
/// </summary>
/// <param name="exception">The exception whose type and message describe the failure.</param>
public Activity? SetFailure(Exception exception)
{
if (activity == null)
return null;
activity.SetTag("http.response.status_code", statusCode);
return statusCode >= 400 ? activity.SetErrorTags(statusCode) : activity;
}

activity.SetTag("error.type", exception.GetType().FullName);
activity.SetStatus(ActivityStatusCode.Error, exception.Message);
return activity;
}
/// <summary>
/// Marks the activity as failed with the exception type as <c>error.type</c>.
/// </summary>
/// <param name="exception">The exception whose type and message describe the failure.</param>
public Activity? SetFailure(Exception exception)
{
if (activity == null)
return null;

activity.SetTag("error.type", exception.GetType().FullName);
activity.SetStatus(ActivityStatusCode.Error, exception.Message);
return activity;
}

private Activity? SetErrorTags( int statusCode)
{
if (activity == null)
return null;

activity.SetTag("error.type", statusCode.ToString());
activity.SetStatus(ActivityStatusCode.Error);
return activity;
}
private Activity? SetErrorTags(int statusCode)
{
activity!.SetTag("error.type", statusCode.ToString());
activity.SetStatus(ActivityStatusCode.Error);
return activity;
}

}

}
16 changes: 16 additions & 0 deletions packages/Core/Core/Http/DefaultHttpClientFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Net;
using System.Net.Http;

namespace Supabase.Core.Http;

/// <summary>Builds the fallback <see cref="HttpClient"/> a package uses when a consumer hasn't injected one.</summary>
public static class DefaultHttpClientFactory
{
/// <summary>Creates a client with the given timeout (BCL default, 100s, when null) and optional proxy.</summary>
public static HttpClient Create(TimeSpan? timeout = null, IWebProxy? proxy = null)
{
var handler = new HttpClientHandler { Proxy = proxy, UseProxy = proxy != null };
return timeout.HasValue ? new HttpClient(handler) { Timeout = timeout.Value } : new HttpClient(handler);
}
}
55 changes: 55 additions & 0 deletions packages/Core/Core/Http/RetryExecutor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Supabase.Core.Http;

/// <summary>Sends a request, retrying with backoff per <see cref="RetryOptions"/>. Default options send once, un-retried.</summary>
public static class RetryExecutor
{
private static readonly ThreadLocal<Random> RandomProvider = new(() => new Random(Guid.NewGuid().GetHashCode()));

/// <summary>Sends via <paramref name="requestFactory"/>, called fresh per attempt since a sent <see cref="HttpRequestMessage"/> can't be reused.</summary>
public static async Task<HttpResponseMessage> SendAsync(HttpClient client, Func<HttpRequestMessage> requestFactory,
RetryOptions options, CancellationToken cancellationToken = default)
{
var attempt = 0;
while (true)
{
var (response, exception) = await Attempt(client, requestFactory, cancellationToken).ConfigureAwait(false);
if (!ShouldRetry(response, exception, attempt, options))
return response ?? throw exception!;

response?.Dispose();
attempt++;
await Task.Delay(BackoffDelay(options, attempt), cancellationToken).ConfigureAwait(false);
}
}

private static async Task<(HttpResponseMessage? Response, HttpRequestException? Exception)> Attempt(
HttpClient client, Func<HttpRequestMessage> requestFactory, CancellationToken cancellationToken)
{
using var request = requestFactory();
try
{
return (await client.SendAsync(request, cancellationToken).ConfigureAwait(false), null);
}
catch (HttpRequestException e)
{
return (null, e);
}
}

private static bool ShouldRetry(HttpResponseMessage? response, HttpRequestException? exception, int attempt, RetryOptions options) =>
attempt < options.MaxRetries && (exception != null || options.RetryableStatusCodes.Contains((int) response!.StatusCode));

private static TimeSpan BackoffDelay(RetryOptions options, int attempt)
{
var exponentialMs = options.BaseDelay.TotalMilliseconds * Math.Pow(2, attempt - 1);
var cappedMs = Math.Min(exponentialMs, options.MaxDelay.TotalMilliseconds);
var delayMs = options.UseJitter ? RandomProvider.Value!.NextDouble() * cappedMs : cappedMs;
return TimeSpan.FromMilliseconds(delayMs);
}
}
Loading
Loading