From 66a9403259235dd19c4602ed17a8c51c4615fba0 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Sun, 22 Nov 2026 23:45:06 +0800 Subject: [PATCH] Capture update failure stages per record Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/core-execution-flow.md | 2 + .../Executors/HttpDownloadExecutor.cs | 6 +- .../Download/Executors/OssDownloadExecutor.cs | 6 +- .../Download/Models/DownloadProgress.cs | 10 +- .../DefaultDownloadOrchestrator.cs | 11 +- .../Download/Reporting/IUpdateReporter.cs | 51 +++- .../Event/ExceptionEventArgs.cs | 6 + .../Pipeline/PipelineBuilder.cs | 16 +- .../Pipeline/PipelineContext.cs | 1 + .../Strategy/AbstractStrategy.cs | 59 +++- .../Strategy/ClientStrategy.cs | 30 ++- .../Strategy/UpdateStrategy.cs | 3 +- .../Strategy/FailureReportingTests.cs | 253 ++++++++++++++++++ 13 files changed, 432 insertions(+), 22 deletions(-) create mode 100644 tests/CoreTest/Strategy/FailureReportingTests.cs diff --git a/docs/core-execution-flow.md b/docs/core-execution-flow.md index c7d21660..6ede67b9 100644 --- a/docs/core-execution-flow.md +++ b/docs/core-execution-flow.md @@ -1118,6 +1118,8 @@ public static void EncryptToFile(byte[] plainBytes, string filePath, byte[] key, `ReportType` 选择服务器记录表,与包的 `AppType` 无关。下载阶段上报 Updating;主程序暂存后不报告成功,升级进程完成应用后才报告结果。同一批次中共享记录 ID 的包按记录汇总,任何失败优先;角色策略可能重复上报结果,启动抛错时也可能在成功后上报失败。成功仅表示文件应用完成,不代表重启后的健康检查通过。推送上报还需要调用方提供服务器分配的对应推送记录 ID,不能复用轮询记录 ID。 +下载及内置管道的失败报告可带 `category`、`phase`、`errorCode` 和 `message`。下载、校验、解压、补丁应用及回滚在明确的执行边界分类;自定义中间件或编排器没有提供阶段时不猜测。上报只包含固定的诊断代码和消息,不包含异常文本、URL、凭据或堆栈;本地事件保留可获得的原始异常和下载资源。回滚失败时先报告原始包失败,再对同一记录报告回滚失败;服务端是否保留两次历史取决于其实现。Chain 回退 Full 时报告所属 Chain 记录,现有 IPC 不携带独立 Full 记录 ID。取消、启动、兼容性及其他无可靠阶段来源的失败不附加阶段诊断;自检不在此流程中。 + --- ## 10. UpdateStrategy:Upgrade 进程的执行流程 diff --git a/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs b/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs index 8dbf5d0a..7056ee42 100644 --- a/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs +++ b/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs @@ -161,7 +161,11 @@ public async Task ExecuteAsync( { GeneralTracer.Error($"HttpDownloadExecutor: download failed '{asset.Url}' -> '{destPath}' after {sw.Elapsed}. {ex.Message}", ex); sw.Stop(); - return new DownloadResult(asset, destPath, existingBytes, sw.Elapsed, retries, false, ex.Message); + return new DownloadResult(asset, destPath, existingBytes, sw.Elapsed, retries, false, ex.Message) + { + Error = ex, + FailureCategory = Reporting.FailureCategory.Download + }; } } diff --git a/src/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs b/src/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs index c2985607..6770e389 100644 --- a/src/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs +++ b/src/GeneralUpdate.Core/Download/Executors/OssDownloadExecutor.cs @@ -99,7 +99,11 @@ public async Task ExecuteAsync( { GeneralTracer.Error($"OssDownloadExecutor: download failed '{asset.Url}' -> '{destPath}' after {sw.Elapsed}. {ex.Message}", ex); sw.Stop(); - return new DownloadResult(asset, destPath, 0, sw.Elapsed, 0, false, ex.Message); + return new DownloadResult(asset, destPath, 0, sw.Elapsed, 0, false, ex.Message) + { + Error = ex, + FailureCategory = Reporting.FailureCategory.Download + }; } } } diff --git a/src/GeneralUpdate.Core/Download/Models/DownloadProgress.cs b/src/GeneralUpdate.Core/Download/Models/DownloadProgress.cs index 1e15f8b0..c62a187a 100644 --- a/src/GeneralUpdate.Core/Download/Models/DownloadProgress.cs +++ b/src/GeneralUpdate.Core/Download/Models/DownloadProgress.cs @@ -1,4 +1,5 @@ using System; +using GeneralUpdate.Core.Download.Reporting; namespace GeneralUpdate.Core.Download.Models; @@ -23,4 +24,11 @@ public record DownloadResult( int RetryCount, bool Success, string? ErrorMessage -); +) +{ + /// The original local exception, when available. Never sent to the server. + public Exception? Error { get; init; } + + /// The known failure category; null when the origin is unknown. + public FailureCategory? FailureCategory { get; init; } +} diff --git a/src/GeneralUpdate.Core/Download/Orchestrators/DefaultDownloadOrchestrator.cs b/src/GeneralUpdate.Core/Download/Orchestrators/DefaultDownloadOrchestrator.cs index e33bc677..270b9961 100644 --- a/src/GeneralUpdate.Core/Download/Orchestrators/DefaultDownloadOrchestrator.cs +++ b/src/GeneralUpdate.Core/Download/Orchestrators/DefaultDownloadOrchestrator.cs @@ -216,7 +216,10 @@ public async Task ExecuteAsync( GeneralTracer.Warn($"DefaultDownloadOrchestrator: semaphore wait timed out (1 min) for '{asset.Name}'. Concurrency={effectiveConcurrency}, ActiveSlots={effectiveConcurrency - sem.CurrentCount}. Skipping asset."); lock (results) { - results.Add(new DownloadResult(asset, null, 0, TimeSpan.Zero, 0, false, "Semaphore wait timed out")); + results.Add(new DownloadResult(asset, null, 0, TimeSpan.Zero, 0, false, "Semaphore wait timed out") + { + FailureCategory = Reporting.FailureCategory.Timeout + }); } return; } @@ -254,7 +257,11 @@ public async Task ExecuteAsync( { return new DownloadResult(asset, destPath, downloadResult.DownloadedBytes, downloadResult.Duration, - downloadResult.RetryCount, false, $"SHA256 verification failed: {ex.Message}"); + downloadResult.RetryCount, false, $"SHA256 verification failed: {ex.Message}") + { + Error = ex, + FailureCategory = Reporting.FailureCategory.Verify + }; } return downloadResult; diff --git a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs index 4a81f1f6..1cda69cc 100644 --- a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs +++ b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs @@ -2,6 +2,7 @@ using System.Net.Http; using System.Text; using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using GeneralUpdate.Core.JsonContext; @@ -69,7 +70,55 @@ public enum UpdateStatus { Updating = 1, Success = 2, Failure = 3 } /// 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); +public record UpdateReport(int RecordId, int Status = 1, int Type = 1) +{ + /// Optional failure category, matching the server's diagnostic contract. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public FailureCategory? Category { get; init; } + + /// Optional name of the operation that failed. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Phase { get; init; } + + /// Optional stable, non-sensitive diagnostic code. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? ErrorCode { get; init; } + + /// Optional sanitized diagnostic message. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Message { get; init; } +} + +/// Failure categories understood by the reporting service. +public enum FailureCategory +{ + Download = 0, Verify = 1, Extract = 2, Apply = 3, Compat = 4, + Startup = 5, Rollback = 6, Timeout = 7, Unknown = 8 +} + +internal static class FailureReports +{ + internal static UpdateReport Create(int recordId, int type, FailureCategory? category) + { + var phase = category switch + { + FailureCategory.Download => "Download", + FailureCategory.Verify => "Verify", + FailureCategory.Extract => "Extract", + FailureCategory.Apply => "Apply", + FailureCategory.Rollback => "Rollback", + FailureCategory.Timeout => "Download", + _ => null + }; + return new UpdateReport(recordId, (int)UpdateStatus.Failure, type) + { + Category = category, + Phase = phase, + ErrorCode = category?.ToString().ToUpperInvariant(), + Message = phase == null ? null : phase + " failed." + }; + } +} /// /// An HTTP POST-based update status reporter that serializes to JSON diff --git a/src/GeneralUpdate.Core/Event/ExceptionEventArgs.cs b/src/GeneralUpdate.Core/Event/ExceptionEventArgs.cs index cc64f6fe..965456e8 100644 --- a/src/GeneralUpdate.Core/Event/ExceptionEventArgs.cs +++ b/src/GeneralUpdate.Core/Event/ExceptionEventArgs.cs @@ -31,4 +31,10 @@ public class ExceptionEventArgs(Exception? exception = null, string? message = n /// /// May be null if no custom message was provided. public string Message { get; private set; } = message; + + /// The affected record, when the failure can be associated with a package. + public int? RecordId { get; init; } + + /// The known failure category; null when the operation is not identifiable. + public Download.Reporting.FailureCategory? Category { get; init; } } diff --git a/src/GeneralUpdate.Core/Pipeline/PipelineBuilder.cs b/src/GeneralUpdate.Core/Pipeline/PipelineBuilder.cs index 4e4e077b..45b7f114 100644 --- a/src/GeneralUpdate.Core/Pipeline/PipelineBuilder.cs +++ b/src/GeneralUpdate.Core/Pipeline/PipelineBuilder.cs @@ -118,7 +118,21 @@ public async Task Build() { foreach (var middleware in _middlewareQueue) { - await middleware.InvokeAsync(context); + try + { + await middleware.InvokeAsync(context); + } + catch + { + context.FailureCategory = middleware switch + { + HashMiddleware => Download.Reporting.FailureCategory.Verify, + CompressMiddleware => Download.Reporting.FailureCategory.Extract, + PatchMiddleware => Download.Reporting.FailureCategory.Apply, + _ => null + }; + throw; + } } } } diff --git a/src/GeneralUpdate.Core/Pipeline/PipelineContext.cs b/src/GeneralUpdate.Core/Pipeline/PipelineContext.cs index 1a1f4803..d07c872b 100644 --- a/src/GeneralUpdate.Core/Pipeline/PipelineContext.cs +++ b/src/GeneralUpdate.Core/Pipeline/PipelineContext.cs @@ -71,6 +71,7 @@ namespace GeneralUpdate.Core.Pipeline; public class PipelineContext { private ConcurrentDictionary _context = new(); + internal Download.Reporting.FailureCategory? FailureCategory { get; set; } /// /// Retrieves a strongly-typed value associated with the specified key from the context. diff --git a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs index 5a837937..d7971bea 100644 --- a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs @@ -14,6 +14,7 @@ using GeneralUpdate.Core.Hooks; using IUpdateReporter = GeneralUpdate.Core.Download.Reporting.IUpdateReporter; using UpdateReport = GeneralUpdate.Core.Download.Reporting.UpdateReport; +using GeneralUpdate.Core.Download.Reporting; namespace GeneralUpdate.Core.Strategy { @@ -54,6 +55,8 @@ public abstract class AbstractStrategy : IStrategy /// Tracks whether at least one version was applied successfully in the current batch. private bool _appliedAnyVersion; + private int? _failureRecordId; + private FailureCategory? _failureCategory; /// /// Global configuration information containing parameters such as update package path, temporary directory, report URL, and version list. @@ -104,6 +107,9 @@ public abstract class AbstractStrategy : IStrategy /// public bool AllPackagesSucceeded { get; private set; } + /// Whether this execution produced a per-record package failure report. + public bool HasReportedPackageFailures { get; private set; } + /// /// Starts the main application. Virtual method, overridden by subclasses to provide platform-specific application launch implementations. /// @@ -160,8 +166,10 @@ public virtual async Task ExecuteAsync() try { AllPackagesSucceeded = true; + HasReportedPackageFailures = false; _appliedAnyVersion = false; - var recordStatuses = new Dictionary(); + var recordStatuses = new Dictionary(); + var rollbackFailures = new HashSet(); patchRoot = StorageManager.GetTempDirectory(Patchs); // Track the highest version already applied via full-package fallback, @@ -181,10 +189,12 @@ public virtual async Task ExecuteAsync() { 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); + recordStatuses.Add(version.RecordId, new UpdateReport(version.RecordId, ReportType.Success, _configinfo.ReportType)); continue; } var status = ReportType.None; + PipelineContext? context = null; + FailureCategory? failureCategory = null; try { // Use a version-specific subdirectory under patchRoot so that @@ -201,7 +211,7 @@ public virtual async Task ExecuteAsync() ? $"version_{(version.Version ?? rawName).GetHashCode():X8}" : safeDir; var patchPath = Path.Combine(patchRoot, versionName); - var context = CreatePipelineContext(version, patchPath); + context = CreatePipelineContext(version, patchPath); var pipelineBuilder = BuildPipeline(context); await pipelineBuilder.Build(); _appliedAnyVersion = true; @@ -212,6 +222,10 @@ public virtual async Task ExecuteAsync() && e is not OperationCanceledException) { GeneralTracer.Warn($"AbstractStrategy.ExecuteAsync: chain patch failed for {version.Version}, falling back to full package {version.FallbackFullName}. Error: {e.Message}"); + EventManager.Instance.Dispatch(this, new ExceptionEventArgs(e, e.Message) + { + RecordId = version.RecordId, Category = context?.FailureCategory + }); // Rebuild pipeline context with the fallback full zip. // CompressMiddleware will extract directly to SourcePath, @@ -251,30 +265,40 @@ public virtual async Task ExecuteAsync() // surface the exception, so the version is NOT recorded as upgraded. GeneralTracer.Error($"AbstractStrategy.ExecuteAsync: fallback full package also failed for {version.Version}. Error: {fallbackEx.Message}"); AllPackagesSucceeded = false; - HandleExecuteException(fallbackEx); status = ReportType.Failure; + failureCategory = fallbackContext.FailureCategory; + _failureRecordId = version.RecordId; + _failureCategory = failureCategory; + HandleExecuteException(fallbackEx); // Only rollback when NO version has succeeded yet in this batch. if (!_appliedAnyVersion) - TryRollback(); + if (!TryRollback(version.RecordId)) rollbackFailures.Add(version.RecordId); } } catch (Exception e) { status = ReportType.Failure; AllPackagesSucceeded = false; + failureCategory = context?.FailureCategory; + _failureRecordId = version.RecordId; + _failureCategory = failureCategory; HandleExecuteException(e); // Only rollback when NO version has succeeded yet in this batch. // If a previous version was already applied successfully, // rolling back would undo valid work and leave the app in // a downgraded state across version boundaries. if (!_appliedAnyVersion) - TryRollback(); + if (!TryRollback(version.RecordId)) rollbackFailures.Add(version.RecordId); } finally { + _failureRecordId = null; + _failureCategory = null; if (!recordStatuses.TryGetValue(version.RecordId, out var previousStatus) - || previousStatus != ReportType.Failure) - recordStatuses[version.RecordId] = status; + || previousStatus.Status != ReportType.Failure) + recordStatuses[version.RecordId] = status == ReportType.Failure + ? FailureReports.Create(version.RecordId, _configinfo.ReportType, failureCategory) + : new UpdateReport(version.RecordId, status, _configinfo.ReportType); // Delete only this version's zip file — other AppType packages // in TempPath may still be needed by a downstream process. @@ -284,9 +308,13 @@ public virtual async Task ExecuteAsync() foreach (var record in recordStatuses) { + if (record.Value.Status == ReportType.Failure) + HasReportedPackageFailures = true; try { - await Reporter.ReportAsync(new UpdateReport(record.Key, record.Value, _configinfo.ReportType)).ConfigureAwait(false); + await Reporter.ReportAsync(record.Value).ConfigureAwait(false); + if (rollbackFailures.Contains(record.Key)) + await Reporter.ReportAsync(FailureReports.Create(record.Key, _configinfo.ReportType, FailureCategory.Rollback)).ConfigureAwait(false); } catch (Exception ex) { @@ -421,7 +449,10 @@ protected virtual Task OnExecuteCompleteAsync() protected virtual void HandleExecuteException(Exception e) { GeneralTracer.Error($"Strategy execution exception.", e); - EventManager.Instance.Dispatch(this, new ExceptionEventArgs(e, e.Message)); + EventManager.Instance.Dispatch(this, new ExceptionEventArgs(e, e.Message) + { + RecordId = _failureRecordId, Category = _failureCategory + }); } /// @@ -525,7 +556,7 @@ private string ResolveUpdateDir() /// Tries the specific backup directory for this update first; /// falls back to the most recent backup if the specific one is unavailable. /// - private void TryRollback() + private bool TryRollback(int recordId) { try { @@ -548,10 +579,16 @@ private void TryRollback() { GeneralTracer.Warn("AbstractStrategy.TryRollback: no backup found, rollback skipped."); } + return true; } catch (Exception ex) { GeneralTracer.Error("AbstractStrategy.TryRollback: rollback failed.", ex); + EventManager.Instance.Dispatch(this, new ExceptionEventArgs(ex, ex.Message) + { + RecordId = recordId, Category = FailureCategory.Rollback + }); + return false; } } diff --git a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs index e8fe5da6..7bb11dbe 100644 --- a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs @@ -72,6 +72,7 @@ public class ClientStrategy : IStrategy private Download.Abstractions.IDownloadExecutor? _customDownloadExecutor; private Func? _customDownloadPipelineFactory; private int _mainRecordId; + private bool _downloadFailuresReported; private int _upgradeRecordId; private int? _reportTypeOverride; private int _reportType = 1; // 1=Upgrade(active poll), 2=Push(SignalR push) @@ -272,6 +273,7 @@ public async Task ExecuteAsync() if (_configInfo == null) throw new InvalidOperationException("ClientStrategy not configured."); HasPreparedClientUpdate = false; + _downloadFailuresReported = false; try { @@ -283,7 +285,8 @@ public async Task ExecuteAsync() { var errCtx = BuildUpdateContext(); await SafeOnUpdateErrorAsync(errCtx, ex).ConfigureAwait(false); - await SafeReportUpdateFailedAsync(errCtx, ex).ConfigureAwait(false); + if (!_downloadFailuresReported) + await SafeReportUpdateFailedAsync(errCtx, ex).ConfigureAwait(false); GeneralTracer.Error("ClientStrategy.ExecuteAsync failed.", ex); EventManager.Instance.Dispatch(this, new ExceptionEventArgs(ex, ex.Message)); } @@ -617,6 +620,25 @@ async Task DownloadAndApplyAsync(Download.Models.DownloadPlan plan, UpdateScenar if (downloadReport.FailedCount > 0) { + var reportedRecords = new HashSet(); + foreach (var result in downloadReport.Results.Where(r => !r.Success)) + { + var error = result.Error ?? new InvalidOperationException(result.ErrorMessage ?? "Download failed."); + EventManager.Instance.Dispatch(this, new Download.MultiDownloadErrorEventArgs(error, result.Asset)); + if (reportedRecords.Add(result.Asset.RecordId)) + { + try + { + await Reporter.ReportAsync(Download.Reporting.FailureReports.Create( + result.Asset.RecordId, _reportType, result.FailureCategory)).ConfigureAwait(false); + } + catch (Exception reportError) + { + GeneralTracer.Warn($"Report download failure failed: {reportError.Message}"); + } + } + } + _downloadFailuresReported = reportedRecords.Count > 0; var failDetails = string.Join(", ", downloadReport.Results.Where(r => !r.Success) .Select(r => $"{r.Asset.Name}: {r.ErrorMessage}")); @@ -670,7 +692,8 @@ async Task DownloadAndApplyAsync(Download.Models.DownloadPlan plan, UpdateScenar { var failEx = new InvalidOperationException("Upgrade packages failed to apply."); await SafeOnUpdateErrorAsync(hooksCtx, failEx).ConfigureAwait(false); - await SafeReportUpdateFailedAsync(hooksCtx, failEx).ConfigureAwait(false); + if (_osStrategy is not AbstractStrategy { HasReportedPackageFailures: true }) + await SafeReportUpdateFailedAsync(hooksCtx, failEx).ConfigureAwait(false); EventManager.Instance.Dispatch(this, new ExceptionEventArgs(failEx, failEx.Message)); GeneralTracer.Error("ClientStrategy: Upgrade-only update failed, client continues running."); } @@ -697,7 +720,8 @@ async Task DownloadAndApplyAsync(Download.Models.DownloadPlan plan, UpdateScenar { var failEx = new InvalidOperationException("Upgrade packages failed to apply."); await SafeOnUpdateErrorAsync(hooksCtx, failEx).ConfigureAwait(false); - await SafeReportUpdateFailedAsync(hooksCtx, failEx).ConfigureAwait(false); + if (_osStrategy is not AbstractStrategy { HasReportedPackageFailures: true }) + await SafeReportUpdateFailedAsync(hooksCtx, failEx).ConfigureAwait(false); EventManager.Instance.Dispatch(this, new ExceptionEventArgs(failEx, failEx.Message)); GeneralTracer.Error( "ClientStrategy: upgrade packages failed to apply, aborting MainApp update and upgrade launch."); diff --git a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs index e84e37d5..c359f587 100644 --- a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs @@ -153,7 +153,8 @@ public async Task ExecuteAsync() { var failEx = new InvalidOperationException("MainApp pipeline did not complete successfully."); await SafeOnUpdateErrorAsync(ctx, failEx).ConfigureAwait(false); - await SafeReportUpdateFailedAsync(ctx, failEx).ConfigureAwait(false); + if (_osStrategy is not AbstractStrategy { HasReportedPackageFailures: true }) + await SafeReportUpdateFailedAsync(ctx, failEx).ConfigureAwait(false); EventManager.Instance.Dispatch(this, new ExceptionEventArgs(failEx, failEx.Message)); return; } diff --git a/tests/CoreTest/Strategy/FailureReportingTests.cs b/tests/CoreTest/Strategy/FailureReportingTests.cs new file mode 100644 index 00000000..29fcc2cb --- /dev/null +++ b/tests/CoreTest/Strategy/FailureReportingTests.cs @@ -0,0 +1,253 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Download; +using GeneralUpdate.Core.Download.Abstractions; +using GeneralUpdate.Core.Download.Models; +using GeneralUpdate.Core.Download.Orchestrators; +using GeneralUpdate.Core.Download.Reporting; +using GeneralUpdate.Core.Event; +using GeneralUpdate.Core.FileSystem; +using GeneralUpdate.Core.JsonContext; +using GeneralUpdate.Core.Pipeline; +using GeneralUpdate.Core.Strategy; +using Moq; + +namespace CoreTest.Strategy; + +[Collection("NonParallel_EventManager")] +public class FailureReportingTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"GU_Failures_{Guid.NewGuid():N}"); + private readonly IBlackMatcher? _matcher = StorageManager.BlackMatcher; + + public FailureReportingTests() => Directory.CreateDirectory(_root); + + [Fact] + public async Task Client_DownloadAndVerificationFailures_ReportCorrectRecordsAndKeepOriginalErrors() + { + var networkError = new HttpRequestException("secret-token https://example.test/?password=secret"); + var handler = new CaptureHandler(networkError); + using var http = new HttpClient(handler); + var reporter = new HttpUpdateReporter(http, "https://report.test/Upgrade/Report"); + var assets = new[] + { + new DownloadAsset("network", "https://download.test/network", 1, null, "2.0.0", RecordId: 101, AppType: (int)AppType.Client), + new DownloadAsset("checksum", "https://download.test/checksum", 1, "wrong", "2.0.0", RecordId: 202, AppType: (int)AppType.Upgrade) + }; + var source = new Mock(); + source.Setup(s => s.ListAsync(It.IsAny())) + .ReturnsAsync(new DownloadSourceResult { Assets = assets }); + var client = new ClientStrategy { DownloadSource = source.Object, Reporter = reporter, LaunchAfterPrepare = false }; + client.SetOrchestrator(new DefaultDownloadOrchestrator(http, new DownloadOrchestratorOptions { VerifyChecksum = true })); + client.SetReportType(2); + client.Create(NewContext()); + var errors = new List(); + void OnError(object sender, MultiDownloadErrorEventArgs e) { if (ReferenceEquals(sender, client)) errors.Add(e); } + EventManager.Instance.AddListener(OnError); + try { await client.ExecuteAsync(); } + finally { EventManager.Instance.RemoveListener(OnError); } + + Assert.Equal(2, errors.Count); + Assert.Same(networkError, errors.Single(e => ((DownloadAsset)e.Version).RecordId == 101).Exception); + Assert.IsType(errors.Single(e => ((DownloadAsset)e.Version).RecordId == 202).Exception); + var failures = handler.Reports.Where(r => r.GetProperty("status").GetInt32() == 3).ToArray(); + Assert.Equal(2, failures.Length); + AssertReport(failures.Single(r => r.GetProperty("recordId").GetInt32() == 101), 101, 2, 0, "Download"); + AssertReport(failures.Single(r => r.GetProperty("recordId").GetInt32() == 202), 202, 2, 1, "Verify"); + Assert.DoesNotContain("secret", string.Join("", failures.Select(r => r.GetRawText())), StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("verify", FailureCategory.Verify)] + [InlineData("extract", FailureCategory.Extract)] + [InlineData("apply", FailureCategory.Apply)] + public async Task Updater_RealMiddlewareFailure_ReportsItsRecordAndStage(string stage, FailureCategory category) + { + var reporter = new RecordingReporter(); + var platform = new StagePlatform(stage); + var context = NewContext(); + context.ReportType = 2; + context.LaunchClientAfterUpdate = false; + context.UpdateVersions = new() { new() { Name = "package", Version = "2.0.0", RecordId = 303, AppType = (int)AppType.Client, Hash = "bad" } }; + await File.WriteAllTextAsync(Path.Combine(_root, "package.zip"), "not a zip"); + var updater = new UpdateStrategy { Reporter = reporter }; + updater.SetOsStrategy(platform); + updater.Create(context); + var errors = new List(); + void OnError(object sender, ExceptionEventArgs e) { if (ReferenceEquals(sender, platform)) errors.Add(e); } + EventManager.Instance.AddListener(OnError); + try { await updater.ExecuteAsync(); } + finally { EventManager.Instance.RemoveListener(OnError); } + var report = Assert.Single(reporter.Reports); + Assert.Equal(303, report.RecordId); + Assert.Equal(2, report.Type); + Assert.Equal(category, report.Category); + Assert.Equal(category.ToString(), report.Phase); + Assert.Equal((int)UpdateStatus.Failure, report.Status); + var error = Assert.Single(errors); + Assert.NotNull(error.Exception); + Assert.Equal(303, error.RecordId); + Assert.Equal(category, error.Category); + } + + [Fact] + public async Task RollbackFailure_ReportsOriginalFailureThenRollbackWithSameRecord() + { + var backup = Path.Combine(_root, "backup"); + Directory.CreateDirectory(backup); + Directory.CreateDirectory(Path.Combine(backup, "blocked")); + await File.WriteAllTextAsync(Path.Combine(_root, "blocked"), "prevents directory creation"); + var reporter = new RecordingReporter(); + var context = NewContext(); + context.BackupDirectory = backup; + context.ReportType = 2; + context.UpdateVersions = new() { new() { Name = "missing", Version = "2.0.0", RecordId = 404, Hash = "bad" } }; + var platform = new StagePlatform("verify") { Reporter = reporter }; + platform.Create(context); + var errors = new List(); + void OnError(object sender, ExceptionEventArgs e) { if (ReferenceEquals(sender, platform)) errors.Add(e); } + EventManager.Instance.AddListener(OnError); + try { await platform.ExecuteAsync(); } + finally { EventManager.Instance.RemoveListener(OnError); } + Assert.Equal(new FailureCategory?[] { FailureCategory.Verify, FailureCategory.Rollback }, reporter.Reports.Select(r => r.Category)); + Assert.All(reporter.Reports, r => { Assert.Equal(404, r.RecordId); Assert.Equal(2, r.Type); }); + Assert.Equal(new FailureCategory?[] { FailureCategory.Verify, FailureCategory.Rollback }, errors.Select(e => e.Category)); + Assert.All(errors, e => { Assert.Equal(404, e.RecordId); Assert.NotNull(e.Exception); }); + } + + [Fact] + public async Task FallbackFailure_ReportsFallbackStageForOriginalRecord() + { + var reporter = new RecordingReporter(); + var context = NewContext(); + context.ReportType = 2; + context.UpdateVersions = new() + { + new() { Name = "chain", Version = "2.0.0", RecordId = 505, Hash = "bad", + PackageType = (int)PackageType.Chain, FallbackFullName = "full" } + }; + await File.WriteAllTextAsync(Path.Combine(_root, "full.zip"), "not a zip"); + var platform = new FallbackPlatform { Reporter = reporter }; + platform.Create(context); + await platform.ExecuteAsync(); + var report = Assert.Single(reporter.Reports); + Assert.Equal(505, report.RecordId); + Assert.Equal(2, report.Type); + Assert.Equal(FailureCategory.Extract, report.Category); + } + + [Fact] + public async Task CustomMiddlewareFailure_IsNotGuessed() + { + var reporter = new RecordingReporter(); + var context = NewContext(); + context.UpdateVersions = new() { new() { Name = "custom", Version = "2.0.0", RecordId = 606 } }; + var platform = new CustomPlatform { Reporter = reporter }; + platform.Create(context); + await platform.ExecuteAsync(); + var report = Assert.Single(reporter.Reports); + Assert.Equal(606, report.RecordId); + Assert.Null(report.Category); + Assert.Null(report.Phase); + Assert.Null(report.ErrorCode); + Assert.Null(report.Message); + } + + [Fact] + public async Task HttpReporter_OldPayloadUnchangedAndOldDtoIgnoresOptionalFields() + { + var handler = new CaptureHandler(new HttpRequestException()); + using var http = new HttpClient(handler); + var reporter = new HttpUpdateReporter(http, "https://report.test/Upgrade/Report"); + await reporter.ReportAsync(new UpdateReport(17, 1, 2)); + await reporter.ReportAsync(new UpdateReport(17, 3, 2) { Category = FailureCategory.Extract, Phase = "Extract", ErrorCode = "EXTRACT", Message = "Extract failed." }); + Assert.Equal(3, handler.Reports[0].EnumerateObject().Count()); + var legacy = JsonSerializer.Deserialize(handler.Reports[1].GetRawText(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + Assert.Equal((17, 3, 2), (legacy!.RecordId, legacy.Status, legacy.Type)); + AssertReport(handler.Reports[1], 17, 2, 2, "Extract"); + var replay = JsonSerializer.Deserialize(handler.Reports[1].GetRawText(), UpdateReportJsonContext.Default.UpdateReport); + Assert.Equal(new UpdateReport(17, 3, 2) { Category = FailureCategory.Extract, Phase = "Extract", ErrorCode = "EXTRACT", Message = "Extract failed." }, replay); + } + + private static void AssertReport(JsonElement report, int id, int type, int category, string phase) + { + Assert.Equal(id, report.GetProperty("recordId").GetInt32()); + Assert.Equal(type, report.GetProperty("type").GetInt32()); + Assert.Equal(category, report.GetProperty("category").GetInt32()); + Assert.Equal(phase, report.GetProperty("phase").GetString()); + Assert.Equal(phase.ToUpperInvariant(), report.GetProperty("errorCode").GetString()); + } + + private UpdateContext NewContext() => new() + { + InstallPath = _root, TempPath = _root, ClientVersion = "1.0.0", UpgradeClientVersion = "1.0.0", + MainAppName = "app", UpdateAppName = "updater", Encoding = Encoding.UTF8, Format = Format.Zip, + BackupEnabled = false, VerifyChecksum = true + }; + + private sealed class StagePlatform(string stage) : AbstractStrategy + { + protected override PipelineBuilder BuildPipeline(PipelineContext context) => stage switch + { + "verify" => new PipelineBuilder(context).UseMiddleware(), + "extract" => new PipelineBuilder(context).UseMiddleware(), + _ => new PipelineBuilder(context).UseMiddleware() + }; + } + + private sealed class FallbackPlatform : AbstractStrategy + { + private int _calls; + protected override PipelineBuilder BuildPipeline(PipelineContext context) => _calls++ == 0 + ? new PipelineBuilder(context).UseMiddleware() + : new PipelineBuilder(context).UseMiddleware(); + } + + private sealed class CustomPlatform : AbstractStrategy + { + protected override PipelineBuilder BuildPipeline(PipelineContext context) => + new PipelineBuilder(context).UseMiddleware(); + } + + public sealed class CustomMiddleware : IMiddleware + { + public Task InvokeAsync(PipelineContext context) => Task.FromException(new IOException("custom failure")); + } + + 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 CaptureHandler(Exception failure) : HttpMessageHandler + { + public List Reports { get; } = new(); + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token) + { + if (request.RequestUri!.Host == "report.test") + { + using var doc = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(token)); + Reports.Add(doc.RootElement.Clone()); + return new HttpResponseMessage(HttpStatusCode.OK); + } + if (request.RequestUri.AbsolutePath.EndsWith("network", StringComparison.Ordinal)) throw failure; + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("incorrect contents") }; + } + } + + private sealed class LegacyReport + { + public int RecordId { get; set; } + public int Status { get; set; } + public int Type { get; set; } + } + + public void Dispose() + { + StorageManager.BlackMatcher = _matcher; + if (Directory.Exists(_root)) Directory.Delete(_root, true); + } +}