diff --git a/Directory.Packages.props b/Directory.Packages.props index 3ad29e29..549e29a2 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -19,6 +19,10 @@ all + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + diff --git a/packages/Core/.gate-baseline.json b/packages/Core/.gate-baseline.json index e0af0161..3ada2754 100644 --- a/packages/Core/.gate-baseline.json +++ b/packages/Core/.gate-baseline.json @@ -9,6 +9,6 @@ }, "updated": "2026-08-14T08:21:47Z", "coverage": { - "hermeticLine": 97.96 + "hermeticLine": 100.00 } } diff --git a/packages/Core/Core.Tests/Http/DefaultHttpClientFactoryTests.cs b/packages/Core/Core.Tests/Http/DefaultHttpClientFactoryTests.cs new file mode 100644 index 00000000..0bf6dabc --- /dev/null +++ b/packages/Core/Core.Tests/Http/DefaultHttpClientFactoryTests.cs @@ -0,0 +1,25 @@ +using System; +using System.Net; +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Core.Http; + +namespace Core.Tests.Http; + +/// Covers : the fallback client built when a consumer hasn't injected one. +[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(); +} diff --git a/packages/Core/Core.Tests/Http/RetryExecutorTests.cs b/packages/Core/Core.Tests/Http/RetryExecutorTests.cs new file mode 100644 index 00000000..49f328f7 --- /dev/null +++ b/packages/Core/Core.Tests/Http/RetryExecutorTests.cs @@ -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; + +/// Covers : retry/backoff policy, cancellation, and single-send behavior when disabled. +[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.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(); + 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(); + 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 respond) : HttpMessageHandler + { + public int CallCount { get; private set; } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + this.CallCount++; + return Task.FromResult(respond(request)); + } + } +} diff --git a/packages/Core/Core/Core.csproj b/packages/Core/Core/Core.csproj index 0e7af837..adfb19a7 100644 --- a/packages/Core/Core/Core.csproj +++ b/packages/Core/Core/Core.csproj @@ -20,7 +20,7 @@ snupkg true - + enable True @@ -35,6 +35,10 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + diff --git a/packages/Core/Core/Diagnostics/ActivityExtensions.cs b/packages/Core/Core/Diagnostics/ActivityExtensions.cs index e8f9ec69..fbea8811 100644 --- a/packages/Core/Core/Diagnostics/ActivityExtensions.cs +++ b/packages/Core/Core/Diagnostics/ActivityExtensions.cs @@ -1,80 +1,76 @@ using System; using System.Diagnostics; -namespace Supabase.Core.Diagnostics +namespace Supabase.Core.Diagnostics; + +/// +/// Null-safe helpers for tagging activities with OpenTelemetry HTTP semantic conventions. +/// +/// All members accept a null (the result of +/// when nothing is listening) +/// and no-op, so call sites need no listener checks. URLs are recorded through +/// only — never record a raw URL, query string, token, or other +/// credential as a tag value. +/// +public static class ActivityExtensions { - /// - /// Null-safe helpers for tagging activities with OpenTelemetry HTTP semantic conventions. - /// - /// All members accept a null (the result of - /// when nothing is listening) - /// and no-op, so call sites need no listener checks. URLs are recorded through - /// only — never record a raw URL, query string, token, or other - /// credential as a tag value. - /// - public static class ActivityExtensions + /// The activity to tag, or null when nothing is listening. + extension(Activity? activity) { - /// The activity to tag, or null when nothing is listening. - extension(Activity? activity) + /// + /// 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. + /// + /// The HTTP method, e.g. POST. + /// The request URI, sanitized before tagging. + public Activity? SetHttpRequestTags(string method, Uri uri) { - /// - /// 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. - /// - /// The HTTP method, e.g. POST. - /// The request URI, sanitized before tagging. - 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); - /// - /// Tags the response status code, marking the activity as failed for 4xx/5xx responses. - /// - /// The HTTP response status code. - 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; - } + /// + /// Tags the response status code, marking the activity as failed for 4xx/5xx responses. + /// + /// The HTTP response status code. + public Activity? SetHttpResponseTags(int statusCode) + { + if (activity == null) + return null; - /// - /// Marks the activity as failed with the exception type as error.type. - /// - /// The exception whose type and message describe the failure. - 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; - } + /// + /// Marks the activity as failed with the exception type as error.type. + /// + /// The exception whose type and message describe the failure. + 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; } - } + } diff --git a/packages/Core/Core/Http/DefaultHttpClientFactory.cs b/packages/Core/Core/Http/DefaultHttpClientFactory.cs new file mode 100644 index 00000000..65837754 --- /dev/null +++ b/packages/Core/Core/Http/DefaultHttpClientFactory.cs @@ -0,0 +1,16 @@ +using System; +using System.Net; +using System.Net.Http; + +namespace Supabase.Core.Http; + +/// Builds the fallback a package uses when a consumer hasn't injected one. +public static class DefaultHttpClientFactory +{ + /// Creates a client with the given timeout (BCL default, 100s, when null) and optional proxy. + 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); + } +} diff --git a/packages/Core/Core/Http/RetryExecutor.cs b/packages/Core/Core/Http/RetryExecutor.cs new file mode 100644 index 00000000..5910442b --- /dev/null +++ b/packages/Core/Core/Http/RetryExecutor.cs @@ -0,0 +1,55 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace Supabase.Core.Http; + +/// Sends a request, retrying with backoff per . Default options send once, un-retried. +public static class RetryExecutor +{ + private static readonly ThreadLocal RandomProvider = new(() => new Random(Guid.NewGuid().GetHashCode())); + + /// Sends via , called fresh per attempt since a sent can't be reused. + public static async Task SendAsync(HttpClient client, Func 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 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); + } +} diff --git a/packages/Core/Core/Http/RetryOptions.cs b/packages/Core/Core/Http/RetryOptions.cs new file mode 100644 index 00000000..ddaea34f --- /dev/null +++ b/packages/Core/Core/Http/RetryOptions.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; + +namespace Supabase.Core.Http; + +/// Retry policy applied by around a request. +public sealed record RetryOptions +{ + /// Retry attempts after the initial request. Default 0 preserves today's no-retry behavior. + public int MaxRetries { get; init; } + + /// Delay before the first retry; later attempts back off exponentially, capped at . + public TimeSpan BaseDelay { get; init; } = TimeSpan.FromMilliseconds(200); + + /// Upper bound on the backoff delay between attempts. + public TimeSpan MaxDelay { get; init; } = TimeSpan.FromSeconds(5); + + /// Randomizes each backoff delay between zero and its exponential value to avoid retry lockstep. + public bool UseJitter { get; init; } = true; + + /// HTTP status codes treated as transient and worth retrying. + public IReadOnlyCollection RetryableStatusCodes { get; init; } = new HashSet { 408, 429, 500, 502, 503, 504 }; +} diff --git a/packages/Core/Core/PublicAPI.Unshipped.txt b/packages/Core/Core/PublicAPI.Unshipped.txt index 7dc5c581..6ae4ff2c 100644 --- a/packages/Core/Core/PublicAPI.Unshipped.txt +++ b/packages/Core/Core/PublicAPI.Unshipped.txt @@ -1 +1,24 @@ #nullable enable +override Supabase.Core.Http.RetryOptions.Equals(object? obj) -> bool +override Supabase.Core.Http.RetryOptions.GetHashCode() -> int +override Supabase.Core.Http.RetryOptions.ToString() -> string! +static Supabase.Core.Http.DefaultHttpClientFactory.Create(System.TimeSpan? timeout = null, System.Net.IWebProxy? proxy = null) -> System.Net.Http.HttpClient! +static Supabase.Core.Http.RetryExecutor.SendAsync(System.Net.Http.HttpClient! client, System.Func! requestFactory, Supabase.Core.Http.RetryOptions! options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +static Supabase.Core.Http.RetryOptions.operator !=(Supabase.Core.Http.RetryOptions? left, Supabase.Core.Http.RetryOptions? right) -> bool +static Supabase.Core.Http.RetryOptions.operator ==(Supabase.Core.Http.RetryOptions? left, Supabase.Core.Http.RetryOptions? right) -> bool +Supabase.Core.Http.DefaultHttpClientFactory +Supabase.Core.Http.RetryExecutor +Supabase.Core.Http.RetryOptions +Supabase.Core.Http.RetryOptions.$() -> Supabase.Core.Http.RetryOptions! +Supabase.Core.Http.RetryOptions.BaseDelay.get -> System.TimeSpan +Supabase.Core.Http.RetryOptions.BaseDelay.init -> void +Supabase.Core.Http.RetryOptions.Equals(Supabase.Core.Http.RetryOptions? other) -> bool +Supabase.Core.Http.RetryOptions.MaxDelay.get -> System.TimeSpan +Supabase.Core.Http.RetryOptions.MaxDelay.init -> void +Supabase.Core.Http.RetryOptions.MaxRetries.get -> int +Supabase.Core.Http.RetryOptions.MaxRetries.init -> void +Supabase.Core.Http.RetryOptions.RetryableStatusCodes.get -> System.Collections.Generic.IReadOnlyCollection! +Supabase.Core.Http.RetryOptions.RetryableStatusCodes.init -> void +Supabase.Core.Http.RetryOptions.RetryOptions() -> void +Supabase.Core.Http.RetryOptions.UseJitter.get -> bool +Supabase.Core.Http.RetryOptions.UseJitter.init -> void diff --git a/packages/Core/Core/Util.cs b/packages/Core/Core/Util.cs index 0ba9e0c0..c810c592 100644 --- a/packages/Core/Core/Util.cs +++ b/packages/Core/Core/Util.cs @@ -1,110 +1,112 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; -namespace Supabase.Core +namespace Supabase.Core; + +/// +/// Shared utilities for Supabase client libraries. +/// +public static class Util { /// - /// Shared utilities for Supabase client libraries. + /// Builds the X-Client-Info header value for the given client type. /// - public static class Util + /// + /// Format: name-csharp/version[; key=value ...]
+ /// Appended metadata includes platform, platform version, runtime, runtime version, + /// and framework (when detectable). + ///
+ /// A type belonging to the client assembly, used to resolve the assembly name and version. + /// A structured header value identifying the client library and its host environment. + public static string GetAssemblyVersion(Type clientType) => + GetAssemblyVersion(clientType, RuntimeInformation.OSDescription, RuntimeInformation.IsOSPlatform, AppDomain.CurrentDomain.GetAssemblies()); + + // Testability seam: the platform and framework probes read process-wide ambient state + // (RuntimeInformation, the loaded assembly set) that a host cannot vary at runtime. This + // overload takes those reads as parameters, so every branch is reachable hermetically; the + // public entry point above supplies the real values. Internal — not part of the public API. + internal static string GetAssemblyVersion(Type clientType, string osDescription, Func isOsPlatform, IReadOnlyCollection loadedAssemblies) => + $"{GetClientName(clientType)}-csharp/{GetClientVersion(clientType)}{BuildMetadata(osDescription, isOsPlatform, loadedAssemblies)}"; + + private static string GetClientName(Type clientType) => clientType.Assembly.GetName().Name.ToLower(); + + private static string? GetClientVersion(Type clientType) => GetInformationalVersion(clientType.Assembly); + + private static string BuildMetadata(string osDescription, Func isOsPlatform, IReadOnlyCollection loadedAssemblies) => + string.Concat(GetPlatformInfo(osDescription, isOsPlatform).ToString(), GetRuntimeInfo().ToString(), GetFrameworkInfo(loadedAssemblies).ToString()); + + private sealed class MetadataEntry { - /// - /// Builds the X-Client-Info header value for the given client type. - /// - /// - /// Format: name-csharp/version[; key=value ...]
- /// Appended metadata includes platform, platform version, runtime, runtime version, - /// and framework (when detectable). - ///
- /// A type belonging to the client assembly, used to resolve the assembly name and version. - /// A structured header value identifying the client library and its host environment. - public static string GetAssemblyVersion(Type clientType) => - GetAssemblyVersion(clientType, RuntimeInformation.OSDescription, RuntimeInformation.IsOSPlatform, AppDomain.CurrentDomain.GetAssemblies()); - - // Testability seam: the platform and framework probes read process-wide ambient state - // (RuntimeInformation, the loaded assembly set) that a host cannot vary at runtime. This - // overload takes those reads as parameters, so every branch is reachable hermetically; the - // public entry point above supplies the real values. Internal — not part of the public API. - internal static string GetAssemblyVersion(Type clientType, string osDescription, Func isOsPlatform, IReadOnlyCollection loadedAssemblies) => - $"{GetClientName(clientType)}-csharp/{GetClientVersion(clientType)}{BuildMetadata(osDescription, isOsPlatform, loadedAssemblies)}"; - - private static string GetClientName(Type clientType) => clientType.Assembly.GetName().Name.ToLower(); - - private static string? GetClientVersion(Type clientType) => GetInformationalVersion(clientType.Assembly); - - private static string BuildMetadata(string osDescription, Func isOsPlatform, IReadOnlyCollection loadedAssemblies) => - string.Concat(GetPlatformInfo(osDescription, isOsPlatform).ToString(), GetRuntimeInfo().ToString(), GetFrameworkInfo(loadedAssemblies).ToString()); - - private sealed class MetadataEntry - { - private readonly string key; - private readonly string value; - private readonly string? version; - - internal MetadataEntry(string key, string value, string? version = null) - { - this.key = key; - this.value = value; - this.version = version; - } - - public override string ToString() => string.IsNullOrEmpty(this.version) - ? $"; {this.key}={this.value}" - : $"; {this.key}={this.value}; {this.key}-version={this.version}"; - - internal static MetadataEntry Unknown(string key) => new(key, "unknown"); - } + private readonly string key; + private readonly string value; + private readonly string? version; - private static string GetPlatform(string osDescription, Func isOsPlatform) + internal MetadataEntry(string key, string value, string? version = null) { - if (osDescription == "Browser") return "browser"; - if (isOsPlatform(OSPlatform.Windows)) return "Windows"; - if (isOsPlatform(OSPlatform.OSX)) return "macOS"; - if (isOsPlatform(OSPlatform.Create("iOS"))) return "iOS"; - if (isOsPlatform(OSPlatform.Linux)) return "Linux"; - if (isOsPlatform(OSPlatform.Create("Android"))) return "Android"; - return osDescription; + this.key = key; + this.value = value; + this.version = version; } - private static MetadataEntry GetPlatformInfo(string osDescription, Func isOsPlatform) => new("platform", GetPlatform(osDescription, isOsPlatform), Environment.OSVersion.Version.ToString()); + public override string ToString() => string.IsNullOrEmpty(this.version) + ? $"; {this.key}={this.value}" + : $"; {this.key}={this.value}; {this.key}-version={this.version}"; - private static MetadataEntry GetRuntimeInfo() => new("runtime", "dotnet", Environment.Version.ToString()); + internal static MetadataEntry Unknown(string key) => new(key, "unknown"); + } - // Priority is explicit: MAUI wins over Blazor in hybrid apps where both assemblies are present. - // Unity version uses GetCustomAttributesData() rather than member reflection — safe under IL2CPP. - private static MetadataEntry GetFrameworkInfo(IReadOnlyCollection loadedAssemblies) - { - var assemblies = loadedAssemblies - .GroupBy(a => a.GetName().Name) - .ToDictionary(g => g.Key, g => g.First()); - - if (assemblies.TryGetValue("Microsoft.Maui", out var maui)) - return new MetadataEntry("framework", "maui", GetInformationalVersion(maui)); - if (assemblies.ContainsKey("UnityEngine.CoreModule")) - return new MetadataEntry("framework", "unity", GetUnityVersion(loadedAssemblies)); - if (assemblies.TryGetValue("Microsoft.AspNetCore.Components", out var blazor)) - return new MetadataEntry("framework", "blazor", GetInformationalVersion(blazor)); - return MetadataEntry.Unknown("framework"); - } + private static string GetPlatform(string osDescription, Func isOsPlatform) + { + if (osDescription == "Browser") return "browser"; + if (isOsPlatform(OSPlatform.Windows)) return "Windows"; + if (isOsPlatform(OSPlatform.OSX)) return "macOS"; + if (isOsPlatform(OSPlatform.Create("iOS"))) return "iOS"; + if (isOsPlatform(OSPlatform.Linux)) return "Linux"; + if (isOsPlatform(OSPlatform.Create("Android"))) return "Android"; + return osDescription; + } - private static string? GetInformationalVersion(Assembly assembly) => - assembly.GetCustomAttribute()?.InformationalVersion; + private static MetadataEntry GetPlatformInfo(string osDescription, Func isOsPlatform) => new("platform", GetPlatform(osDescription, isOsPlatform), Environment.OSVersion.Version.ToString()); - private static CustomAttributeData[] SafeGetCustomAttributesData(Assembly assembly) - { - try { return assembly.GetCustomAttributesData().ToArray(); } - catch { return []; } - } + private static MetadataEntry GetRuntimeInfo() => new("runtime", "dotnet", Environment.Version.ToString()); - private static string? GetUnityVersion(IReadOnlyCollection loadedAssemblies) - { - var attr = loadedAssemblies - .SelectMany(SafeGetCustomAttributesData) - .FirstOrDefault(d => d.AttributeType.Name == "UnityAPICompatibilityVersionAttribute"); - return attr?.ConstructorArguments.Count > 0 ? attr.ConstructorArguments[0].Value as string : null; - } + // Priority is explicit: MAUI wins over Blazor in hybrid apps where both assemblies are present. + // Unity version uses GetCustomAttributesData() rather than member reflection — safe under IL2CPP. + private static MetadataEntry GetFrameworkInfo(IReadOnlyCollection loadedAssemblies) + { + var assemblies = loadedAssemblies + .GroupBy(a => a.GetName().Name) + .ToDictionary(g => g.Key, g => g.First()); + + if (assemblies.TryGetValue("Microsoft.Maui", out var maui)) + return new MetadataEntry("framework", "maui", GetInformationalVersion(maui)); + if (assemblies.ContainsKey("UnityEngine.CoreModule")) + return new MetadataEntry("framework", "unity", GetUnityVersion(loadedAssemblies)); + if (assemblies.TryGetValue("Microsoft.AspNetCore.Components", out var blazor)) + return new MetadataEntry("framework", "blazor", GetInformationalVersion(blazor)); + return MetadataEntry.Unknown("framework"); + } + + private static string? GetInformationalVersion(Assembly assembly) => + assembly.GetCustomAttribute()?.InformationalVersion; + + // Defensive: GetCustomAttributesData() can throw on exotic hosts (dynamic/reflection-emit assemblies); not reliably triggerable in a unit test. + [ExcludeFromCodeCoverage] + private static CustomAttributeData[] SafeGetCustomAttributesData(Assembly assembly) + { + try { return assembly.GetCustomAttributesData().ToArray(); } + catch { return []; } + } + + private static string? GetUnityVersion(IReadOnlyCollection loadedAssemblies) + { + var attr = loadedAssemblies + .SelectMany(SafeGetCustomAttributesData) + .FirstOrDefault(d => d.AttributeType.Name == "UnityAPICompatibilityVersionAttribute"); + return attr?.ConstructorArguments.Count > 0 ? attr.ConstructorArguments[0].Value as string : null; } }