diff --git a/packages/Core/Core.Tests/TestDoubles/UnityApiCompatibilityVersionAttribute.cs b/packages/Core/Core.Tests/TestDoubles/UnityApiCompatibilityVersionAttribute.cs deleted file mode 100644 index 3b3ee2a6f..000000000 --- a/packages/Core/Core.Tests/TestDoubles/UnityApiCompatibilityVersionAttribute.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using Core.Tests.TestDoubles; - -// Util.GetUnityVersion scans loaded assemblies for a custom attribute whose type name is exactly -// "UnityAPICompatibilityVersionAttribute" (Unity stamps this on its player assemblies). Declaring the -// same shape here and applying it to the test assembly lets the unity branch resolve a real version -// hermetically, without a Unity install. -[assembly: UnityAPICompatibilityVersion("2022.3.5f1")] - -namespace Core.Tests.TestDoubles; - -[AttributeUsage(AttributeTargets.Assembly)] -internal sealed class UnityAPICompatibilityVersionAttribute : Attribute -{ - public UnityAPICompatibilityVersionAttribute(string version) => this.Version = version; - - public string Version { get; } -} diff --git a/packages/Core/Core.Tests/UtilTests.cs b/packages/Core/Core.Tests/UtilTests.cs index e3e25a946..dff446c69 100644 --- a/packages/Core/Core.Tests/UtilTests.cs +++ b/packages/Core/Core.Tests/UtilTests.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using Core.Tests.TestDoubles; @@ -20,8 +19,15 @@ namespace Core.Tests; [TestCategory("Unit")] public class UtilTests { - private static readonly Func NoPlatform = _ => false; - private static readonly IReadOnlyCollection 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() => @@ -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() => @@ -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 isOsPlatform) => - Util.GetAssemblyVersion(typeof(Util), osDescription, isOsPlatform, NoFrameworks); + Header(PlainHost with { OsDescription = osDescription, IsOsPlatform = isOsPlatform }); - private static string HeaderWith(IReadOnlyCollection loadedAssemblies) => - Util.GetAssemblyVersion(typeof(Util), "any", NoPlatform, loadedAssemblies); + private static string HeaderWith(params Assembly[] loadedAssemblies) => + Header(PlainHost with { LoadedAssemblies = loadedAssemblies }); private static Func OnlyPlatform(OSPlatform platform) => p => p == platform; } diff --git a/packages/Core/Core/HostEnvironment.cs b/packages/Core/Core/HostEnvironment.cs new file mode 100644 index 000000000..8c6f29f5a --- /dev/null +++ b/packages/Core/Core/HostEnvironment.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Supabase.Core; + +/// +/// The process-wide ambient reads behind the X-Client-Info header: OS, runtime, loaded +/// assemblies and, inside a Unity host, the engine's own view of version and platform. +/// +/// +/// Testability seam: a host cannot vary these at runtime, so takes them as a value +/// and every platform/runtime/framework branch is reachable hermetically. Internal, not public API. +/// +internal sealed record HostEnvironment( + string OsDescription, + Func IsOsPlatform, + IReadOnlyCollection LoadedAssemblies, + string FrameworkDescription, + Func UnityVersion, + Func 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; + } + } +} diff --git a/packages/Core/Core/Util.cs b/packages/Core/Core/Util.cs index 8fce20994..3b6cf7bd9 100644 --- a/packages/Core/Core/Util.cs +++ b/packages/Core/Core/Util.cs @@ -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; @@ -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 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 isOsPlatform, IReadOnlyCollection 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 isOsPlatform, IReadOnlyCollection 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"); } @@ -78,22 +77,54 @@ private static string GetPlatform(string osDescription, Func i return osDescription; } - private static MetadataEntry GetPlatformInfo(string osDescription, Func 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 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"); @@ -101,20 +132,4 @@ private static MetadataEntry GetFrameworkInfo(IReadOnlyCollection load 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; - } }