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
33 changes: 33 additions & 0 deletions .github/workflows/push-aot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: Push Native AOT smoke

on:
pull_request:
paths:
- 'src/GeneralUpdate.Core/**'
- 'src/GeneralUpdate.Differential/**'
- 'tests/PushAotSmoke/**'
- '.github/workflows/push-aot.yml'
workflow_dispatch:

permissions:
contents: read

jobs:
push-aot:
runs-on: windows-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-dotnet@v5
with:
dotnet-version: '10.0.x'
- name: Publish and run native push smoke
shell: cmd
run: |
for /f "usebackq tokens=*" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "VSROOT=%%i"
if not defined VSROOT exit /b 1
call "%VSROOT%\Common7\Tools\VsDevCmd.bat" -arch=x64 -host_arch=x64
if errorlevel 1 exit /b 1
dotnet publish tests\PushAotSmoke\PushAotSmoke.csproj -c Release -r win-x64 -o "%RUNNER_TEMP%\push-aot"
if errorlevel 1 exit /b 1
"%RUNNER_TEMP%\push-aot\PushAotSmoke.exe"
if errorlevel 1 exit /b 1
18 changes: 18 additions & 0 deletions docs/core-execution-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,24 @@ sidebar_position: 4

## 1. 架构总览

### SignalR 推送的宿主接入

`UpgradeHubService.AddListenerReceive` 接收服务端 `ReceiveMessage` 的单个字符串参数。
宿主可先用 `JsonSerializer.Deserialize(message, PushPayloadJsonContext.Default.PushPayload)`
检查 `ProductId`、`Platform`、包格式、来源和适用版本,再为每次推送单独创建
`new PushDownloadSource(message)`,以 `.DownloadSource(source)` 注册到本次
`GeneralUpdateBootstrap`(或设置 `ClientStrategy.DownloadSource`)。不要与轮询结果混合:
推送源使用消息中的 `RecordId`,自动选择报告类型 2,并随 IPC 传给 Upgrade 进程。
老服务端未提供 ID 时仍可处理包,但不会发送记录回执;不会用 Verification 的 ID 代替。
无效的 AppType、URL 或版本信息会被拒绝。宿主负责连接生命周期、异步调度、
避免并发升级,以及验证推送包是否适合当前安装(包括差分包的前置版本)。

下载沿用 `HttpDownloadExecutor` 的全局认证和额外请求头;本地文件服务的租户包需要宿主
配置 `X-Tenant-Id`,例如在 `UpdateRequest.CustomHeaders` 中配置。报告请求也使用这些头。
这些配置是进程级的,宿主必须限制可信下载地址、隔离租户并避免向不可信 URL 泄露凭据;
签名 OBS URL 不代表本地文件服务无需租户认证。消息内的 `Format` 不会自动改变客户端
配置,宿主应确保包格式与配置的 `Option.Format` 一致。实际 HTTP/数据库链路仍需部署环境验证。

### 1.1 三层架构

GeneralUpdate.Core 采用**三层调度 + 两层引擎**的设计:
Expand Down
9 changes: 9 additions & 0 deletions src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -245,11 +245,20 @@ protected T GetOption<T>(Option<T>? option)
/// </remarks>
public TBootstrap DownloadSource<T>() where T : Download.Abstractions.IDownloadSource, new()
{
_instances.Remove(typeof(Download.Abstractions.IDownloadSource));
_extensions[typeof(Download.Abstractions.IDownloadSource)] = typeof(T);
_extensionFactories[typeof(Download.Abstractions.IDownloadSource)] = () => new T();
return (TBootstrap)this;
}

/// <summary>Registers a pre-constructed download source for this update.</summary>
public TBootstrap DownloadSource(Download.Abstractions.IDownloadSource source)
{
_instances[typeof(Download.Abstractions.IDownloadSource)] =
source ?? throw new ArgumentNullException(nameof(source));
return (TBootstrap)this;
}

