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
14 changes: 8 additions & 6 deletions docs/core-execution-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,16 +247,16 @@ flowchart TB
UO2 -- Yes --> UO3["OnAfterUpdate 钩子\nReport UpdateApplied"]
UO2 -- No --> UO_FAIL["Report UpdateFailed"]

CS19 -- "MainOnly" --> MO1["SendProcessIpc()\n写加密 IPC 文件\nHasPreparedClientUpdate = true"]
MO1 --> MO2["OnAfterUpdate 钩子\nReport UpdateApplied"]
CS19 -- "MainOnly" --> MO1["SendProcessIpcAsync()\n写加密 IPC 文件\nHasPreparedClientUpdate = true"]
MO1 --> MO2["OnAfterUpdate 钩子\n等待升级进程应用"]
MO2 --> MO3["OnBeforeStartApp 钩子"]
MO3 --> MO4["LaunchUpgradeProcessAsync()\n拉起 Upgrade 进程"]

CS19 -- "Both" --> BOTH1["ApplyUpgradePackagesAsync()\n先原地升级自身"]
BOTH1 --> BOTH2{"AllPackagesSucceeded?"}
BOTH2 -- No --> BOTH_FAIL["中止!\n不发送 IPC\n不拉起 Upgrade\n防止循环更新"]
BOTH2 -- Yes --> BOTH3["OnAfterUpdate 钩子"]
BOTH3 --> BOTH4["SendProcessIpc()"]
BOTH3 --> BOTH4["SendProcessIpcAsync()"]
BOTH4 --> BOTH5["LaunchUpgradeProcessAsync()"]
end
```
Expand Down Expand Up @@ -387,7 +387,7 @@ if (downloadReport.FailedCount > 0)
┌─────────────────────────────────────────────────────────────────┐
│ MainOnly │
│ │
│ SendProcessIpc() │
│ SendProcessIpcAsync() │
│ ↓ │
│ 写 AES 加密 IPC 文件到 %TEMP%/GeneralUpdate/ipc/process_info.enc│
│ ↓ │
Expand All @@ -401,7 +401,7 @@ if (downloadReport.FailedCount > 0)
│ │
│ ApplyUpgradePackagesAsync() ─── 先升级自身 │
│ ↓ 失败则中止 │
│ SendProcessIpc() ─── 再写 IPC │
│ SendProcessIpcAsync() ─── 再写 IPC │
│ ↓ │
│ LaunchUpgradeProcessAsync() ─── 最后拉起 Upgrade 进程 │
└─────────────────────────────────────────────────────────────────┘
Expand Down Expand Up @@ -1116,6 +1116,8 @@ public static void EncryptToFile(byte[] plainBytes, string filePath, byte[] key,
| `LaunchClientAfterUpdate` | `_configInfo.LaunchClientAfterUpdate` | 更新后是否自动启动主程序 | UpdateStrategy |
| `ReportType` | 1 或 2 | 1=主动轮询 2=推送通知 | 上报区分 |

`ReportType` 选择服务器记录表,与包的 `AppType` 无关。下载阶段上报 Updating;主程序暂存后不报告成功,升级进程完成应用后才报告结果。同一批次中共享记录 ID 的包按记录汇总,任何失败优先;角色策略可能重复上报结果,启动抛错时也可能在成功后上报失败。成功仅表示文件应用完成,不代表重启后的健康检查通过。推送上报还需要调用方提供服务器分配的对应推送记录 ID,不能复用轮询记录 ID。

---

## 10. UpdateStrategy:Upgrade 进程的执行流程
Expand Down Expand Up @@ -1366,7 +1368,7 @@ private void TryRollback()
| 场景判定 | `Strategy/ClientStrategy.cs` | Scenario switch @L452-458 |
| 一次性下载 | `Strategy/ClientStrategy.cs` | `DownloadAndApplyAsync()` @L589-597 |
| 原地升级 Upgrade 包 | `Strategy/ClientStrategy.cs` | `ApplyUpgradePackagesAsync()` @L723-737 |
| IPC 写文件 | `Strategy/ClientStrategy.cs` | `SendProcessIpc()` @L751-765 |
| IPC 写文件 | `Strategy/ClientStrategy.cs` | `SendProcessIpcAsync()` |
| 拉起 Upgrade 进程 | `Strategy/ClientStrategy.cs` | `LaunchUpgradeProcessAsync()` @L777-789 |
| 下载计划构建 | `Download/DownloadPlanBuilder.cs` | `Build()` @L111 |
| Chain vs Full 阈值决策 | `Download/DownloadPlanBuilder.cs` | @L174-196 |
Expand Down
7 changes: 6 additions & 1 deletion src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,15 @@ public enum UpdateStatus { Updating = 1, Success = 2, Failure = 3 }
/// </summary>
/// <param name="RecordId">The record ID returned from version validation, used to identify this update record.</param>
/// <param name="Status">The update status code: 1 = Updating, 2 = Success, 3 = Failure. Defaults to 1 (Updating).</param>
/// <param name="Type">The update type: 1 = Upgrade, 2 = Push. Defaults to 1 (Upgrade).</param>
/// <param name="Type">The record source: 1 = polled upgrade record, 2 = push record. This is not the package AppType. Defaults to 1.</param>
/// <remarks>
/// This record is serialized to JSON using camelCase naming policy.
/// Example JSON: {"recordId": 123, "status": 1, "type": 1}
/// The client reports Updating while downloading and does not report Success for a staged main
/// application. After application, the platform reports one result per record for its package batch;
/// a failure in any package sharing that record takes precedence. The role strategy may report
/// the same result again, or report Failure if a later launch operation throws.
/// Success means package application completed; it does not attest that the restarted application is healthy.
/// </remarks>
public record UpdateReport(int RecordId, int Status = 1, int Type = 1);

Expand Down
24 changes: 21 additions & 3 deletions src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -131,7 +132,7 @@ public abstract class AbstractStrategy : IStrategy
/// <item><description><b>Execute Pipeline:</b> Calls <c>PipelineBuilder.Build()</c> to execute all registered middleware
/// in FIFO order.</description></item>
/// <item><description><b>Report Status:</b> Reports the current version's update result (success or failure) to the server
/// via <see cref="VersionService.Report"/>.</description></item>
/// via <see cref="Reporter"/> after the batch completes.</description></item>
/// <item><description><b>Clean Up Resources:</b> Calls <c>DeleteVersionZip</c> to remove the processed archive file for the current version.</description></item>
/// </list>
/// </para>
Expand Down Expand Up @@ -160,7 +161,7 @@ public virtual async Task ExecuteAsync()
{
AllPackagesSucceeded = true;
_appliedAnyVersion = false;
var status = ReportType.None;
var recordStatuses = new Dictionary<int, int>();
patchRoot = StorageManager.GetTempDirectory(Patchs);

// Track the highest version already applied via full-package fallback,
Expand All @@ -179,8 +180,11 @@ public virtual async Task ExecuteAsync()
&& versionSv <= fallbackEffectiveVersion)
{
GeneralTracer.Info($"AbstractStrategy.ExecuteAsync: skipping {version.Version} ({version.Name}) — already covered by fallback full package v{fallbackEffectiveVersion}.");
if (!recordStatuses.ContainsKey(version.RecordId))
recordStatuses.Add(version.RecordId, ReportType.Success);
continue;
}
var status = ReportType.None;
try
{
// Use a version-specific subdirectory under patchRoot so that
Expand Down Expand Up @@ -268,14 +272,28 @@ public virtual async Task ExecuteAsync()
}
finally
{
await Reporter.ReportAsync(new UpdateReport(version.RecordId, status, version.AppType ?? 1));
if (!recordStatuses.TryGetValue(version.RecordId, out var previousStatus)
|| previousStatus != ReportType.Failure)
recordStatuses[version.RecordId] = status;

// Delete only this version's zip file — other AppType packages
// in TempPath may still be needed by a downstream process.
DeleteVersionZip(version);
}
}

foreach (var record in recordStatuses)
{
try
{
await Reporter.ReportAsync(new UpdateReport(record.Key, record.Value, _configinfo.ReportType)).ConfigureAwait(false);
Comment on lines +285 to +289
}
catch (Exception ex)
{
GeneralTracer.Warn($"Report package result failed: {ex.Message}");
}
}

TryCleanTempPath();
await OnExecuteCompleteAsync();
}
Expand Down
36 changes: 24 additions & 12 deletions src/GeneralUpdate.Core/Strategy/ClientStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ namespace GeneralUpdate.Core.Strategy;
/// 8. <b>Upgrade Application</b>: Calls <c>ApplyUpgradePackagesAsync</c> to apply incremental/full update packages in place through the OS strategy pipeline.
/// </para>
/// <para>
/// 9. <b>IPC Communication</b>: Serializes main program update information as JSON via <c>SendProcessIpc</c> and sends it to the upgrade process through encrypted IPC.
/// 9. <b>IPC Communication</b>: Serializes main program update information as JSON via <c>SendProcessIpcAsync</c> and sends it to the upgrade process through encrypted IPC.
/// </para>
/// <para>
/// 10. <b>Launch Upgrade Process</b>: Delegates to the OS strategy via <c>LaunchUpgradeProcessAsync</c> to start the upgrade executable.</para>
Expand All @@ -73,6 +73,7 @@ public class ClientStrategy : IStrategy
private Func<string?, Download.Abstractions.IDownloadPipeline>? _customDownloadPipelineFactory;
private int _mainRecordId;
private int _upgradeRecordId;
private int? _reportTypeOverride;
private int _reportType = 1; // 1=Upgrade(active poll), 2=Push(SignalR push)

/// <summary>
Expand All @@ -84,7 +85,7 @@ public class ClientStrategy : IStrategy

/// <summary>
/// After <see cref="ExecuteAsync"/> completes, <c>true</c> indicates that client packages were
/// staged via <see cref="SendProcessIpc"/> and the upgrade process should be launched to apply them.
/// staged via <see cref="SendProcessIpcAsync"/> and the upgrade process should be launched to apply them.
/// </summary>
public bool HasPreparedClientUpdate { get; private set; }

Expand Down Expand Up @@ -132,6 +133,12 @@ private enum UpdateScenario
/// </remarks>
public Download.Abstractions.IDownloadSource? DownloadSource { get; set; }

/// <summary>
/// Optional IPC provider for handing prepared client packages to the upgrade process.
/// When unset, the encrypted file provider is used.
/// </summary>
public IProcessContractProvider? ProcessContractProvider { get; set; }

/// <summary>
/// Initializes a new instance of the <see cref="ClientStrategy"/> class.
/// </summary>
Expand Down Expand Up @@ -183,7 +190,11 @@ public ClientStrategy(Download.Abstractions.IDownloadOrchestrator? orchestrator)
/// When a push notification triggers the update (via SignalR hub), the caller should set this to 2
/// so the server can distinguish push-triggered updates from active poll updates.
/// </remarks>
public void SetReportType(int reportType) => _reportType = reportType;
public void SetReportType(int reportType)
{
_reportTypeOverride = _reportType = reportType;
if (_configInfo != null) _configInfo.ReportType = reportType;
}

/// <summary>
/// Sets a custom download retry policy. Registered and injected by the bootstrap via <c>.DownloadPolicy&lt;T&gt;()</c>.
Expand Down Expand Up @@ -233,6 +244,8 @@ public ClientStrategy(Download.Abstractions.IDownloadOrchestrator? orchestrator)
public void Create(UpdateContext parameter)
{
_configInfo = parameter ?? throw new ArgumentNullException(nameof(parameter));
_reportType = _reportTypeOverride ?? parameter.ReportType;
parameter.ReportType = _reportType;
_osStrategy = ResolveOsStrategy();
if (_osStrategy is AbstractStrategy abs)
{
Expand Down Expand Up @@ -387,7 +400,7 @@ private async Task ExecuteWorkflowAsync()
/// <b>Step 9 - Scenario Dispatch</b>: Executes different operations based on the determined scenario:
/// <list type="bullet">
/// <item><description><c>UpgradeOnly</c>: Calls <see cref="ApplyUpgradePackagesAsync"/> to apply upgrade packages in place.</description></item>
/// <item><description><c>MainOnly</c>: Calls <see cref="SendProcessIpc"/> to send main program update information,
/// <item><description><c>MainOnly</c>: Calls <see cref="SendProcessIpcAsync"/> to send main program update information,
/// then calls <see cref="LaunchUpgradeProcessAsync"/> to start the upgrade process.</description></item>
/// <item><description><c>Both</c>: Applies upgrade packages first, then sends main program information and starts the upgrade process.</description></item>
/// </list>
Expand Down Expand Up @@ -664,9 +677,8 @@ async Task DownloadAndApplyAsync(Download.Models.DownloadPlan plan, UpdateScenar
break;

case UpdateScenario.MainOnly:
SendProcessIpc(cVersions);
await SendProcessIpcAsync(cVersions).ConfigureAwait(false);
await SafeOnAfterUpdateAsync(hooksCtx).ConfigureAwait(false);
await SafeReportUpdateAppliedAsync(hooksCtx, _mainRecordId).ConfigureAwait(false);
if (LaunchAfterPrepare)
{
await SafeOnBeforeStartAppAsync(hooksCtx).ConfigureAwait(false);
Expand Down Expand Up @@ -694,7 +706,7 @@ async Task DownloadAndApplyAsync(Download.Models.DownloadPlan plan, UpdateScenar

await SafeOnAfterUpdateAsync(hooksCtx).ConfigureAwait(false);
await SafeReportUpdateAppliedAsync(hooksCtx, _upgradeRecordId).ConfigureAwait(false);
SendProcessIpc(cVersions);
await SendProcessIpcAsync(cVersions).ConfigureAwait(false);
if (LaunchAfterPrepare)
{
await SafeOnBeforeStartAppAsync(hooksCtx).ConfigureAwait(false);
Expand Down Expand Up @@ -751,7 +763,7 @@ private async Task ApplyUpgradePackagesAsync(List<VersionEntry> upgradeVersions)
/// <para>After the upgrade process (Bowl) receives this information, it will perform the actual installation and replacement operations
/// based on the <c>ProcessContract</c>.</para>
/// </remarks>
private void SendProcessIpc(List<VersionEntry> clientVersions)
private async Task SendProcessIpcAsync(List<VersionEntry> clientVersions)
{
var processInfo = ConfigurationMapper.MapToProcessContract(
_configInfo!, clientVersions,
Expand All @@ -762,7 +774,7 @@ private void SendProcessIpc(List<VersionEntry> clientVersions)

_configInfo.ProcessContract = JsonSerializer.Serialize(processInfo,
ProcessContractJsonContext.Default.ProcessContract);
new EncryptedFileProcessContractProvider().Send(processInfo);
await (ProcessContractProvider ?? new EncryptedFileProcessContractProvider()).SendAsync(processInfo).ConfigureAwait(false);
HasPreparedClientUpdate = true;
GeneralTracer.Info("ClientStrategy: ProcessContract sent with MainApp versions only.");
}
Expand Down Expand Up @@ -1121,7 +1133,7 @@ private async Task SafeReportUpdateStartedAsync(Hooks.HookContext ctx)
try
{
await Reporter
.ReportAsync(new Download.Reporting.UpdateReport(_mainRecordId,
.ReportAsync(new Download.Reporting.UpdateReport(_mainRecordId != 0 ? _mainRecordId : _upgradeRecordId,
(int)Download.Reporting.UpdateStatus.Updating, _reportType)).ConfigureAwait(false);
}
catch (Exception ex)
Expand All @@ -1139,7 +1151,7 @@ private async Task SafeReportDownloadCompletedAsync(Hooks.HookContext ctx)
try
{
await Reporter
.ReportAsync(new Download.Reporting.UpdateReport(_mainRecordId,
.ReportAsync(new Download.Reporting.UpdateReport(_mainRecordId != 0 ? _mainRecordId : _upgradeRecordId,
(int)Download.Reporting.UpdateStatus.Updating, _reportType)).ConfigureAwait(false);
}
catch (Exception ex)
Expand All @@ -1158,7 +1170,7 @@ private async Task SafeReportUpdateFailedAsync(Hooks.HookContext ctx, Exception
try
{
await Reporter
.ReportAsync(new Download.Reporting.UpdateReport(_mainRecordId,
.ReportAsync(new Download.Reporting.UpdateReport(_mainRecordId != 0 ? _mainRecordId : _upgradeRecordId,
(int)Download.Reporting.UpdateStatus.Failure, _reportType)).ConfigureAwait(false);
Comment on lines +1173 to 1174
}
catch (Exception ex)
Expand Down
9 changes: 8 additions & 1 deletion src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ public class UpdateStrategy : IStrategy
private UpdateContext? _configInfo;
private IStrategy? _osStrategy;
private IStrategy? _customOsStrategy;
private int? _reportTypeOverride;
private int _reportType = 1; // 1=Upgrade(active poll), 2=Push(SignalR push)

/// <summary>
Expand All @@ -68,7 +69,11 @@ public class UpdateStrategy : IStrategy
/// report type it used, so the server can distinguish push-triggered updates from active polls.
/// </summary>
/// <param name="reportType">1 = Upgrade (active poll), 2 = Push (SignalR push). Default is 1.</param>
public void SetReportType(int reportType) => _reportType = reportType;
public void SetReportType(int reportType)
{
_reportTypeOverride = _reportType = reportType;
if (_configInfo != null) _configInfo.ReportType = reportType;
}

/// <summary>
/// Initializes the upgrade-side strategy. Receives the global configuration information passed from the client
Expand All @@ -79,6 +84,8 @@ public class UpdateStrategy : IStrategy
public void Create(UpdateContext parameter)
{
_configInfo = parameter ?? throw new ArgumentNullException(nameof(parameter));
_reportType = _reportTypeOverride ?? parameter.ReportType;
parameter.ReportType = _reportType;
_osStrategy = ResolveOsStrategy();
if (_osStrategy is AbstractStrategy abs)
{
Expand Down
Loading
Loading