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

This file was deleted.

86 changes: 69 additions & 17 deletions packages/Core/Core.Tests/UtilTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using Core.Tests.TestDoubles;
Expand All @@ -20,8 +19,15 @@ namespace Core.Tests;
[TestCategory("Unit")]
public class UtilTests
{
private static readonly Func<OSPlatform, bool> NoPlatform = _ => false;
private static readonly IReadOnlyCollection<Assembly> NoFrameworks = [];
private static readonly HostEnvironment PlainHost = new(
OsDescription: "any",
IsOsPlatform: _ => false,
LoadedAssemblies: [],
FrameworkDescription: ".NET 10.0.0",
UnityVersion: () => null,
UnityPlatform: () => null);

private static readonly HostEnvironment UnityHost = PlainHost with { LoadedAssemblies = [FakeAssembly.Named("UnityEngine.CoreModule")] };

[TestMethod]
public void GetAssemblyVersion_ShouldStartWithClientNameAndVersion() =>
Expand Down Expand Up @@ -61,7 +67,7 @@ public void GetAssemblyVersion_ShouldReuseCachedValue_GivenAssemblyIsAlreadyGene

[TestMethod]
public void GetAssemblyVersion_ShouldReportBrowserPlatform_GivenBrowserOsDescription() =>
HeaderFor("Browser", NoPlatform).Should().Contain("; platform=browser;");
HeaderFor("Browser", PlainHost.IsOsPlatform).Should().Contain("; platform=browser;");

[TestMethod]
public void GetAssemblyVersion_ShouldReportWindowsPlatform_GivenWindows() =>
Expand All @@ -85,41 +91,87 @@ public void GetAssemblyVersion_ShouldReportAndroidPlatform_GivenAndroid() =>

[TestMethod]
public void GetAssemblyVersion_ShouldFallBackToOsDescription_GivenUnrecognizedPlatform() =>
HeaderFor("Solaris 11", NoPlatform).Should().Contain("; platform=Solaris 11;");
HeaderFor("Solaris 11", PlainHost.IsOsPlatform).Should().Contain("; platform=Solaris 11;");

[TestMethod]
public void GetAssemblyVersion_ShouldReportUnknownFramework_GivenNoKnownFrameworkAssembly() =>
HeaderWith(NoFrameworks).Should().Contain("; framework=unknown");
Header(PlainHost).Should().Contain("; framework=unknown");

[TestMethod]
public void GetAssemblyVersion_ShouldReportMauiFramework_GivenMauiAssembly() =>
HeaderWith([FakeAssembly.Named("Microsoft.Maui")]).Should().Contain("; framework=maui");
HeaderWith(FakeAssembly.Named("Microsoft.Maui")).Should().Contain("; framework=maui");

[TestMethod]
public void GetAssemblyVersion_ShouldReportBlazorFramework_GivenBlazorAssembly() =>
HeaderWith([FakeAssembly.Named("Microsoft.AspNetCore.Components")]).Should().Contain("; framework=blazor");
HeaderWith(FakeAssembly.Named("Microsoft.AspNetCore.Components")).Should().Contain("; framework=blazor");

[TestMethod]
public void GetAssemblyVersion_ShouldPreferMauiOverBlazor_GivenBothAssemblies() =>
HeaderWith([FakeAssembly.Named("Microsoft.AspNetCore.Components"), FakeAssembly.Named("Microsoft.Maui")])
HeaderWith(FakeAssembly.Named("Microsoft.AspNetCore.Components"), FakeAssembly.Named("Microsoft.Maui"))
.Should().Contain("; framework=maui", "MAUI wins over Blazor in hybrid apps where both are present");

[TestMethod]
public void GetAssemblyVersion_ShouldReportUnityFrameworkWithVersion_GivenUnityAssembly() =>
HeaderWith([FakeAssembly.Named("UnityEngine.CoreModule"), typeof(UtilTests).Assembly])
.Should().Contain("; framework=unity; framework-version=2022.3.5f1");
Header(UnityHost with { UnityVersion = () => "6000.3.21f1" })
.Should().Contain("; framework=unity; framework-version=6000.3.21f1");

[TestMethod]
public void GetAssemblyVersion_ShouldReportUnityFrameworkWithoutVersion_GivenNoUnityVersionAttribute() =>
HeaderWith([FakeAssembly.Named("UnityEngine.CoreModule")])
public void GetAssemblyVersion_ShouldReportUnityFrameworkWithoutVersion_GivenUnityVersionIsUnavailable() =>
Header(UnityHost)
.Should().Contain("; framework=unity").And.NotContain("framework-version",
"an absent Unity version attribute must resolve to no version, not throw");
"a stripped Application.unityVersion must resolve to no version, not throw");