/// <summary>
/// Registers a custom post-download processing pipeline for performing hash verification,
/// decryption, virus scanning, or other post-processing on downloaded files.
Expand Down
13 changes: 13 additions & 0 deletions src/GeneralUpdate.Core/Configuration/PushPayload.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,19 @@ namespace GeneralUpdate.Core.Configuration;
/// </summary>
public class PushPayload : VersionIdentity
{
/// <summary>Push record identifier, absent when sent by older servers.</summary>
[JsonPropertyName("RecordId")]
public int? RecordId { get; set; }

[JsonPropertyName("Size")]
public long Size { get; set; }

[JsonPropertyName("PackageType")]
public int PackageType { get; set; }

[JsonPropertyName("Format")]
public string? Format { get; set; }

[JsonPropertyName("IsForcibly")]
public bool? IsForcibly { get; set; }

Expand Down
10 changes: 10 additions & 0 deletions src/GeneralUpdate.Core/Download/DownloadPlanBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,16 @@ public static DownloadPlan Build(
.Where(a => a.PackageType == (int)Configuration.PackageType.Full)
.ToList();

if (chainCandidates.Count == 0 && fullCandidates.Count > 0)
{
var latestFulls = fullCandidates
.GroupBy(a => a.AppType)
.Select(g => g.OrderByDescending(a => Lookup(a)).First())
.OrderBy(a => Lookup(a))
.ToList();
return new DownloadPlan(latestFulls, isForcibly);
}

// ── Chain vs Full: count-first heuristic ──
if (chainCandidates.Count > 0 && fullCandidates.Count > 0)
{
Expand Down
71 changes: 71 additions & 0 deletions src/GeneralUpdate.Core/Download/Sources/PushDownloadSource.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using System;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using GeneralUpdate.Core.Configuration;
using GeneralUpdate.Core.Download.Abstractions;
using GeneralUpdate.Core.Download.Models;
using GeneralUpdate.Core.JsonContext;

namespace GeneralUpdate.Core.Download.Sources;

/// <summary>
/// A single GeneralSpace SignalR packet, used as the source for one push-triggered update.
/// </summary>
public sealed class PushDownloadSource : IDownloadSource
{
private readonly DownloadAsset _asset;

/// <summary>
/// Parses the single JSON string delivered to the ReceiveMessage listener.
/// The packet must identify its application type, URL and version; a missing push
/// record ID is supported for older servers but cannot be reported.
/// </summary>
public PushDownloadSource(string message)
{
if (message == null) throw new ArgumentNullException(nameof(message));
var packet = JsonSerializer.Deserialize(message, PushPayloadJsonContext.Default.PushPayload)
?? throw new JsonException("The push packet must not be null.");
if (packet.AppType != (int)AppType.Client && packet.AppType != (int)AppType.Upgrade)
throw new JsonException("The push packet must specify a Client or Upgrade AppType.");
if (string.IsNullOrWhiteSpace(packet.Url) || string.IsNullOrWhiteSpace(packet.Version))
throw new JsonException("The push packet must include a download URL and version.");
if (packet.RecordId < 0 || packet.Size < 0 || packet.PackageType < 0 || packet.PackageType > 2)
throw new JsonException("The push packet contains invalid record, size or package type values.");

var name = string.IsNullOrWhiteSpace(packet.Name) ? packet.Version! : packet.Name!;
if (name.EndsWith(Format.Zip.ToExtension(), StringComparison.OrdinalIgnoreCase))
name = name.Substring(0, name.Length - Format.Zip.ToExtension().Length);
if (string.IsNullOrWhiteSpace(name) || name == "." || name == ".." ||
name.IndexOf('/') >= 0 || name.IndexOf('\\') >= 0 ||
name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
throw new JsonException("The push packet contains an invalid package name.");

if (!packet.RecordId.HasValue || packet.RecordId == 0)
GeneralTracer.Warn("PushDownloadSource: no push record ID; update status cannot be reported.");

_asset = new DownloadAsset(
Name: name,
Url: packet.Url!,
Size: packet.Size,
SHA256: packet.Hash,
Version: packet.Version!,
PackageType: packet.PackageType,
IsForcibly: packet.IsForcibly == true,
IsFreeze: packet.IsFreeze == true,
RecordId: packet.RecordId ?? 0,
AppType: packet.AppType);
}

public Task<DownloadSourceResult> ListAsync(CancellationToken token = default)
{
token.ThrowIfCancellationRequested();
return Task.FromResult(new DownloadSourceResult
{
Assets = new[] { _asset },
HasMainUpdate = _asset.AppType == (int)AppType.Client,
HasUpgradeUpdate = _asset.AppType == (int)AppType.Upgrade
});
}
}
1 change: 1 addition & 0 deletions src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@ public virtual async Task ExecuteAsync()

foreach (var record in recordStatuses)
{
if (_configinfo.ReportType == 2 && record.Key <= 0) continue;
try
{
await Reporter.ReportAsync(new UpdateReport(record.Key, record.Value, _configinfo.ReportType)).ConfigureAwait(false);
Expand Down
10 changes: 10 additions & 0 deletions src/GeneralUpdate.Core/Strategy/ClientStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,12 @@ private async Task ExecuteStandardWorkflowAsync()
_configInfo.BasicUsername,
_configInfo.BasicPassword);

if (downloadSource is Download.Sources.PushDownloadSource)
{
_reportType = 2;
_configInfo.ReportType = 2;
Comment on lines +438 to +439
}

// Call server validation — returns assets from the two Validate calls
var sourceResult = await downloadSource.ListAsync().ConfigureAwait(false);

Expand Down Expand Up @@ -1130,6 +1136,7 @@ private async Task SafeOnDownloadCompletedAsync(Hooks.HookContext ctx)
/// <param name="ctx">The update context.</param>
private async Task SafeReportUpdateStartedAsync(Hooks.HookContext ctx)
{
if (_reportType == 2 && _mainRecordId <= 0 && _upgradeRecordId <= 0) return;
try
{
await Reporter
Expand All @@ -1148,6 +1155,7 @@ await Reporter
/// <param name="ctx">The update context.</param>
private async Task SafeReportDownloadCompletedAsync(Hooks.HookContext ctx)
{
if (_reportType == 2 && _mainRecordId <= 0 && _upgradeRecordId <= 0) return;
try
{
await Reporter
Expand All @@ -1167,6 +1175,7 @@ await Reporter
/// <param name="error">The exception that caused the update to fail.</param>
private async Task SafeReportUpdateFailedAsync(Hooks.HookContext ctx, Exception error)
{
if (_reportType == 2 && _mainRecordId <= 0 && _upgradeRecordId <= 0) return;
try
{
await Reporter
Expand All @@ -1185,6 +1194,7 @@ await Reporter
/// <param name="ctx">The update context.</param>
private async Task SafeReportUpdateAppliedAsync(Hooks.HookContext ctx, int recordId)
{
if (_reportType == 2 && recordId <= 0) return;
try
{
await Reporter
Expand Down
2 changes: 2 additions & 0 deletions src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,7 @@ private async Task SafeReportUpdateAppliedAsync(Hooks.HookContext ctx)
try
{
var recordId = _configInfo?.UpdateVersions?.FirstOrDefault()?.RecordId ?? 0;
if (_reportType == 2 && recordId <= 0) return;
await Reporter
.ReportAsync(new Download.Reporting.UpdateReport(recordId,
(int)Download.Reporting.UpdateStatus.Success, _reportType)).ConfigureAwait(false);
Expand All @@ -276,6 +277,7 @@ private async Task SafeReportUpdateFailedAsync(Hooks.HookContext ctx, Exception
try
{
var recordId = _configInfo?.UpdateVersions?.FirstOrDefault()?.RecordId ?? 0;
if (_reportType == 2 && recordId <= 0) return;
await Reporter
.ReportAsync(new Download.Reporting.UpdateReport(recordId,
(int)Download.Reporting.UpdateStatus.Failure, _reportType)).ConfigureAwait(false);
Expand Down
86 changes: 86 additions & 0 deletions tests/CoreTest/Download/PushDownloadSourceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
using GeneralUpdate.Core.Configuration;
using GeneralUpdate.Core.Download;
using GeneralUpdate.Core.Download.Sources;
using System.Text.Json;

namespace CoreTest.Download;

public class PushDownloadSourceTests
{
[Theory]
[InlineData(1, 1, 123)]
[InlineData(2, 2, 456)]
public async Task MapsFlatServerPacketAndBuildsPlan(int appType, int packageType, int recordId)
{
var json = $$"""
{"Name":"pkg","Url":"https://example.test/pkg.zip","Version":"2.0.0",
"Hash":"abc","AppType":{{appType}},"RecordId":{{recordId}},"PackageType":{{packageType}},
"Size":42,"IsForcibly":true,"IsFreeze":false,"ProductId":"p"}
""";
var result = await new PushDownloadSource(json).ListAsync();
var asset = Assert.Single(result.Assets);
Assert.Equal(recordId, asset.RecordId);
Assert.Equal(appType, asset.AppType);
Assert.Equal(packageType, asset.PackageType);
Assert.Equal(42, asset.Size);
Assert.Equal("abc", asset.SHA256);
Assert.True(asset.IsForcibly);
Assert.Equal(appType == 1, result.HasMainUpdate);
Assert.Equal(appType == 2, result.HasUpgradeUpdate);
Assert.Single(DownloadPlanBuilder.Build(result.Assets, "1.0.0", "1.0.0").Assets);
}

[Fact]
public async Task OldPacketWithoutRecordIdCanStillBeDownloaded()
{
var source = new PushDownloadSource("""{"Url":"https://example.test/pkg","Version":"2.0.0","AppType":1}""");
var asset = Assert.Single((await source.ListAsync()).Assets);
Assert.Equal(0, asset.RecordId);
Assert.Equal(1, asset.AppType);
}

[Fact]
public async Task ZipSuffixIsNormalizedForDownloadAndApply()
{
var source = new PushDownloadSource("""{"Name":"pkg.ZIP","Url":"https://example.test/pkg","Version":"2.0.0","AppType":1}""");
Assert.Equal("pkg", Assert.Single((await source.ListAsync()).Assets).Name);
}

[Fact]
public void FullOnlyPlansSelectLatestPackageForEachAppType()
{
var assets = new[]
{
new GeneralUpdate.Core.Download.Models.DownloadAsset("c1", "c1", 1, null, "2.0.0", PackageType: 2, AppType: 1),
new GeneralUpdate.Core.Download.Models.DownloadAsset("c2", "c2", 1, null, "3.0.0", PackageType: 2, AppType: 1),
new GeneralUpdate.Core.Download.Models.DownloadAsset("u", "u", 1, null, "2.0.0", PackageType: 2, AppType: 2)
};
var plan = DownloadPlanBuilder.Build(assets, "1.0.0", "1.0.0");
Assert.Equal(2, plan.Assets.Count);
Assert.Contains(plan.Assets, a => a.Name == "c2");
Assert.Contains(plan.Assets, a => a.Name == "u");
}

[Theory]
[InlineData("""{"Url":"x","Version":"2.0.0"}""")]
[InlineData("""{"Url":"x","Version":"2.0.0","AppType":3}""")]
[InlineData("""{"Version":"2.0.0","AppType":1}""")]
[InlineData("""{"Url":"x","AppType":1}""")]
[InlineData("""{"Url":"x","Version":"2.0.0","AppType":1,"RecordId":-1}""")]
[InlineData("""{"Url":"x","Version":"2.0.0","AppType":1,"PackageType":3}""")]
[InlineData("""{"Name":"../pkg","Url":"x","Version":"2.0.0","AppType":1}""")]
[InlineData("""{"Name":"..\\pkg","Url":"x","Version":"2.0.0","AppType":1}""")]
[InlineData("""{"Name":".zip","Url":"x","Version":"2.0.0","AppType":1}""")]
[InlineData("null")]
public void InvalidPacketsAreRejected(string json) =>
Assert.Throws<JsonException>(() => new PushDownloadSource(json));

[Fact]
public async Task CancellationIsHonoured()
{
var source = new PushDownloadSource("""{"Url":"x","Version":"2.0.0","AppType":1}""");
using var cts = new CancellationTokenSource();
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => source.ListAsync(cts.Token));
}
}
Loading
Loading