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
2 changes: 2 additions & 0 deletions docs/core-execution-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 进程的执行流程
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,11 @@ public async Task<DownloadResult> 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
};
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ public async Task<DownloadResult> 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
};
}
}
}
10 changes: 9 additions & 1 deletion src/GeneralUpdate.Core/Download/Models/DownloadProgress.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using GeneralUpdate.Core.Download.Reporting;

namespace GeneralUpdate.Core.Download.Models;

Expand All @@ -23,4 +24,11 @@ public record DownloadResult(
int RetryCount,
bool Success,
string? ErrorMessage
);
)
{
/// <summary>The original local exception, when available. Never sent to the server.</summary>
public Exception? Error { get; init; }

/// <summary>The known failure category; null when the origin is unknown.</summary>
public FailureCategory? FailureCategory { get; init; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,10 @@ public async Task<DownloadReport> 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;
}
Expand Down Expand Up @@ -254,7 +257,11 @@ public async Task<DownloadReport> 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;
Expand Down
51 changes: 50 additions & 1 deletion src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
/// </remarks>
public record UpdateReport(int RecordId, int Status = 1, int Type = 1);
public record UpdateReport(int RecordId, int Status = 1, int Type = 1)
{
/// <summary>Optional failure category, matching the server's diagnostic contract.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public FailureCategory? Category { get; init; }

/// <summary>Optional name of the operation that failed.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Phase { get; init; }

/// <summary>Optional stable, non-sensitive diagnostic code.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? ErrorCode { get; init; }

/// <summary>Optional sanitized diagnostic message.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Message { get; init; }
}

/// <summary>Failure categories understood by the reporting service.</summary>
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."
};
}
}

/// <summary>
/// An HTTP POST-based update status reporter that serializes <see cref="UpdateReport"/> to JSON
Expand Down
6 changes: 6 additions & 0 deletions src/GeneralUpdate.Core/Event/ExceptionEventArgs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,10 @@ public class ExceptionEventArgs(Exception? exception = null, string? message = n
/// </summary>
/// <value>May be <c>null</c> if no custom message was provided.</value>
public string Message { get; private set; } = message;

/// <summary>The affected record, when the failure can be associated with a package.</summary>
public int? RecordId { get; init; }

/// <summary>The known failure category; null when the operation is not identifiable.</summary>
public Download.Reporting.FailureCategory? Category { get; init; }
}
16 changes: 15 additions & 1 deletion src/GeneralUpdate.Core/Pipeline/PipelineBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/GeneralUpdate.Core/Pipeline/PipelineContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ namespace GeneralUpdate.Core.Pipeline;
public class PipelineContext
{
private ConcurrentDictionary<string, object?> _context = new();
internal Download.Reporting.FailureCategory? FailureCategory { get; set; }

/// <summary>
/// Retrieves a strongly-typed value associated with the specified key from the context.
Expand Down
59 changes: 48 additions & 11 deletions src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -54,6 +55,8 @@ public abstract class AbstractStrategy : IStrategy

/// <summary>Tracks whether at least one version was applied successfully in the current batch.</summary>
private bool _appliedAnyVersion;
private int? _failureRecordId;
private FailureCategory? _failureCategory;

/// <summary>
/// Global configuration information containing parameters such as update package path, temporary directory, report URL, and version list.
Expand Down Expand Up @@ -104,6 +107,9 @@ public abstract class AbstractStrategy : IStrategy
/// </summary>
public bool AllPackagesSucceeded { get; private set; }

/// <summary>Whether this execution produced a per-record package failure report.</summary>
public bool HasReportedPackageFailures { get; private set; }

/// <summary>
/// Starts the main application. Virtual method, overridden by subclasses to provide platform-specific application launch implementations.
/// </summary>
Expand Down Expand Up @@ -160,8 +166,10 @@ public virtual async Task ExecuteAsync()
try
{
AllPackagesSucceeded = true;
HasReportedPackageFailures = false;
_appliedAnyVersion = false;
var recordStatuses = new Dictionary<int, int>();
var recordStatuses = new Dictionary<int, UpdateReport>();
var rollbackFailures = new HashSet<int>();
patchRoot = StorageManager.GetTempDirectory(Patchs);

// Track the highest version already applied via full-package fallback,
Expand All @@ -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
Expand All @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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);
Comment on lines +315 to +317
}
catch (Exception ex)
{
Expand Down Expand Up @@ -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
});
}

/// <summary>
Expand Down Expand Up @@ -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.
/// </summary>
private void TryRollback()
private bool TryRollback(int recordId)
{
try
{
Expand All @@ -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;
}
}

Expand Down
Loading