[TestMethod]
[DataRow("Android", "Android")]
[DataRow("IPhonePlayer", "iOS")]
[DataRow("WebGLPlayer", "browser")]
[DataRow("WindowsPlayer", "Windows")]
[DataRow("WSAPlayerARM", "Windows")]
[DataRow("OSXEditor", "macOS")]
[DataRow("LinuxServer", "Linux")]
[DataRow("EmbeddedLinuxArm64", "Linux")]
[DataRow("Switch", "Switch")]
public void GetAssemblyVersion_ShouldReportUnityPlatform_GivenUnityRuntimePlatform(string runtimePlatform, string expected) =>
Header(UnityHost with { OsDescription = "Unix 5.15.189.13", UnityPlatform = () => runtimePlatform })
.Should().Contain($"; platform={expected};");

[TestMethod]
public void GetAssemblyVersion_ShouldFallBackToOsPlatform_GivenUnityPlatformIsUnavailable() =>
Header(UnityHost with { OsDescription = "Unix 5.15.189.13" })
.Should().Contain("; platform=Unix 5.15.189.13;");

[TestMethod]
public void GetAssemblyVersion_ShouldIgnoreUnityPlatform_GivenNoUnityAssembly() =>
Header(PlainHost with { OsDescription = "Solaris 11", UnityPlatform = () => "Android" })
.Should().Contain("; platform=Solaris 11;");

[TestMethod]
public void GetAssemblyVersion_ShouldReportMonoRuntimeVersion_GivenUnityOnMono() =>
Header(UnityHost with { FrameworkDescription = "Mono 6.13.0 (Visual Studio built mono)" })
.Should().Contain("; runtime=mono; runtime-version=6.13.0;");

[TestMethod]
public void GetAssemblyVersion_ShouldReportIl2CppRuntimeWithoutVersion_GivenUnityOnIl2Cpp() =>
Header(UnityHost with { FrameworkDescription = "Mono Unity IL2CPP(Oct 1 2025 10:00:00)" })
.Should().Contain("; runtime=il2cpp; framework=unity");

[TestMethod]
public void GetAssemblyVersion_ShouldReportDotnetRuntime_GivenUnityWithUnrecognizedFrameworkDescription() =>
Header(UnityHost with { FrameworkDescription = ".NET 10.0.0" })
.Should().MatchRegex("; runtime=dotnet; runtime-version=[^;]+; framework=unity");

[TestMethod]
public void GetAssemblyVersion_ShouldReportDotnetRuntime_GivenMonoOutsideUnity() =>
Header(PlainHost with { FrameworkDescription = "Mono 6.13.0 (Visual Studio built mono)" })
.Should().Contain("; runtime=dotnet;");

private static string Header(HostEnvironment host) => Util.GetAssemblyVersion(typeof(Util), host);

private static string HeaderFor(string osDescription, Func<OSPlatform, bool> isOsPlatform) =>
Util.GetAssemblyVersion(typeof(Util), osDescription, isOsPlatform, NoFrameworks);
Header(PlainHost with { OsDescription = osDescription, IsOsPlatform = isOsPlatform });

