diff --git a/docs/core-execution-flow.md b/docs/core-execution-flow.md
index 01e39fbf..c7d21660 100644
--- a/docs/core-execution-flow.md
+++ b/docs/core-execution-flow.md
@@ -247,8 +247,8 @@ 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 进程"]
@@ -256,7 +256,7 @@ flowchart TB
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
```
@@ -387,7 +387,7 @@ if (downloadReport.FailedCount > 0)
┌─────────────────────────────────────────────────────────────────┐
│ MainOnly │
│ │
-│ SendProcessIpc() │
+│ SendProcessIpcAsync() │
│ ↓ │
│ 写 AES 加密 IPC 文件到 %TEMP%/GeneralUpdate/ipc/process_info.enc│
│ ↓ │
@@ -401,7 +401,7 @@ if (downloadReport.FailedCount > 0)
│ │
│ ApplyUpgradePackagesAsync() ─── 先升级自身 │
│ ↓ 失败则中止 │
-│ SendProcessIpc() ─── 再写 IPC │
+│ SendProcessIpcAsync() ─── 再写 IPC │
│ ↓ │
│ LaunchUpgradeProcessAsync() ─── 最后拉起 Upgrade 进程 │
└─────────────────────────────────────────────────────────────────┘
@@ -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 进程的执行流程
@@ -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 |
diff --git a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
index 7a2029db..4a81f1f6 100644
--- a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
+++ b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
@@ -59,10 +59,15 @@ public enum UpdateStatus { Updating = 1, Success = 2, Failure = 3 }
///
/// The record ID returned from version validation, used to identify this update record.
/// The update status code: 1 = Updating, 2 = Success, 3 = Failure. Defaults to 1 (Updating).
-/// The update type: 1 = Upgrade, 2 = Push. Defaults to 1 (Upgrade).
+/// The record source: 1 = polled upgrade record, 2 = push record. This is not the package AppType. Defaults to 1.
///
/// 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.
///
public record UpdateReport(int RecordId, int Status = 1, int Type = 1);
diff --git a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs
index bf60a66f..5a837937 100644
--- a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs
+++ b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
@@ -131,7 +132,7 @@ public abstract class AbstractStrategy : IStrategy
/// - Execute Pipeline: Calls PipelineBuilder.Build() to execute all registered middleware
/// in FIFO order.
/// - Report Status: Reports the current version's update result (success or failure) to the server
- /// via .
+ /// via after the batch completes.
/// - Clean Up Resources: Calls DeleteVersionZip to remove the processed archive file for the current version.
///
///
@@ -160,7 +161,7 @@ public virtual async Task ExecuteAsync()
{
AllPackagesSucceeded = true;
_appliedAnyVersion = false;
- var status = ReportType.None;
+ var recordStatuses = new Dictionary();
patchRoot = StorageManager.GetTempDirectory(Patchs);
// Track the highest version already applied via full-package fallback,
@@ -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
@@ -268,7 +272,9 @@ 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.
@@ -276,6 +282,18 @@ public virtual async Task ExecuteAsync()
}
}
+ foreach (var record in recordStatuses)
+ {
+ try
+ {
+ await Reporter.ReportAsync(new UpdateReport(record.Key, record.Value, _configinfo.ReportType)).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ GeneralTracer.Warn($"Report package result failed: {ex.Message}");
+ }
+ }
+
TryCleanTempPath();
await OnExecuteCompleteAsync();
}
diff --git a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs
index 7d3c87ea..e8fe5da6 100644
--- a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs
+++ b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs
@@ -51,7 +51,7 @@ namespace GeneralUpdate.Core.Strategy;
/// 8. Upgrade Application: Calls ApplyUpgradePackagesAsync to apply incremental/full update packages in place through the OS strategy pipeline.
///
///
-/// 9. IPC Communication: Serializes main program update information as JSON via SendProcessIpc and sends it to the upgrade process through encrypted IPC.
+/// 9. IPC Communication: Serializes main program update information as JSON via SendProcessIpcAsync and sends it to the upgrade process through encrypted IPC.
///
///
/// 10. Launch Upgrade Process: Delegates to the OS strategy via LaunchUpgradeProcessAsync to start the upgrade executable.
@@ -73,6 +73,7 @@ public class ClientStrategy : IStrategy
private Func? _customDownloadPipelineFactory;
private int _mainRecordId;
private int _upgradeRecordId;
+ private int? _reportTypeOverride;
private int _reportType = 1; // 1=Upgrade(active poll), 2=Push(SignalR push)
///
@@ -84,7 +85,7 @@ public class ClientStrategy : IStrategy
///
/// After completes, true indicates that client packages were
- /// staged via and the upgrade process should be launched to apply them.
+ /// staged via and the upgrade process should be launched to apply them.
///
public bool HasPreparedClientUpdate { get; private set; }
@@ -132,6 +133,12 @@ private enum UpdateScenario
///
public Download.Abstractions.IDownloadSource? DownloadSource { get; set; }
+ ///
+ /// Optional IPC provider for handing prepared client packages to the upgrade process.
+ /// When unset, the encrypted file provider is used.
+ ///
+ public IProcessContractProvider? ProcessContractProvider { get; set; }
+
///
/// Initializes a new instance of the class.
///
@@ -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.
///
- public void SetReportType(int reportType) => _reportType = reportType;
+ public void SetReportType(int reportType)
+ {
+ _reportTypeOverride = _reportType = reportType;
+ if (_configInfo != null) _configInfo.ReportType = reportType;
+ }
///
/// Sets a custom download retry policy. Registered and injected by the bootstrap via .DownloadPolicy<T>().
@@ -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)
{
@@ -387,7 +400,7 @@ private async Task ExecuteWorkflowAsync()
/// Step 9 - Scenario Dispatch: Executes different operations based on the determined scenario:
///
/// - UpgradeOnly: Calls to apply upgrade packages in place.
- /// - MainOnly: Calls to send main program update information,
+ ///
- MainOnly: Calls to send main program update information,
/// then calls to start the upgrade process.
/// - Both: Applies upgrade packages first, then sends main program information and starts the upgrade process.
///
@@ -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);
@@ -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);
@@ -751,7 +763,7 @@ private async Task ApplyUpgradePackagesAsync(List upgradeVersions)
/// After the upgrade process (Bowl) receives this information, it will perform the actual installation and replacement operations
/// based on the ProcessContract.
///
- private void SendProcessIpc(List clientVersions)
+ private async Task SendProcessIpcAsync(List clientVersions)
{
var processInfo = ConfigurationMapper.MapToProcessContract(
_configInfo!, clientVersions,
@@ -762,7 +774,7 @@ private void SendProcessIpc(List 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.");
}
@@ -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)
@@ -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)
@@ -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);
}
catch (Exception ex)
diff --git a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs
index eb2124b2..e84e37d5 100644
--- a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs
+++ b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs
@@ -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)
///
@@ -68,7 +69,11 @@ public class UpdateStrategy : IStrategy
/// report type it used, so the server can distinguish push-triggered updates from active polls.
///
/// 1 = Upgrade (active poll), 2 = Push (SignalR push). Default is 1.
- public void SetReportType(int reportType) => _reportType = reportType;
+ public void SetReportType(int reportType)
+ {
+ _reportTypeOverride = _reportType = reportType;
+ if (_configInfo != null) _configInfo.ReportType = reportType;
+ }
///
/// Initializes the upgrade-side strategy. Receives the global configuration information passed from the client
@@ -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)
{
diff --git a/tests/CoreTest/Strategy/ReportRoutingTests.cs b/tests/CoreTest/Strategy/ReportRoutingTests.cs
new file mode 100644
index 00000000..caa89426
--- /dev/null
+++ b/tests/CoreTest/Strategy/ReportRoutingTests.cs
@@ -0,0 +1,188 @@
+using System.Text;
+using System.Text.Json;
+using GeneralUpdate.Core.Configuration;
+using GeneralUpdate.Core.Download.Abstractions;
+using GeneralUpdate.Core.Download.Models;
+using GeneralUpdate.Core.Download.Reporting;
+using GeneralUpdate.Core.FileSystem;
+using GeneralUpdate.Core.Ipc;
+using GeneralUpdate.Core.JsonContext;
+using GeneralUpdate.Core.Pipeline;
+using GeneralUpdate.Core.Strategy;
+using Moq;
+using CoreTest.Shared;
+
+namespace CoreTest.Strategy;
+
+[Collection("NonParallel_EventManager")]
+public class ReportRoutingTests : IDisposable
+{
+ private readonly string _directory = Path.Combine(Path.GetTempPath(), $"GU_Reports_{Guid.NewGuid():N}");
+ private readonly IBlackMatcher? _blackMatcher = StorageManager.BlackMatcher;
+
+ public ReportRoutingTests() => Directory.CreateDirectory(_directory);
+
+ [Theory]
+ [InlineData(1, false, true)]
+ [InlineData(2, false, true)]
+ [InlineData(1, true, false)]
+ [InlineData(2, true, false)]
+ [InlineData(1, true, true)]
+ [InlineData(2, true, true)]
+ public async Task ClientAndUpdater_RouteReportsAndDoNotMarkStagingSuccessful(int reportType, bool main, bool upgrade)
+ {
+ var assets = new List();
+ if (main) assets.Add(Asset("main", 101, AppType.Client));
+ if (upgrade) assets.Add(Asset("upgrade", 202, AppType.Upgrade));
+ var source = new Mock();
+ source.Setup(s => s.ListAsync(It.IsAny()))
+ .ReturnsAsync(new DownloadSourceResult { Assets = assets });
+ var orchestrator = new Mock();
+ orchestrator.Setup(o => o.ExecuteAsync(It.IsAny(), It.IsAny(), It.IsAny(),
+ It.IsAny>(), It.IsAny()))
+ .ReturnsAsync((DownloadPlan plan, string _, int _, IProgress? _, CancellationToken _) =>
+ new DownloadReport(Array.Empty(), 0, TimeSpan.Zero, plan.Assets.Count, 0));
+ var reporter = new RecordingReporter();
+ var platform = new TestPlatform();
+ var ipc = new EncryptedFileProcessContractProvider(Path.Combine(_directory, "ipc"));
+ var client = new ClientStrategy
+ {
+ DownloadSource = source.Object, Reporter = reporter, LaunchAfterPrepare = false, ProcessContractProvider = ipc
+ };
+ client.SetOrchestrator(orchestrator.Object);
+ client.SetOsStrategy(platform);
+ client.SetReportType(reportType);
+ var context = NewContext();
+ client.Create(context);
+
+ await client.ExecuteAsync();
+
+ Assert.All(reporter.Reports, r => Assert.Equal(reportType, r.Type));
+ if (upgrade)
+ Assert.Contains(reporter.Reports, r => r.RecordId == 202 && r.Status == (int)UpdateStatus.Success);
+ if (!main)
+ {
+ Assert.All(reporter.Reports, r => Assert.Equal(202, r.RecordId));
+ Assert.False(client.HasPreparedClientUpdate);
+ return;
+ }
+
+ Assert.True(client.HasPreparedClientUpdate);
+ Assert.DoesNotContain(reporter.Reports, r => r.RecordId == 101 && r.Status == (int)UpdateStatus.Success);
+ var contract = await ipc.ReceiveAsync();
+ Assert.NotNull(contract);
+ var serialized = JsonSerializer.Deserialize(context.ProcessContract, ProcessContractJsonContext.Default.ProcessContract)!;
+ Assert.Equal(reportType, serialized.ReportType);
+ Assert.Equal(reportType, contract.ReportType);
+ var updaterContext = NewContext();
+ updaterContext.UpdateVersions = contract.UpdateVersions;
+ updaterContext.ReportType = contract.ReportType;
+ updaterContext.LaunchClientAfterUpdate = false;
+ var updater = new UpdateStrategy { Reporter = reporter };
+ updater.SetOsStrategy(new TestPlatform());
+ updater.Create(updaterContext);
+ await updater.ExecuteAsync();
+ Assert.Equal((int)UpdateStatus.Success, reporter.Reports.Last(r => r.RecordId == 101).Status);
+ Assert.All(reporter.Reports, r => Assert.Equal(reportType, r.Type));
+ }
+
+ [Theory]
+ [InlineData(1, (int)AppType.Upgrade)]
+ [InlineData(2, (int)AppType.Client)]
+ public async Task PackagesSharingRecord_FailureCannotBeOverwrittenByLaterSuccess(int reportType, int appType)
+ {
+ var reporter = new RecordingReporter();
+ var platform = new TestPlatform { FailFirst = true, Reporter = reporter };
+ var context = NewContext();
+ context.ReportType = reportType;
+ context.UpdateVersions = new()
+ {
+ new() { Name = "first", Version = "2.0.0", AppType = appType, RecordId = 42 },
+ new() { Name = "second", Version = "3.0.0", AppType = appType, RecordId = 42 }
+ };
+ platform.Create(context);
+ await platform.ExecuteAsync();
+ var report = Assert.Single(reporter.Reports);
+ Assert.Equal(new UpdateReport(42, (int)UpdateStatus.Failure, reportType), report);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public async Task SetterBeforeOrAfterCreate_UpdatesPlatformAndRoleReports(bool beforeCreate)
+ {
+ var reporter = new RecordingReporter();
+ var context = NewContext();
+ context.LaunchClientAfterUpdate = false;
+ context.UpdateVersions = new() { new() { Name = "main", Version = "2.0.0", AppType = 1, RecordId = 42 } };
+ var updater = new UpdateStrategy { Reporter = reporter };
+ updater.SetOsStrategy(new TestPlatform());
+ if (beforeCreate) updater.SetReportType(2);
+ updater.Create(context);
+ if (!beforeCreate) updater.SetReportType(2);
+ await updater.ExecuteAsync();
+ Assert.NotEmpty(reporter.Reports);
+ Assert.All(reporter.Reports, r => Assert.Equal(2, r.Type));
+ }
+
+ [Fact]
+ public async Task Updater_LaunchFailureReportsFailureAfterAppliedSuccess()
+ {
+ var reporter = new RecordingReporter();
+ var context = NewContext();
+ context.UpdateVersions = new() { new() { Name = "main", Version = "2.0.0", AppType = 1, RecordId = 42 } };
+ var updater = new UpdateStrategy { Reporter = reporter };
+ updater.SetOsStrategy(new TestPlatform { FailLaunch = true });
+ updater.Create(context);
+ await updater.ExecuteAsync();
+ Assert.Equal((int)UpdateStatus.Success, reporter.Reports.First().Status);
+ Assert.Equal((int)UpdateStatus.Failure, reporter.Reports.Last().Status);
+ }
+
+ [Fact]
+ public void OldContractDefaultsToPolling()
+ {
+ var contract = JsonSerializer.Deserialize("{}", ProcessContractJsonContext.Default.ProcessContract);
+ Assert.Equal(1, contract!.ReportType);
+ }
+
+ private static DownloadAsset Asset(string name, int id, AppType type) =>
+ new(name, $"https://example.test/{name}", 1, null, "2.0.0", RecordId: id, AppType: (int)type);
+
+ private UpdateContext NewContext() => new()
+ {
+ InstallPath = _directory, TempPath = _directory, ClientVersion = "1.0.0",
+ UpgradeClientVersion = "1.0.0", MainAppName = "app", UpdateAppName = "updater",
+ AppSecretKey = FixtureValues.SingleKey, Encoding = Encoding.UTF8, Format = Format.Zip, BackupEnabled = false
+ };
+
+ private sealed class RecordingReporter : IUpdateReporter
+ {
+ public List Reports { get; } = new();
+ public Task ReportAsync(UpdateReport report, CancellationToken token = default)
+ {
+ Reports.Add(report);
+ return Task.CompletedTask;
+ }
+ }
+
+ private sealed class TestPlatform : AbstractStrategy
+ {
+ private int _calls;
+ public bool FailFirst { get; init; }
+ public bool FailLaunch { get; init; }
+ protected override PipelineBuilder BuildPipeline(PipelineContext context)
+ {
+ if (FailFirst && _calls++ == 0) throw new InvalidOperationException("test failure");
+ return new PipelineBuilder(context);
+ }
+ public override Task StartAppAsync() =>
+ FailLaunch ? Task.FromException(new InvalidOperationException("test launch failure")) : Task.CompletedTask;
+ }
+
+ public void Dispose()
+ {
+ StorageManager.BlackMatcher = _blackMatcher;
+ if (Directory.Exists(_directory)) Directory.Delete(_directory, true);
+ }
+}