Skip to content
Open
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
19 changes: 14 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 }}
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.**</br>

Expand Down
34 changes: 34 additions & 0 deletions docs/native-aot.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# 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. 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.
5 changes: 3 additions & 2 deletions src/GeneralUpdate.Bowl/FileSystem/StorageHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;

namespace GeneralUpdate.Bowl.FileSystem;

Expand Down Expand Up @@ -48,15 +49,15 @@ public static void DeleteDirectory(string targetDir)
Directory.Delete(targetDir, false);
}

public static void CreateJson<T>(string targetPath, T obj) where T : class
public static void CreateJson<T>(string targetPath, T obj, JsonTypeInfo<T> typeInfo) where T : class
{
var folderPath = Path.GetDirectoryName(targetPath) ??
throw new ArgumentException("invalid path", nameof(targetPath));

if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);

var jsonString = JsonSerializer.Serialize(obj);
var jsonString = JsonSerializer.Serialize(obj, typeInfo);
File.WriteAllText(targetPath, jsonString);
}
}
1 change: 1 addition & 0 deletions src/GeneralUpdate.Bowl/GeneralUpdate.Bowl.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

<ItemGroup>
<InternalsVisibleTo Include="BowlTest" />
<InternalsVisibleTo Include="AotSmoke" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/GeneralUpdate.Bowl/Internal/CrashReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public Task<string> 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);
Expand Down
12 changes: 4 additions & 8 deletions src/GeneralUpdate.Core/FileSystem/StorageManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,11 @@ public ComparisonResult Compare(string leftDir, string rightDir)
/// <typeparam name="T">The type of the object to serialize. Must be a reference type.</typeparam>
/// <param name="targetPath">The full path of the target JSON file.</param>
/// <param name="obj">The object instance to serialize.</param>
/// <param name="typeInfo">JSON type info metadata for source generator serialization support. When <c>null</c>, the reflection-based serializer is used (not AOT-compatible); pass a generated context for Native AOT support.</param>
/// <param name="typeInfo">Required JSON type metadata, typically from a generated context.</param>
/// <exception cref="ArgumentException">Thrown when <paramref name="targetPath"/> does not contain a valid directory path.</exception>
/// <remarks>
/// If the directory of the target file does not exist, it will be created automatically.
/// When <paramref name="typeInfo"/> 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
/// <see cref="JsonTypeInfo{T}"/> instance.
/// A null <paramref name="typeInfo"/> throws; no reflection fallback is provided.
/// </remarks>
public static void CreateJson<T>(string targetPath, T obj, JsonTypeInfo<T>? typeInfo = null) where T : class
{
Expand All @@ -176,13 +174,11 @@ public static void CreateJson<T>(string targetPath, T obj, JsonTypeInfo<T>? type
/// </summary>
/// <typeparam name="T">The target type for deserialization. Must be a reference type.</typeparam>
/// <param name="path">The full path of the JSON file.</param>
/// <param name="typeInfo">JSON type info metadata for source generator deserialization support. When <c>null</c>, the reflection-based serializer is used (not AOT-compatible); pass a generated context for Native AOT support.</param>
/// <param name="typeInfo">Required JSON type metadata, typically from a generated context.</param>
/// <returns>The deserialized object instance; returns <c>default</c> if the file does not exist.</returns>
/// <remarks>
/// If the file does not exist, no exception is thrown and <c>null</c> is returned.
/// When <paramref name="typeInfo"/> 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
/// <see cref="JsonTypeInfo{T}"/> instance.
/// A null <paramref name="typeInfo"/> throws; no reflection fallback is provided.
/// </remarks>
public static T? GetJson<T>(string path, JsonTypeInfo<T>? typeInfo = null) where T : class
{
Expand Down
14 changes: 14 additions & 0 deletions tests/AotSmoke/AotSmoke.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\GeneralUpdate.Core\GeneralUpdate.Core.csproj" />
<ProjectReference Include="..\..\src\GeneralUpdate.Bowl\GeneralUpdate.Bowl.csproj" />
</ItemGroup>
</Project>
133 changes: 133 additions & 0 deletions tests/AotSmoke/Program.cs
Original file line number Diff line number Diff line change
@@ -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<VersionEntry> { 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<HttpResponseMessage> 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\"}]")
};
}
}
28 changes: 10 additions & 18 deletions tests/BowlTest/FileSystem/StorageHelperTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Text.Json;
using GeneralUpdate.Bowl.FileSystem;
using GeneralUpdate.Bowl.Internal;

namespace BowlTest.FileSystem;

Expand Down Expand Up @@ -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);
Expand All @@ -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));
}
Expand All @@ -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<TestModel>(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
Expand Down Expand Up @@ -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
}
Loading