private static string HeaderWith(IReadOnlyCollection<Assembly> loadedAssemblies) =>
Util.GetAssemblyVersion(typeof(Util), "any", NoPlatform, loadedAssemblies);
private static string HeaderWith(params Assembly[] loadedAssemblies) =>
Header(PlainHost with { LoadedAssemblies = loadedAssemblies });

private static Func<OSPlatform, bool> OnlyPlatform(OSPlatform platform) => p => p == platform;
}
48 changes: 48 additions & 0 deletions packages/Core/Core/HostEnvironment.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.InteropServices;

namespace Supabase.Core;

/// <summary>
/// The process-wide ambient reads behind the <c>X-Client-Info</c> header: OS, runtime, loaded
/// assemblies and, inside a Unity host, the engine's own view of version and platform.
/// </summary>
/// <remarks>
/// Testability seam: a host cannot vary these at runtime, so <see cref="Util"/> takes them as a value
/// and every platform/runtime/framework branch is reachable hermetically. Internal, not public API.
/// </remarks>
internal sealed record HostEnvironment(
string OsDescription,
Func<OSPlatform, bool> IsOsPlatform,
IReadOnlyCollection<Assembly> LoadedAssemblies,
string FrameworkDescription,
Func<string?> UnityVersion,
Func<string?> UnityPlatform)
{
[ExcludeFromCodeCoverage]
internal static HostEnvironment Current() => new(
RuntimeInformation.OSDescription,
RuntimeInformation.IsOSPlatform,
AppDomain.CurrentDomain.GetAssemblies(),
RuntimeInformation.FrameworkDescription,
() => ReadUnityApplicationProperty("unityVersion") as string,
() => ReadUnityApplicationProperty("platform")?.ToString());

[ExcludeFromCodeCoverage]
private static object? ReadUnityApplicationProperty(string name)
{
try
{
return Type.GetType("UnityEngine.Application, UnityEngine.CoreModule", throwOnError: false)
?.GetProperty(name, BindingFlags.Public | BindingFlags.Static)
?.GetValue(null);
}
catch
{
return null;
}
}
}
91 changes: 53 additions & 38 deletions packages/Core/Core/Util.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
Expand All @@ -27,42 +26,42 @@ public static string GetAssemblyVersion(Type clientType) =>
ClientInfoCache.GetOrAdd(clientType.Assembly, static (_, type) => BuildClientInfo(type), clientType);

// The header is process-invariant, yet callers stamp it on every request; building it scans
// every loaded assembly (and, on Unity, every assembly's attributes), so it is built once per client assembly.
// every loaded assembly, so it is built once per client assembly.
private static readonly ConcurrentDictionary<Assembly, string> ClientInfoCache = new();

private static string BuildClientInfo(Type clientType) =>
GetAssemblyVersion(clientType, RuntimeInformation.OSDescription, RuntimeInformation.IsOSPlatform, AppDomain.CurrentDomain.GetAssemblies());
private static string BuildClientInfo(Type clientType) => GetAssemblyVersion(clientType, HostEnvironment.Current());

// 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<OSPlatform, bool> isOsPlatform, IReadOnlyCollection<Assembly> loadedAssemblies) =>
$"{GetClientName(clientType)}-csharp/{GetClientVersion(clientType)}{BuildMetadata(osDescription, isOsPlatform, loadedAssemblies)}";
internal static string GetAssemblyVersion(Type clientType, HostEnvironment host) =>
$"{GetClientName(clientType)}-csharp/{GetClientVersion(clientType)}{BuildMetadata(host)}";

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<OSPlatform, bool> isOsPlatform, IReadOnlyCollection<Assembly> loadedAssemblies) =>
string.Concat(GetPlatformInfo(osDescription, isOsPlatform).ToString(), GetRuntimeInfo().ToString(), GetFrameworkInfo(loadedAssemblies).ToString());
private static string BuildMetadata(HostEnvironment host)
{
var framework = GetFrameworkInfo(host);
var isUnityHost = framework.Value == "unity";
return string.Concat(GetPlatformInfo(host, isUnityHost).ToString(), GetRuntimeInfo(host, isUnityHost).ToString(), framework.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.Value = value;
this.version = version;
}

internal string Value { get; }

public override string ToString() => string.IsNullOrEmpty(this.version)
? $"; {this.key}={this.value}"
: $"; {this.key}={this.value}; {this.key}-version={this.version}";
? $"; {this.key}={this.Value}"
: $"; {this.key}={this.Value}; {this.key}-version={this.version}";

internal static MetadataEntry Unknown(string key) => new(key, "unknown");
}
Expand All @@ -78,43 +77,59 @@ private static string GetPlatform(string osDescription, Func<OSPlatform, bool> i
return osDescription;
}

