From fb4d143bea0b0f26f078aa07331385448b3ea497 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Sun, 22 Nov 2026 22:59:49 +0800 Subject: [PATCH 1/2] Add Native AOT smoke coverage Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/ci.yml | 19 ++- README.md | 5 +- docs/native-aot.md | 32 +++++ .../FileSystem/StorageHelper.cs | 5 +- .../GeneralUpdate.Bowl.csproj | 1 + .../Internal/CrashReporter.cs | 2 +- .../FileSystem/StorageManager.cs | 12 +- tests/AotSmoke/AotSmoke.csproj | 14 ++ tests/AotSmoke/Program.cs | 133 ++++++++++++++++++ .../BowlTest/FileSystem/StorageHelperTests.cs | 28 ++-- 10 files changed, 216 insertions(+), 35 deletions(-) create mode 100644 docs/native-aot.md create mode 100644 tests/AotSmoke/AotSmoke.csproj create mode 100644 tests/AotSmoke/Program.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 28361112..4d17f350 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,7 +38,16 @@ jobs: dotnet test tests/DifferentialTest/DifferentialTest.csproj -c Release --no-build aot-verify: - runs-on: windows-latest + strategy: + matrix: + include: + - os: windows-latest + rid: win-x64 + executable: AotSmoke.exe + - os: ubuntu-latest + rid: linux-x64 + executable: AotSmoke + runs-on: ${{ matrix.os }} steps: - name: Checkout uses: actions/checkout@v6 @@ -48,8 +57,8 @@ jobs: with: dotnet-version: '10.0.x' - - name: Restore - run: dotnet restore ./src/GeneralUpdate.slnx + - name: Publish Native AOT smoke executable + run: dotnet publish ./tests/AotSmoke/AotSmoke.csproj -c Release -r ${{ matrix.rid }} -o ./artifacts/aot-smoke - - name: Verify AOT compatibility - run: dotnet build ./src/GeneralUpdate.Core/GeneralUpdate.Core.csproj -c Release -f net10.0 /p:IsAotCompatible=true --no-restore + - name: Run Native AOT smoke executable + run: ./artifacts/aot-smoke/${{ matrix.executable }} diff --git a/README.md b/README.md index 1422742e..22b6446d 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,10 @@ ![](./imgs/LOGO白1.png) -# GeneralUpdate # +# GeneralUpdate # # + +For the tested Native AOT scope and publish instructions, see +[Native AOT verification](docs/native-aot.md). **Unlimited Updates, Boundless Upgrades.**
diff --git a/docs/native-aot.md b/docs/native-aot.md new file mode 100644 index 00000000..5764d7ed --- /dev/null +++ b/docs/native-aot.md @@ -0,0 +1,32 @@ +# Native AOT verification + +The executable in `tests/AotSmoke` targets .NET 10 and disables reflection-based +JSON serialization. It exercises manifest persistence, the HTTP version request +and response over loopback, OSS version parsing, update reporting, encrypted +process-contract IPC, Bowl crash-report serialization, and a BSDiff patch +round trip. The OSS and reporting HTTP transports are in-memory test handlers; +the Bowl reporter is invoked directly without launching external dump tools. +These checks do not constitute an end-to-end application upgrade. + +On a machine with the [.NET Native AOT prerequisites](https://aka.ms/nativeaot-prerequisites), +publish and run the executable for the host RID, for example on Windows x64: + +```powershell +dotnet publish tests\AotSmoke\AotSmoke.csproj -c Release -r win-x64 -o artifacts\aot-smoke +.\artifacts\aot-smoke\AotSmoke.exe +``` + +CI publishes and runs the same executable for `win-x64` and `linux-x64`. +Other RIDs, .NET 8, and cross-compilation are not covered by this smoke test. +The host needs the matching native compiler and system dependencies; a successful +ordinary build or `IsAotCompatible` setting alone is not proof of AOT support. + +The smoke test covers only the paths listed above, not every Core API or +dependency. In particular SignalR push connections, complete download and +upgrade orchestration, external Bowl monitoring/diagnostics and rollback, +and third-party extensions or host-provided JSON types are not validated. +Callers of `StorageManager` must supply suitable `JsonTypeInfo`; arbitrary +application types require their own AOT-compatible metadata. The Differential +and Bowl dependencies currently target netstandard2.0, so their compatibility +cannot be inferred from Core's analyzer settings. Native publish warnings must +be evaluated for the paths used by each application. diff --git a/src/GeneralUpdate.Bowl/FileSystem/StorageHelper.cs b/src/GeneralUpdate.Bowl/FileSystem/StorageHelper.cs index 3a270fca..ba1b5759 100644 --- a/src/GeneralUpdate.Bowl/FileSystem/StorageHelper.cs +++ b/src/GeneralUpdate.Bowl/FileSystem/StorageHelper.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Text.Json; +using System.Text.Json.Serialization.Metadata; namespace GeneralUpdate.Bowl.FileSystem; @@ -48,7 +49,7 @@ public static void DeleteDirectory(string targetDir) Directory.Delete(targetDir, false); } - public static void CreateJson(string targetPath, T obj) where T : class + public static void CreateJson(string targetPath, T obj, JsonTypeInfo typeInfo) where T : class { var folderPath = Path.GetDirectoryName(targetPath) ?? throw new ArgumentException("invalid path", nameof(targetPath)); @@ -56,7 +57,7 @@ public static void CreateJson(string targetPath, T obj) where T : class if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath); - var jsonString = JsonSerializer.Serialize(obj); + var jsonString = JsonSerializer.Serialize(obj, typeInfo); File.WriteAllText(targetPath, jsonString); } } diff --git a/src/GeneralUpdate.Bowl/GeneralUpdate.Bowl.csproj b/src/GeneralUpdate.Bowl/GeneralUpdate.Bowl.csproj index 0e76b34d..9b1a6df8 100644 --- a/src/GeneralUpdate.Bowl/GeneralUpdate.Bowl.csproj +++ b/src/GeneralUpdate.Bowl/GeneralUpdate.Bowl.csproj @@ -33,6 +33,7 @@ + diff --git a/src/GeneralUpdate.Bowl/Internal/CrashReporter.cs b/src/GeneralUpdate.Bowl/Internal/CrashReporter.cs index f64c2735..6fa9a7eb 100644 --- a/src/GeneralUpdate.Bowl/Internal/CrashReporter.cs +++ b/src/GeneralUpdate.Bowl/Internal/CrashReporter.cs @@ -33,7 +33,7 @@ public Task GenerateReportAsync( }; var failJsonPath = Path.Combine(context.FailDirectory, context.FailFileName); - StorageHelper.CreateJson(failJsonPath, crash); + StorageHelper.CreateJson(failJsonPath, crash, CrashJsonContext.Default.Crash); GeneralTracer.Info($"CrashReporter.GenerateReportAsync: report written to {failJsonPath}."); return Task.FromResult(failJsonPath); diff --git a/src/GeneralUpdate.Core/FileSystem/StorageManager.cs b/src/GeneralUpdate.Core/FileSystem/StorageManager.cs index 37ac6fbe..81f95736 100644 --- a/src/GeneralUpdate.Core/FileSystem/StorageManager.cs +++ b/src/GeneralUpdate.Core/FileSystem/StorageManager.cs @@ -145,13 +145,11 @@ public ComparisonResult Compare(string leftDir, string rightDir) /// The type of the object to serialize. Must be a reference type. /// The full path of the target JSON file. /// The object instance to serialize. - /// JSON type info metadata for source generator serialization support. When null, the reflection-based serializer is used (not AOT-compatible); pass a generated context for Native AOT support. + /// Required JSON type metadata, typically from a generated context. /// Thrown when does not contain a valid directory path. /// /// If the directory of the target file does not exist, it will be created automatically. - /// When is null, this method falls back to the reflection-based serializer - /// which is not compatible with Native AOT. For AOT compilation, always pass a generated - /// instance. + /// A null throws; no reflection fallback is provided. /// public static void CreateJson(string targetPath, T obj, JsonTypeInfo? typeInfo = null) where T : class { @@ -176,13 +174,11 @@ public static void CreateJson(string targetPath, T obj, JsonTypeInfo? type /// /// The target type for deserialization. Must be a reference type. /// The full path of the JSON file. - /// JSON type info metadata for source generator deserialization support. When null, the reflection-based serializer is used (not AOT-compatible); pass a generated context for Native AOT support. + /// Required JSON type metadata, typically from a generated context. /// The deserialized object instance; returns default if the file does not exist. /// /// If the file does not exist, no exception is thrown and null is returned. - /// When is null, this method falls back to the reflection-based serializer - /// which is not compatible with Native AOT. For AOT compilation, always pass a generated - /// instance. + /// A null throws; no reflection fallback is provided. /// public static T? GetJson(string path, JsonTypeInfo? typeInfo = null) where T : class { diff --git a/tests/AotSmoke/AotSmoke.csproj b/tests/AotSmoke/AotSmoke.csproj new file mode 100644 index 00000000..541e6eea --- /dev/null +++ b/tests/AotSmoke/AotSmoke.csproj @@ -0,0 +1,14 @@ + + + Exe + net10.0 + enable + enable + true + false + + + + + + diff --git a/tests/AotSmoke/Program.cs b/tests/AotSmoke/Program.cs new file mode 100644 index 00000000..1d3ad7d7 --- /dev/null +++ b/tests/AotSmoke/Program.cs @@ -0,0 +1,133 @@ +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Internal; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Download.Reporting; +using GeneralUpdate.Core.Download.Sources; +using GeneralUpdate.Core.Ipc; +using GeneralUpdate.Core.Network; +using GeneralUpdate.Differential.Differ; + +static void Check(bool condition, string message) +{ + if (!condition) throw new InvalidOperationException(message); +} + +var directory = Path.Combine(Path.GetTempPath(), "GeneralUpdateAotSmoke_" + Guid.NewGuid().ToString("N")); +Directory.CreateDirectory(directory); +try +{ + Check(!JsonSerializer.IsReflectionEnabledByDefault, "JSON reflection must be disabled"); + var manifestPath = Path.Combine(directory, ManifestInfo.FileName); + new ManifestInfo { MainAppName = "app", ClientVersion = "1.0", ProductId = "product" }.Save(manifestPath); + Check(ManifestInfo.Load(manifestPath)?.ToUpdateRequest().ProductId == "product", "Manifest round trip failed"); + + var ipc = new EncryptedFileProcessContractProvider(directory); + await ipc.SendAsync(new ProcessContract + { + AppName = "app", + CurrentVersion = "1.0", + UpdateVersions = new List { new() { Version = "2.0", RecordId = 42 } } + }); + var contract = await ipc.ReceiveAsync(); + Check(contract?.AppName == "app" && contract.UpdateVersions[0].RecordId == 42, "IPC round trip failed"); + Check(!File.Exists(EncryptedFileProcessContractProvider.GetDefaultFilePath(directory)), "IPC file was not removed"); + + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var server = RespondToVersionRequest(listener); + using var versionTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + var response = await VersionService.Validate($"http://127.0.0.1:{port}/validate", "1.0", + AppType.Client, "", PlatformType.Windows, "product", ct: versionTimeout.Token); + await server; + Check(response.Body?.Count == 1 && response.Body[0].RecordId == 42, "Version response failed"); + + using var handler = new RecordingHandler(); + using var client = new HttpClient(handler); + var source = new OssDownloadSource(client, "http://localhost/versions"); + var assets = await source.ListAsync(); + Check(assets.Assets.Count == 1 && assets.Assets[0].Version == "2.0", "OSS version parsing failed"); + var reporter = new HttpUpdateReporter(client, "http://localhost/report"); + await reporter.ReportAsync(new UpdateReport(42, 2, 1)); + Check(handler.Report == "{\"recordId\":42,\"status\":2,\"type\":1}", "Update report payload failed"); + + var crashPath = await new CrashReporter().GenerateReportAsync(new BowlContext + { + FailDirectory = directory, + FailFileName = "crash.json", + ProcessNameOrId = "app", + ExtendedField = "2.0" + }, new[] { "dump captured" }, CancellationToken.None); + using var crash = JsonDocument.Parse(await File.ReadAllTextAsync(crashPath)); + Check(crash.RootElement.GetProperty("ProcessNameOrId").GetString() == "app" && + crash.RootElement.GetProperty("ProcdumpOutPutLines")[0].GetString() == "dump captured", + "Crash report failed"); + + var oldPath = Path.Combine(directory, "old.txt"); + var newPath = Path.Combine(directory, "new.txt"); + var patchPath = Path.Combine(directory, "patch.bin"); + var resultPath = Path.Combine(directory, "result.txt"); + await File.WriteAllTextAsync(oldPath, "old version of the application"); + await File.WriteAllTextAsync(newPath, "new version of the application with changes"); + var differ = new BsdiffDiffer(); + await differ.Clean(oldPath, newPath, patchPath); + await differ.Dirty(oldPath, resultPath, patchPath); + Check(await File.ReadAllTextAsync(resultPath) == await File.ReadAllTextAsync(newPath), "Binary patch failed"); + + Console.WriteLine("Native AOT smoke passed"); +} +finally +{ + Directory.Delete(directory, recursive: true); +} + +static async Task RespondToVersionRequest(TcpListener listener) +{ + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + using var connection = await listener.AcceptTcpClientAsync(timeout.Token); + using var stream = connection.GetStream(); + using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true); + var requestLine = await reader.ReadLineAsync(timeout.Token); + Check(requestLine?.StartsWith("POST /validate ", StringComparison.Ordinal) == true, "Wrong version request"); + var length = 0; + string? line; + while (!string.IsNullOrEmpty(line = await reader.ReadLineAsync(timeout.Token))) + { + if (line.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase)) + length = int.Parse(line["Content-Length:".Length..].Trim()); + } + var body = new char[length]; + await reader.ReadBlockAsync(body.AsMemory(), timeout.Token); + using var json = JsonDocument.Parse(new string(body)); + Check(json.RootElement.GetProperty("version").GetString() == "1.0" && + json.RootElement.GetProperty("productId").GetString() == "product", "Version request payload failed"); + const string response = "{\"code\":0,\"body\":[{\"recordId\":42,\"version\":\"2.0\"}],\"message\":\"ok\"}"; + var bytes = Encoding.UTF8.GetBytes(response); + var headers = Encoding.ASCII.GetBytes($"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {bytes.Length}\r\nConnection: close\r\n\r\n"); + await stream.WriteAsync(headers, timeout.Token); + await stream.WriteAsync(bytes, timeout.Token); +} + +sealed class RecordingHandler : HttpMessageHandler +{ + public string? Report { get; private set; } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.Method == HttpMethod.Post) + { + Report = await request.Content!.ReadAsStringAsync(cancellationToken); + return new HttpResponseMessage(HttpStatusCode.OK); + } + + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("[{\"PacketName\":\"app\",\"Version\":\"2.0\",\"Url\":\"http://localhost/app.zip\",\"Hash\":\"abc\",\"PubTime\":\"2025-01-01T00:00:00\"}]") + }; + } +} diff --git a/tests/BowlTest/FileSystem/StorageHelperTests.cs b/tests/BowlTest/FileSystem/StorageHelperTests.cs index 6bd37e6c..52fe1ab3 100644 --- a/tests/BowlTest/FileSystem/StorageHelperTests.cs +++ b/tests/BowlTest/FileSystem/StorageHelperTests.cs @@ -1,5 +1,6 @@ using System.Text.Json; using GeneralUpdate.Bowl.FileSystem; +using GeneralUpdate.Bowl.Internal; namespace BowlTest.FileSystem; @@ -32,9 +33,9 @@ public void Dispose() public void CreateJson_WritesValidJsonFile() { var filePath = Path.Combine(_testBasePath, "test.json"); - var obj = new { Name = "Test", Value = 42 }; + var obj = new Crash { ProcessNameOrId = "Test", ExtendedField = "42" }; - StorageHelper.CreateJson(filePath, obj); + StorageHelper.CreateJson(filePath, obj, CrashJsonContext.Default.Crash); Assert.True(System.IO.File.Exists(filePath)); var content = System.IO.File.ReadAllText(filePath); @@ -47,9 +48,9 @@ public void CreateJson_CreatesDirectoryIfMissing() { var subDir = Path.Combine(_testBasePath, "nested", "deep"); var filePath = Path.Combine(subDir, "data.json"); - var obj = new { Key = "value" }; + var obj = new Crash { ExtendedField = "value" }; - StorageHelper.CreateJson(filePath, obj); + StorageHelper.CreateJson(filePath, obj, CrashJsonContext.Default.Crash); Assert.True(System.IO.File.Exists(filePath)); } @@ -58,16 +59,16 @@ public void CreateJson_CreatesDirectoryIfMissing() public void CreateJson_ProducesDeserializableJson() { var filePath = Path.Combine(_testBasePath, "roundtrip.json"); - var original = new TestModel { Id = 1, Name = "roundtrip" }; + var original = new Crash { ProcessNameOrId = "roundtrip", ExtendedField = "1" }; - StorageHelper.CreateJson(filePath, original); + StorageHelper.CreateJson(filePath, original, CrashJsonContext.Default.Crash); var json = System.IO.File.ReadAllText(filePath); - var deserialized = JsonSerializer.Deserialize(json); + var deserialized = JsonSerializer.Deserialize(json, CrashJsonContext.Default.Crash); Assert.NotNull(deserialized); - Assert.Equal(original.Id, deserialized.Id); - Assert.Equal(original.Name, deserialized.Name); + Assert.Equal(original.ProcessNameOrId, deserialized.ProcessNameOrId); + Assert.Equal(original.ExtendedField, deserialized.ExtendedField); } #endregion @@ -168,13 +169,4 @@ public void DeleteDirectory_RemovesReadOnlyFiles() #endregion - #region Helper model - - private sealed class TestModel - { - public int Id { get; set; } - public string Name { get; set; } = string.Empty; - } - - #endregion } From e9f2dcb1d7175f591319e33d29bd7a3d3b6fcb71 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Sun, 22 Nov 2026 23:08:21 +0800 Subject: [PATCH 2/2] Document Native AOT tracing limitation Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/native-aot.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/native-aot.md b/docs/native-aot.md index 5764d7ed..711471f1 100644 --- a/docs/native-aot.md +++ b/docs/native-aot.md @@ -29,4 +29,6 @@ Callers of `StorageManager` must supply suitable `JsonTypeInfo`; arbitrary application types require their own AOT-compatible metadata. The Differential and Bowl dependencies currently target netstandard2.0, so their compatibility cannot be inferred from Core's analyzer settings. Native publish warnings must -be evaluated for the paths used by each application. +be evaluated for the paths used by each application. The smoke publish reports +IL2026 for Core and Bowl tracing: stack-frame method metadata may be unavailable +after trimming, so diagnostic method names are best-effort.