private static MetadataEntry GetPlatformInfo(string osDescription, Func<OSPlatform, bool> isOsPlatform) => new("platform", GetPlatform(osDescription, isOsPlatform), Environment.OSVersion.Version.ToString());
private static string? GetUnityPlatform(HostEnvironment host) =>
host.UnityPlatform() is { } runtimePlatform ? ToPlatformName(runtimePlatform) : null;

private static MetadataEntry GetRuntimeInfo() => new("runtime", "dotnet", Environment.Version.ToString());
private static string ToPlatformName(string unityRuntimePlatform) => unityRuntimePlatform switch
{
"IPhonePlayer" => "iOS",
"WebGLPlayer" => "browser",
_ when StartsWithAny(unityRuntimePlatform, "Windows", "WSAPlayer") => "Windows",
_ when StartsWithAny(unityRuntimePlatform, "OSX") => "macOS",
_ when StartsWithAny(unityRuntimePlatform, "Linux", "EmbeddedLinux") => "Linux",
_ => unityRuntimePlatform,
};

private static bool StartsWithAny(string value, params string[] prefixes) =>
prefixes.Any(prefix => value.StartsWith(prefix, StringComparison.Ordinal));

private static MetadataEntry GetPlatformInfo(HostEnvironment host, bool isUnityHost)
{
var platform = (isUnityHost ? GetUnityPlatform(host) : null) ?? GetPlatform(host.OsDescription, host.IsOsPlatform);
return new MetadataEntry("platform", platform, Environment.OSVersion.Version.ToString());
}

private static MetadataEntry GetRuntimeInfo(HostEnvironment host, bool isUnityHost) =>
(isUnityHost ? GetUnityRuntimeInfo(host.FrameworkDescription) : null) ?? new MetadataEntry("runtime", "dotnet", Environment.Version.ToString());

private const string MonoPrefix = "Mono ";

private static MetadataEntry? GetUnityRuntimeInfo(string frameworkDescription) => frameworkDescription switch
{
_ when frameworkDescription.Contains("IL2CPP", StringComparison.OrdinalIgnoreCase) => new MetadataEntry("runtime", "il2cpp"),
_ when frameworkDescription.StartsWith(MonoPrefix, StringComparison.Ordinal) => new MetadataEntry("runtime", "mono", ParseMonoVersion(frameworkDescription)),
_ => null,
};

private static string ParseMonoVersion(string frameworkDescription) =>
frameworkDescription.Substring(MonoPrefix.Length).Split(' ')[0];

// 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<Assembly> loadedAssemblies)
private static MetadataEntry GetFrameworkInfo(HostEnvironment host)
{
var assemblies = loadedAssemblies
var assemblies = host.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));
return new MetadataEntry("framework", "unity", host.UnityVersion());
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<AssemblyInformationalVersionAttribute>()?.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<Assembly> loadedAssemblies)
{
var attr = loadedAssemblies
.SelectMany(SafeGetCustomAttributesData)
.FirstOrDefault(d => d.AttributeType.Name == "UnityAPICompatibilityVersionAttribute");
return attr?.ConstructorArguments.Count > 0 ? attr.ConstructorArguments[0].Value as string : null;
}
}
Loading