diff --git a/.github/workflows/ordered-report-aot.yml b/.github/workflows/ordered-report-aot.yml new file mode 100644 index 00000000..0e764436 --- /dev/null +++ b/.github/workflows/ordered-report-aot.yml @@ -0,0 +1,38 @@ +name: Ordered report Native AOT + +on: + pull_request: + workflow_dispatch: + +jobs: + publish-and-run: + strategy: + matrix: + include: + - os: windows-latest + rid: win-x64 + executable: ReportWorker.exe + - os: ubuntu-latest + rid: linux-x64 + executable: ReportWorker + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-dotnet@v5 + with: + dotnet-version: '10.0.x' + - name: Test outbox + run: >- + dotnet test tests/CoreTest/CoreTest.csproj -c Release + --filter "FullyQualifiedName~OrderedUpdateReporterTests|FullyQualifiedName~RealFallback_CoveredChainCannotOverwriteFailureOrReportDurableSuccess|FullyQualifiedName~Child_apply_failure_survives_restart_and_replays_exact_ordered_event_over_http|FullyQualifiedName~Child_process_requires_the_matching_attempt_contract" + - name: Publish Native AOT + run: dotnet publish tests/ReportWorker/ReportWorker.csproj -c Release -f net10.0 -r ${{ matrix.rid }} -p:PublishAot=true -p:TargetFrameworks=net10.0 -o aot-out + - name: Run native outbox + shell: pwsh + run: | + $exe = Join-Path $PWD "aot-out" "${{ matrix.executable }}" + $queue = Join-Path $env:RUNNER_TEMP "ordered-aot" + & $exe $queue success + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & $exe $queue success + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/.github/workflows/report-integration-regression.yml b/.github/workflows/report-integration-regression.yml new file mode 100644 index 00000000..87834e82 --- /dev/null +++ b/.github/workflows/report-integration-regression.yml @@ -0,0 +1,48 @@ +name: Report integration regression + +on: + push: + branches: [justerzhu-persistent-regression-integration] + workflow_dispatch: + +permissions: + contents: read + +jobs: + report-regression: + name: Report regression (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + env: + REPORT_INTEGRATION_MERGE_SHA: 057da130aab3251342d344e2b60a12dcc8be71ef + REPORT_ROUTING_SHA: 623a87ce5112af0dab4d23c457797d23cd419143 + FAILURE_STAGE_SHA: 66a9403259235dd19c4602ed17a8c51c4615fba0 + PERSISTENT_REPORT_SHA: ad77b50c5125a436ab4d4c8a894f6df7235d95b0 + steps: + - name: Checkout fixed integration history + uses: actions/checkout@v6 + with: + ref: ${{ github.sha }} + fetch-depth: 0 + + - name: Verify dependency commits + shell: bash + run: | + test "$(git rev-parse "${REPORT_INTEGRATION_MERGE_SHA}^1")" = "${FAILURE_STAGE_SHA}" + test "$(git rev-parse "${REPORT_INTEGRATION_MERGE_SHA}^2")" = "${PERSISTENT_REPORT_SHA}" + git merge-base --is-ancestor "${REPORT_ROUTING_SHA}" "${REPORT_INTEGRATION_MERGE_SHA}" + git merge-base --is-ancestor "${REPORT_INTEGRATION_MERGE_SHA}" HEAD + + - name: Setup .NET + uses: actions/setup-dotnet@v5 + with: + dotnet-version: '10.0.x' + + - name: Run cross-PR report regressions + run: >- + dotnet test tests/CoreTest/CoreTest.csproj + --configuration Release + --filter "FullyQualifiedName~PersistentUpdateReporterTests|FullyQualifiedName~FailureReportingTests|FullyQualifiedName~ReportRoutingTests" diff --git a/README.md b/README.md index 1422742e..3e838a5e 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,80 @@ Special thanks to the authors of the following open source projects for contribu | 🩺 `generalupdate-troubleshoot` | `/generalupdate-troubleshoot` | 50+ known issues diagnosis | +## Durable update reports (opt-in) + +The default `HttpUpdateReporter` remains best-effort. Hosts that need durable reporting +can create and register a `PersistentUpdateReporter`, and must replay it on every +application start (and periodically when connectivity returns): + +```csharp +var sender = new HttpUpdateReporter(httpClient, reportUrl); +var reporter = new PersistentUpdateReporter(queueDirectory, sender); +await reporter.ReplayAsync(cancellationToken); // handle and log failures; retry later +bootstrap.UpdateReporter(reporter); +``` + +Use the same writable, local, private queue directory and endpoint across restarts and +processes, and a separate directory for each endpoint/account. Configure authentication +and register the reporter again in each reporting process, including the upgrade process; +neither the URL nor credentials are stored in the queue. Queue +files contain record IDs and statuses and should be protected and retained by the host. +The host must arrange periodic retries and monitor disk usage, permissions and errors. +`ReportAsync` writes before sending and throws if persistence or delivery fails; +the built-in strategies catch and log reporter exceptions so the update continues. + +All statuses are queued to preserve their order, including success after failure. +Delivery stops at the first unconfirmed report: HTTP success alone is insufficient; +the response must also have `code: 200` and `body: true`. This is **at-least-once**, +not exactly-once: a crash or lost response after server acceptance can resend a report, +and the current server may count a repeated failure again. Safe deduplication requires +a server-supported event ID/idempotency contract. Ordering applies only to reporters +sharing this queue, not old clients or independent queues. A report is durable once its +queue file has been flushed and published; failure before that point cannot be recovered. +Storage and filesystem durability depend on the host's filesystem and hardware. +The queue's local file order is not a server sequence or a causal order, and its file +numbering can restart after the queue drains. + +### Ordered idempotent reports (separate opt-in) + +`OrderedUpdateReporter` uses the GeneralSpace ordered-event protocol, but is **disabled +by default** and separate from the legacy file queue. Enable it only after an operator +confirms the deployed service supports both `eventId` and `sequence`; an ordinary +success response is not evidence because older servers ignore unknown fields. + +```csharp +var reporter = new OrderedUpdateReporter( + queueDirectory, httpClient, reportUrl, + namespaceIdentity: "stable-tenant-and-server-database-id", + protocolConfirmed: true); +await reporter.ReplayAsync(cancellationToken); +bootstrap.UpdateReporter(reporter); +``` + +The host must replay on startup and periodically, monitor errors and storage, and +register the same reporter in each reporting process. It must ensure that **all** +writers for a server database's `(type, recordId)` use this one database on the same +machine and the same exact endpoint and namespace identity; no legacy, independent, +multi-machine or restored-old-copy writers may write those records. The namespace must +identify the tenant and actual server database, not an ephemeral token or hostname. +URLs and credentials are not stored, but a hash binding the exact URL and namespace is +stored to reject accidental reconfiguration. The host must prevent redirects, retargeting, +and authentication changes that could send to a different tenant or database. + +The private directory must be on a local filesystem supporting SQLite locking and +durable flushes, with access restricted to trusted processes. Protect the database, +rollback journal, lock file, and backups: report payloads may contain sensitive +diagnostics. SQLite transactionally commits the record counter, GUID, and complete +payload before sending. A lost response or crash replays the same event; a business +conflict or other failure stops replay without deleting it. Keep the database and +counters even when the queue is empty. Deleting, rolling back or cloning the database, +or using network filesystems, invalidates the ordering guarantee. Hardware and filesystem +durability still apply. The SQLite native dependency must be available for the target RID. +Enqueue transactions do not hold the delivery lock during HTTP requests. If delivery +is busy, times out or is cancelled after the transaction commits, `ReportAsync` can +throw while the event remains queued; retry delivery with `ReplayAsync`, not by +submitting a new report. Persistence failures before commit cannot be replayed. + ## 🙏 Thanks
diff --git a/docs/core-execution-flow.md b/docs/core-execution-flow.md index 01e39fbf..6ede67b9 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,10 @@ 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。 + +下载及内置管道的失败报告可带 `category`、`phase`、`errorCode` 和 `message`。下载、校验、解压、补丁应用及回滚在明确的执行边界分类;自定义中间件或编排器没有提供阶段时不猜测。上报只包含固定的诊断代码和消息,不包含异常文本、URL、凭据或堆栈;本地事件保留可获得的原始异常和下载资源。回滚失败时先报告原始包失败,再对同一记录报告回滚失败;服务端是否保留两次历史取决于其实现。Chain 回退 Full 时报告所属 Chain 记录,现有 IPC 不携带独立 Full 记录 ID。取消、启动、兼容性及其他无可靠阶段来源的失败不附加阶段诊断;自检不在此流程中。 + --- ## 10. UpdateStrategy:Upgrade 进程的执行流程 @@ -1366,7 +1370,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/docs/durable-update-attempts.md b/docs/durable-update-attempts.md index 091f0422..526b5330 100644 --- a/docs/durable-update-attempts.md +++ b/docs/durable-update-attempts.md @@ -40,6 +40,8 @@ reopens the journal record to validate the exact bound snapshot. This detects a lost contract only when the child is running a consumer that implements this marker. An older or unrelated executable can ignore it; there is no version handshake proving which consumer was launched. +Such an updater may independently report `Success`; suppression is only +enforced by the participating new Core code, not by the environment marker. The existing IPC file is not an authenticated identity channel. Its fixed AES-CBC key and IV are derived from public implementation constants, and the @@ -47,6 +49,9 @@ contract has no authentication tag or durable consumption nonce. Deleting the file after reading does not prevent a writer from replaying a contract for an active attempt. The required-attempt environment marker checks consistency in the current consumer, not sender authorization. +The default file is `%TEMP%/GeneralUpdate/ipc/process_info.enc` on Windows. +It serializes the configured application secret and authentication credentials; +the fixed-key encryption does not protect them from a local reader. `ReportType` and package `RecordId` values travel in the contract, but the journal does not bind them to an authorized tenant or record identity. There @@ -120,3 +125,11 @@ must establish a versioned required-attempt handshake, consume the attempt contract, keep `AutoRollback=false` until a single real recovery owner is implemented and fenced, and report health only after application-owned readiness confirmation. + +The ordered-report outbox is not automatically installed in either process. +Its `ReplayAsync` must be explicitly invoked by a cooperating host at startup +and after connectivity returns. A committed event is not proof of delivery; +if replay fails after enqueue, replay the queue rather than enqueueing the same +report again. Connecting that lifecycle, verifying the updater before handoff, +and establishing a single authorized writer and recovery owner are separate +unfinished work. No automatic recovery or global filesystem fence is enabled. diff --git a/src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs b/src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs index 7165d88f..1fbc8fd3 100644 --- a/src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs +++ b/src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs @@ -117,11 +117,21 @@ protected T GetOption(Option? option) /// public TBootstrap UpdateReporter() where T : Download.Reporting.IUpdateReporter, new() { + _instances.Remove(typeof(Download.Reporting.IUpdateReporter)); _extensions[typeof(Download.Reporting.IUpdateReporter)] = typeof(T); _extensionFactories[typeof(Download.Reporting.IUpdateReporter)] = () => new T(); return (TBootstrap)this; } + /// Registers a configured reporter instance for the update workflow. + public TBootstrap UpdateReporter(Download.Reporting.IUpdateReporter reporter) + { + if (reporter == null) throw new ArgumentNullException(nameof(reporter)); + _instances[typeof(Download.Reporting.IUpdateReporter)] = reporter; + _extensions[typeof(Download.Reporting.IUpdateReporter)] = reporter.GetType(); + return (TBootstrap)this; + } + /// /// Registers a custom OS-level strategy implementation (e.g., /// , , 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 7a2029db..4f61202e 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; @@ -59,12 +60,73 @@ 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); +public record UpdateReport(int RecordId, int Status = 1, int Type = 1) +{ + /// Optional idempotency key, paired with . + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public Guid? EventId { get; init; } + + /// Optional positive sequence for the record, paired with . + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? Sequence { get; init; } + + /// 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 @@ -141,17 +203,7 @@ public async Task ReportAsync(UpdateReport report, CancellationToken token = def { if(string.IsNullOrWhiteSpace(_reportUrl)) return; - - var json = JsonSerializer.Serialize(report, UpdateReportJsonContext.Default.UpdateReport); - using var request = new HttpRequestMessage(HttpMethod.Post, _reportUrl); - request.Content = new StringContent(json, Encoding.UTF8, "application/json"); - - // Apply the global authentication provider (if one was set via - // VersionService.SetDefaultAuthProvider or HttpClientProvider.DefaultAuthProvider) - // so that report requests carry the same credentials as version validation requests. - await HttpClientProvider.ApplyAuthAsync(request, token).ConfigureAwait(false); - - await _client.SendAsync(request, token).ConfigureAwait(false); + await SendAsync(report, token).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -162,4 +214,39 @@ public async Task ReportAsync(UpdateReport report, CancellationToken token = def GeneralTracer.Warn($"Report failed: {ex.Message}"); } } + + /// Sends a report and throws unless the server confirms both HTTP and business success. + public async Task SendAsync(UpdateReport report, CancellationToken token = default) + { + if (report == null) throw new ArgumentNullException(nameof(report)); + if (string.IsNullOrWhiteSpace(_reportUrl)) + throw new InvalidOperationException("A report URL is required."); + + var json = JsonSerializer.Serialize(report, UpdateReportJsonContext.Default.UpdateReport); + await SendJsonAsync(json, token).ConfigureAwait(false); + } + + internal async Task SendJsonAsync(string json, CancellationToken token) + { + if (string.IsNullOrWhiteSpace(_reportUrl)) + throw new InvalidOperationException("A report URL is required."); + using var request = new HttpRequestMessage(HttpMethod.Post, _reportUrl); + request.Content = new StringContent(json, Encoding.UTF8, "application/json"); + await HttpClientProvider.ApplyAuthAsync(request, token).ConfigureAwait(false); + using var response = await _client.SendAsync(request, token).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + using var document = JsonDocument.Parse(content); + var root = document.RootElement; + if (root.ValueKind == JsonValueKind.Object && + root.TryGetProperty("errorCode", out var errorCode) && + errorCode.ValueKind == JsonValueKind.String && + errorCode.GetString() == "Conflict") + throw new InvalidOperationException("The report endpoint reported an event or sequence conflict."); + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("code", out var code) || code.ValueKind != JsonValueKind.Number || + !code.TryGetInt32(out var value) || value != 200 || + !root.TryGetProperty("body", out var body) || body.ValueKind != JsonValueKind.True) + throw new InvalidOperationException("The report endpoint did not confirm business success."); + } } diff --git a/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs new file mode 100644 index 00000000..737085d4 --- /dev/null +++ b/src/GeneralUpdate.Core/Download/Reporting/OrderedUpdateReporter.cs @@ -0,0 +1,209 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using GeneralUpdate.Core.JsonContext; +using Microsoft.Data.Sqlite; + +namespace GeneralUpdate.Core.Download.Reporting; + +/// +/// Opt-in, single-host outbox for an explicitly authorized ordered-report protocol. +/// All writers for the same server record namespace must share the same local database. +/// +public sealed class OrderedUpdateReporter : IUpdateReporter +{ + private readonly string _directory; + private readonly string _identity; + private readonly HttpUpdateReporter _sender; + private readonly TimeSpan _lockTimeout; + + /// + /// Creates an ordered reporter. The operator must confirm that the endpoint supports + /// the event ID and sequence protocol and that namespaceIdentity identifies the stable + /// tenant and server database namespace. A successful POST is not capability detection. + /// + public OrderedUpdateReporter(string directory, HttpClient client, string reportUrl, + string namespaceIdentity, bool protocolConfirmed, TimeSpan? lockTimeout = null) + { + if (!protocolConfirmed) throw new InvalidOperationException("The ordered-report protocol must be explicitly confirmed."); + if (string.IsNullOrWhiteSpace(directory)) throw new ArgumentException("A private local directory is required.", nameof(directory)); + if (client == null) throw new ArgumentNullException(nameof(client)); + if (!Uri.TryCreate(reportUrl, UriKind.Absolute, out var uri) || + (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + throw new ArgumentException("An absolute HTTP report URL is required.", nameof(reportUrl)); + if (string.IsNullOrWhiteSpace(namespaceIdentity)) + throw new ArgumentException("A stable tenant and database namespace identity is required.", nameof(namespaceIdentity)); + _directory = Path.GetFullPath(directory); + _identity = Identity(reportUrl, namespaceIdentity); + _sender = new HttpUpdateReporter(client, reportUrl); + _lockTimeout = lockTimeout ?? TimeSpan.FromSeconds(30); + if (_lockTimeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(lockTimeout)); + } + + /// Atomically allocates an event and sequence, commits the payload, then replays. + public async Task ReportAsync(UpdateReport report, CancellationToken token = default) + { + if (report == null) throw new ArgumentNullException(nameof(report)); + if (report.EventId != null || report.Sequence != null) + throw new ArgumentException("The outbox allocates event IDs and sequences.", nameof(report)); + if (report.RecordId <= 0 || (report.Type != 1 && report.Type != 2)) + throw new ArgumentException("A positive record ID and supported record type are required.", nameof(report)); + + Directory.CreateDirectory(_directory); + using (var connection = Open()) + { + token.ThrowIfCancellationRequested(); + using (var transaction = connection.BeginTransaction()) + { + using (var update = connection.CreateCommand()) + { + update.Transaction = transaction; + update.CommandText = @"INSERT INTO counters (type, record_id, sequence) VALUES ($type, $record, 1) + ON CONFLICT(type, record_id) DO UPDATE SET sequence = sequence + 1 + WHERE sequence < 9223372036854775807;"; + update.Parameters.AddWithValue("$type", report.Type); + update.Parameters.AddWithValue("$record", report.RecordId); + if (update.ExecuteNonQuery() != 1) throw new InvalidOperationException("Report sequence exhausted."); + } + long sequence; + using (var read = connection.CreateCommand()) + { + read.Transaction = transaction; + read.CommandText = "SELECT sequence FROM counters WHERE type = $type AND record_id = $record;"; + read.Parameters.AddWithValue("$type", report.Type); + read.Parameters.AddWithValue("$record", report.RecordId); + sequence = (long)read.ExecuteScalar()!; + } + var payload = JsonSerializer.Serialize(report with { EventId = Guid.NewGuid(), Sequence = sequence }, + UpdateReportJsonContext.Default.UpdateReport); + using (var insert = connection.CreateCommand()) + { + insert.Transaction = transaction; + insert.CommandText = "INSERT INTO outbox (payload) VALUES ($payload);"; + insert.Parameters.AddWithValue("$payload", payload); + insert.ExecuteNonQuery(); + } + transaction.Commit(); + } + } + await ReplayAsync(token).ConfigureAwait(false); + } + + /// Replays committed events in order, stopping on the first unconfirmed response. + public async Task ReplayAsync(CancellationToken token = default) + { + using (await AcquireLockAsync(token).ConfigureAwait(false)) + using (var connection = Open()) + await ReplayLockedAsync(connection, token).ConfigureAwait(false); + } + + private async Task ReplayLockedAsync(SqliteConnection connection, CancellationToken token) + { + while (true) + { + token.ThrowIfCancellationRequested(); + long id; + string payload; + using (var command = connection.CreateCommand()) + { + command.CommandText = "SELECT id, payload FROM outbox ORDER BY id LIMIT 1;"; + using (var reader = command.ExecuteReader()) + { + if (!reader.Read()) return; + id = reader.GetInt64(0); + payload = reader.GetString(1); + } + } + await _sender.SendJsonAsync(payload, token).ConfigureAwait(false); + using (var command = connection.CreateCommand()) + { + command.CommandText = "DELETE FROM outbox WHERE id = $id;"; + command.Parameters.AddWithValue("$id", id); + if (command.ExecuteNonQuery() != 1) + throw new InvalidDataException("The queued report changed during delivery."); + } + } + } + + private SqliteConnection Open() + { + var builder = new SqliteConnectionStringBuilder + { + DataSource = Path.Combine(_directory, "ordered-reports.db"), + Mode = SqliteOpenMode.ReadWriteCreate, + Pooling = false + }; + var connection = new SqliteConnection(builder.ToString()); + try + { + connection.Open(); + using (var command = connection.CreateCommand()) + { + command.CommandText = "PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL;"; + command.ExecuteNonQuery(); + } + using (var transaction = connection.BeginTransaction()) + { + using (var command = connection.CreateCommand()) + { + command.Transaction = transaction; + command.CommandText = @"CREATE TABLE IF NOT EXISTS metadata (id INTEGER PRIMARY KEY CHECK(id = 1), identity TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS counters (type INTEGER NOT NULL, record_id INTEGER NOT NULL, + sequence INTEGER NOT NULL, PRIMARY KEY(type, record_id)); + CREATE TABLE IF NOT EXISTS outbox (id INTEGER PRIMARY KEY AUTOINCREMENT, payload TEXT NOT NULL); + INSERT OR IGNORE INTO metadata (id, identity) VALUES (1, $identity);"; + command.Parameters.AddWithValue("$identity", _identity); + command.ExecuteNonQuery(); + } + using (var command = connection.CreateCommand()) + { + command.Transaction = transaction; + command.CommandText = "SELECT identity FROM metadata WHERE id = 1;"; + if (!string.Equals(command.ExecuteScalar() as string, _identity, StringComparison.Ordinal)) + throw new InvalidOperationException("The ordered outbox belongs to a different endpoint or namespace."); + } + transaction.Commit(); + } + return connection; + } + catch + { + connection.Dispose(); + throw; + } + } + + private async Task AcquireLockAsync(CancellationToken token) + { + Directory.CreateDirectory(_directory); + var started = Stopwatch.StartNew(); + while (true) + { + token.ThrowIfCancellationRequested(); + try + { + return new FileStream(Path.Combine(_directory, "ordered-reports.lock"), FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.None); + } + catch (IOException) when (started.Elapsed < _lockTimeout) + { + await Task.Delay(TimeSpan.FromMilliseconds(100), token).ConfigureAwait(false); + } + } + } + + private static string Identity(string endpoint, string scope) + { + using (var hash = SHA256.Create()) + { + var value = endpoint.Length + ":" + endpoint + scope.Length + ":" + scope; + return Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(value))); + } + } +} diff --git a/src/GeneralUpdate.Core/Download/Reporting/PersistentUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/PersistentUpdateReporter.cs new file mode 100644 index 00000000..6186b754 --- /dev/null +++ b/src/GeneralUpdate.Core/Download/Reporting/PersistentUpdateReporter.cs @@ -0,0 +1,114 @@ +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using GeneralUpdate.Core.JsonContext; + +namespace GeneralUpdate.Core.Download.Reporting; + +/// +/// Opt-in, disk-backed, ordered at-least-once reporting. The host must replay on startup. +/// Use a separate queue directory for each endpoint and protect it from untrusted writers. +/// +public sealed class PersistentUpdateReporter : IUpdateReporter +{ + private readonly string _directory; + private readonly HttpUpdateReporter _sender; + private readonly TimeSpan _lockTimeout; + + /// Creates a reporter using the supplied endpoint and queue directory. + public PersistentUpdateReporter(string directory, HttpUpdateReporter sender, TimeSpan? lockTimeout = null) + { + if (string.IsNullOrWhiteSpace(directory)) throw new ArgumentException("A queue directory is required.", nameof(directory)); + _directory = Path.GetFullPath(directory); + _sender = sender ?? throw new ArgumentNullException(nameof(sender)); + _lockTimeout = lockTimeout ?? TimeSpan.FromSeconds(30); + if (_lockTimeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(lockTimeout)); + } + + /// Persists the report before attempting to send the ordered queue. + public async Task ReportAsync(UpdateReport report, CancellationToken token = default) + { + if (report == null) throw new ArgumentNullException(nameof(report)); + using (await AcquireLockAsync(token).ConfigureAwait(false)) + { + var files = PendingFiles(); + long sequence = files.Length == 0 ? 1 : + checked(long.Parse(Path.GetFileNameWithoutExtension(files[files.Length - 1]), CultureInfo.InvariantCulture) + 1); + var path = Path.Combine(_directory, sequence.ToString("D20", CultureInfo.InvariantCulture) + ".json"); + var temp = Path.Combine(_directory, Guid.NewGuid().ToString("N") + ".tmp"); + try + { + var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(report, UpdateReportJsonContext.Default.UpdateReport)); + using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + stream.Write(bytes, 0, bytes.Length); + stream.Flush(true); + } + File.Move(temp, path); + } + finally + { + if (File.Exists(temp)) File.Delete(temp); + } + await ReplayLockedAsync(token).ConfigureAwait(false); + } + } + + /// Retries pending reports in order, stopping and throwing on the first failure. + public async Task ReplayAsync(CancellationToken token = default) + { + using (await AcquireLockAsync(token).ConfigureAwait(false)) + await ReplayLockedAsync(token).ConfigureAwait(false); + } + + private async Task ReplayLockedAsync(CancellationToken token) + { + foreach (var path in PendingFiles()) + { + token.ThrowIfCancellationRequested(); + var json = File.ReadAllText(path, Encoding.UTF8); + using (var document = JsonDocument.Parse(json)) + { + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || + !IsInteger(root, "recordId") || !IsInteger(root, "status") || !IsInteger(root, "type")) + throw new InvalidDataException("A queued update report is invalid."); + } + var report = JsonSerializer.Deserialize(json, UpdateReportJsonContext.Default.UpdateReport) + ?? throw new InvalidDataException("A queued update report is null."); + await _sender.SendAsync(report, token).ConfigureAwait(false); + File.Delete(path); + } + } + + private string[] PendingFiles() => + Directory.GetFiles(_directory, "*.json").OrderBy(Path.GetFileName, StringComparer.Ordinal).ToArray(); + + private static bool IsInteger(JsonElement root, string name) => + root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && + value.TryGetInt32(out _); + + private async Task AcquireLockAsync(CancellationToken token) + { + Directory.CreateDirectory(_directory); + var started = System.Diagnostics.Stopwatch.StartNew(); + while (true) + { + token.ThrowIfCancellationRequested(); + try + { + return new FileStream(Path.Combine(_directory, "queue.lock"), FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.None); + } + catch (IOException) when (started.Elapsed < _lockTimeout) + { + await Task.Delay(TimeSpan.FromMilliseconds(100), token).ConfigureAwait(false); + } + } + } +} 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/GeneralUpdate.Core.csproj b/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj index 4758cfe4..4c760338 100644 --- a/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj +++ b/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj @@ -38,6 +38,8 @@ + + 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 39c1598d..2181fb3d 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; @@ -14,6 +15,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 +56,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. @@ -106,6 +110,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. /// @@ -134,7 +141,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. /// /// @@ -162,8 +169,11 @@ public virtual async Task ExecuteAsync() try { AllPackagesSucceeded = true; + HasReportedPackageFailures = false; _appliedAnyVersion = false; - var status = ReportType.None; + var recordStatuses = new Dictionary(); + var reportOrder = new List(); + var rollbackFailures = new HashSet(); patchRoot = StorageManager.GetTempDirectory(Patchs); // Track the highest version already applied via full-package fallback, @@ -182,8 +192,16 @@ 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, new UpdateReport(version.RecordId, ReportType.Success, _configinfo.ReportType)); + reportOrder.Add(version.RecordId); + } continue; } + var status = ReportType.None; + PipelineContext? context = null; + FailureCategory? failureCategory = null; try { // Use a version-specific subdirectory under patchRoot so that @@ -200,7 +218,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; @@ -211,6 +229,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, @@ -250,29 +272,44 @@ 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 { - if (status != ReportType.Success || !_configinfo.DurableUpdateAttemptId.HasValue) - await Reporter.ReportAsync(new UpdateReport(version.RecordId, status, version.AppType ?? 1)); + _failureRecordId = null; + _failureCategory = null; + if (!recordStatuses.TryGetValue(version.RecordId, out var previousStatus) + || previousStatus.Status != ReportType.Failure) + { + if (!recordStatuses.ContainsKey(version.RecordId)) + reportOrder.Add(version.RecordId); + 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. @@ -280,6 +317,25 @@ public virtual async Task ExecuteAsync() } } + foreach (var recordId in reportOrder) + { + var report = recordStatuses[recordId]; + if (report.Status == ReportType.Failure) + HasReportedPackageFailures = true; + if (report.Status == ReportType.Success && _configinfo.DurableUpdateAttemptId.HasValue) + continue; + try + { + await Reporter.ReportAsync(report).ConfigureAwait(false); + if (rollbackFailures.Contains(recordId)) + await Reporter.ReportAsync(FailureReports.Create(recordId, _configinfo.ReportType, FailureCategory.Rollback)).ConfigureAwait(false); + } + catch (Exception ex) + { + GeneralTracer.Warn($"Report package result failed: {ex.Message}"); + } + } + TryCleanTempPath(); await OnExecuteCompleteAsync(); } @@ -407,7 +463,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 + }); } /// @@ -529,12 +588,12 @@ 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) { if (_configinfo.DisableLegacyRollback) { GeneralTracer.Warn("AbstractStrategy.TryRollback: skipped because this durable attempt suppresses legacy automatic rollback."); - return; + return true; } try @@ -558,10 +617,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 688ae2ae..6954deda 100644 --- a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs @@ -53,7 +53,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. @@ -74,10 +74,10 @@ 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) - internal EncryptedFileProcessContractProvider? ProcessContractProvider { get; set; } - /// /// When false, skips in MainOnly / Both scenarios. /// The caller (e.g. ) is responsible for launching the @@ -87,7 +87,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; } @@ -135,6 +135,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. /// @@ -186,7 +192,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>(). @@ -236,6 +246,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) { @@ -262,6 +274,7 @@ public async Task ExecuteAsync() if (_configInfo == null) throw new InvalidOperationException("ClientStrategy not configured."); HasPreparedClientUpdate = false; + _downloadFailuresReported = false; try { @@ -274,7 +287,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)); } @@ -391,7 +405,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. /// @@ -634,6 +648,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}")); @@ -687,16 +720,16 @@ 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."); } 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); @@ -715,7 +748,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."); @@ -724,7 +758,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); @@ -781,7 +815,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, @@ -792,7 +826,7 @@ private void SendProcessIpc(List clientVersions) _configInfo.ProcessContract = JsonSerializer.Serialize(processInfo, ProcessContractJsonContext.Default.ProcessContract); - (ProcessContractProvider ?? new EncryptedFileProcessContractProvider()).Send(processInfo); + await (ProcessContractProvider ?? new EncryptedFileProcessContractProvider()).SendAsync(processInfo).ConfigureAwait(false); HasPreparedClientUpdate = true; GeneralTracer.Info("ClientStrategy: ProcessContract sent with MainApp versions only."); } @@ -1163,7 +1197,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) @@ -1181,7 +1215,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) @@ -1200,7 +1234,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 98b9537e..a88e03fd 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) { @@ -147,7 +154,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/CoreTest.csproj b/tests/CoreTest/CoreTest.csproj index 98368a96..36d79485 100644 --- a/tests/CoreTest/CoreTest.csproj +++ b/tests/CoreTest/CoreTest.csproj @@ -5,6 +5,7 @@ enable enable false + true @@ -22,6 +23,7 @@ + \ No newline at end of file diff --git a/tests/CoreTest/Download/OrderedUpdateReporterTests.cs b/tests/CoreTest/Download/OrderedUpdateReporterTests.cs new file mode 100644 index 00000000..b0d9c79f --- /dev/null +++ b/tests/CoreTest/Download/OrderedUpdateReporterTests.cs @@ -0,0 +1,200 @@ +using System.Diagnostics; +using System.Net; +using System.Text.Json; +using GeneralUpdate.Core.Download.Reporting; +using Microsoft.Data.Sqlite; + +namespace CoreTest.Download; + +public sealed class OrderedUpdateReporterTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "gu-ordered-" + Guid.NewGuid()); + + [Fact] + public async Task ReplaysExactEventAfterLostResponseAndKeepsCountersAfterDrain() + { + var handler = new Handler { Fail = true, AcceptBeforeFailure = true }; + var reporter = Create(handler); + await Assert.ThrowsAsync(() => reporter.ReportAsync(new UpdateReport(10, 3) + { + Category = FailureCategory.Apply, Phase = "Apply", Message = "Apply failed." + })); + handler.Fail = false; + await Create(handler).ReplayAsync(); + await Create(handler).ReportAsync(new UpdateReport(10, 2)); + await Create(handler).ReportAsync(new UpdateReport(10, 1, 2)); + Assert.Equal(handler.Bodies[0], handler.Bodies[1]); + Assert.Equal(new long[] { 1, 1, 2, 1 }, handler.Bodies.Select(Sequence)); + Assert.Equal(EventId(handler.Bodies[0]), EventId(handler.Bodies[1])); + Assert.Equal(3, handler.Applied.Count); + Assert.NotEqual(EventId(handler.Bodies[1]), EventId(handler.Bodies[2])); + Assert.DoesNotContain("example.test", File.ReadAllText(Path.Combine(_directory, "ordered-reports.db"))); + } + + [Fact] + public async Task LegacySenderDoesNotAddProtocolFields() + { + var handler = new Handler(); + await new HttpUpdateReporter(new HttpClient(handler, false), "https://example.test/report") + .SendAsync(new UpdateReport(10)); + using var json = JsonDocument.Parse(Assert.Single(handler.Bodies)); + Assert.False(json.RootElement.TryGetProperty("eventId", out _)); + Assert.False(json.RootElement.TryGetProperty("sequence", out _)); + } + + [Fact] + public async Task AuthorizationIdentityAndConflictFailClosed() + { + var handler = new Handler(); + using var client = new HttpClient(handler, false); + Assert.Throws(() => new OrderedUpdateReporter(_directory, client, "https://example.test/report", "tenant/database", false)); + await Create(handler).ReportAsync(new UpdateReport(10)); + await Assert.ThrowsAsync(() => + new OrderedUpdateReporter(_directory, client, "https://example.test/report", "different tenant", true).ReplayAsync()); + Assert.Single(handler.Bodies); + + handler.Conflict = true; + var error = await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(10))); + Assert.Contains("conflict", error.Message); + handler.Conflict = false; + await Create(handler).ReplayAsync(); + Assert.Equal(handler.Bodies[1], handler.Bodies[2]); + } + + [Fact] + public async Task ConcurrentProcessesAllocateUniqueSequences() + { + var workers = Enumerable.Range(0, 6).Select(_ => StartWorker("offline")).ToArray(); + foreach (var worker in workers) + { + await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(90)); + Assert.Equal(0, worker.ExitCode); + worker.Dispose(); + } + var handler = new Handler(); + await Create(handler).ReplayAsync(); + Assert.Equal(Enumerable.Range(1, 6).Select(i => (long)i), handler.Bodies.Select(Sequence)); + Assert.Equal(6, handler.Bodies.Select(EventId).Distinct().Count()); + } + + [Fact] + public async Task KilledProcessReplaysCommittedPayload() + { + using var worker = StartWorker("hold"); + try + { + Assert.Equal("committed", await worker.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(60))); + } + finally + { + if (!worker.HasExited) worker.Kill(entireProcessTree: true); + await worker.WaitForExitAsync(); + } + var handler = new Handler(); + await Create(handler).ReplayAsync(); + await Create(handler).ReportAsync(new UpdateReport(10, 2)); + Assert.Equal(new long[] { 1, 2 }, handler.Bodies.Select(Sequence)); + } + + [Fact] + public async Task SlowDeliveryDoesNotBlockAnotherProcessFromCommitting() + { + using var first = StartWorker("hold"); + Process? second = null; + try + { + Assert.Equal("committed", await first.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(60))); + second = StartWorker("offline"); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + while (true) + { + timeout.Token.ThrowIfCancellationRequested(); + using var connection = new SqliteConnection(new SqliteConnectionStringBuilder + { + DataSource = Path.Combine(_directory, "ordered-reports.db"), + Mode = SqliteOpenMode.ReadOnly, + Pooling = false + }.ToString()); + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = "SELECT COUNT(*) FROM outbox;"; + if ((long)command.ExecuteScalar()! == 2) break; + await Task.Delay(100, timeout.Token); + } + Assert.False(first.HasExited); + } + finally + { + if (!first.HasExited) first.Kill(entireProcessTree: true); + await first.WaitForExitAsync(); + if (second != null) + { + if (!second.HasExited) second.Kill(entireProcessTree: true); + await second.WaitForExitAsync(); + second.Dispose(); + } + } + var handler = new Handler(); + await Create(handler).ReplayAsync(); + Assert.Equal(new long[] { 1, 2 }, handler.Bodies.Select(Sequence)); + } + + [Fact] + public async Task ConcurrentInstancesAllocatePerRecord() + { + var handler = new Handler { Fail = true }; + await Task.WhenAll(Enumerable.Range(0, 12).Select(async _ => + await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(10, 3))))); + handler.Fail = false; + handler.Bodies.Clear(); + await Create(handler).ReplayAsync(); + Assert.Equal(Enumerable.Range(1, 12).Select(i => (long)i), handler.Bodies.Select(Sequence)); + Assert.Equal(12, handler.Bodies.Select(EventId).Distinct().Count()); + } + + private OrderedUpdateReporter Create(Handler handler) => + new(_directory, new HttpClient(handler, false), "https://example.test/report", "tenant/database", true); + + private Process StartWorker(string mode) + { + var testAssembly = typeof(OrderedUpdateReporterTests).Assembly.Location; + var start = new ProcessStartInfo("dotnet") { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + foreach (var arg in new[] { "exec", "--runtimeconfig", Path.ChangeExtension(testAssembly, ".runtimeconfig.json"), + "--depsfile", Path.ChangeExtension(testAssembly, ".deps.json"), typeof(ReportWorker.Marker).Assembly.Location, _directory, mode }) + start.ArgumentList.Add(arg); + return Process.Start(start)!; + } + + private static long Sequence(string body) => JsonDocument.Parse(body).RootElement.GetProperty("sequence").GetInt64(); + private static Guid EventId(string body) => JsonDocument.Parse(body).RootElement.GetProperty("eventId").GetGuid(); + + public void Dispose() + { + if (Directory.Exists(_directory)) Directory.Delete(_directory, true); + } + + private sealed class Handler : HttpMessageHandler + { + public bool Fail { get; set; } + public bool AcceptBeforeFailure { get; set; } + public bool Conflict { get; set; } + public List Bodies { get; } = []; + public HashSet Applied { get; } = []; + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token) + { + var body = await request.Content!.ReadAsStringAsync(token); + Bodies.Add(body); + using var json = JsonDocument.Parse(body); + if ((!Fail || AcceptBeforeFailure) && !Conflict && + json.RootElement.TryGetProperty("eventId", out var eventId)) + Applied.Add(eventId.GetGuid()); + if (Fail) throw new HttpRequestException("lost response"); + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(Conflict + ? "{\"code\":400,\"errorCode\":\"Conflict\",\"body\":false}" + : "{\"code\":200,\"body\":true}") + }; + } + } +} diff --git a/tests/CoreTest/Download/PersistentUpdateReporterTests.cs b/tests/CoreTest/Download/PersistentUpdateReporterTests.cs new file mode 100644 index 00000000..24824e9a --- /dev/null +++ b/tests/CoreTest/Download/PersistentUpdateReporterTests.cs @@ -0,0 +1,215 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Download.Reporting; +using GeneralUpdate.Core.JsonContext; +using GeneralUpdate.Core.Strategy; + +namespace CoreTest.Download; + +public sealed class PersistentUpdateReporterTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "gu-report-" + Guid.NewGuid()); + + [Theory] + [InlineData(500, "{\"code\":200,\"body\":true}")] + [InlineData(200, "{\"code\":500,\"body\":true}")] + [InlineData(200, "{\"code\":200,\"body\":false}")] + [InlineData(200, "{}")] + [InlineData(200, "not json")] + public async Task RejectedResponseIsPersistedAndReplayed(int status, string body) + { + var handler = new Handler(_ => new HttpResponseMessage((HttpStatusCode)status) { Content = new StringContent(body) }); + var reporter = Create(handler); + await Assert.ThrowsAnyAsync(() => reporter.ReportAsync(new UpdateReport(10, 3))); + Assert.Single(Directory.GetFiles(_directory, "*.json")); + + handler.Respond = _ => Success(); + await Create(handler).ReplayAsync(); + Assert.Empty(Directory.GetFiles(_directory, "*.json")); + Assert.Equal(new[] { 3, 3 }, handler.Statuses); + } + + [Fact] + public async Task OfflineThenRestartPreservesTerminalOrder() + { + var handler = new Handler(_ => throw new HttpRequestException("offline")); + await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(1, 3))); + await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(1, 2))); + Assert.Equal(2, Directory.GetFiles(_directory, "*.json").Length); + + handler.Statuses.Clear(); + handler.Respond = _ => Success(); + await Create(handler).ReplayAsync(); + Assert.Equal(new[] { 3, 2 }, handler.Statuses); + await Create(handler).ReplayAsync(); + Assert.Equal(new[] { 3, 2 }, handler.Statuses); + } + + [Fact] + public async Task FailureDetailsSurviveRestartAndReplayInOrder() + { + var reports = new[] + { + new UpdateReport(41, (int)UpdateStatus.Failure, 2) + { + Category = FailureCategory.Download, + Phase = "Download", + ErrorCode = "DOWNLOAD", + Message = "Download failed." + }, + new UpdateReport(42, (int)UpdateStatus.Failure, 1) + { + Category = FailureCategory.Apply, + Phase = "Apply", + ErrorCode = "APPLY", + Message = "Apply failed." + } + }; + var handler = new Handler(_ => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)); + + await Assert.ThrowsAsync(() => Create(handler).ReportAsync(reports[0])); + await Assert.ThrowsAsync(() => Create(handler).ReportAsync(reports[1])); + + var queuedJson = string.Join("", Directory.GetFiles(_directory, "*.json").Select(File.ReadAllText)); + Assert.DoesNotContain("example.test", queuedJson); + Assert.DoesNotContain("secret", queuedJson); + Assert.Equal(reports, Directory.GetFiles(_directory, "*.json") + .OrderBy(Path.GetFileName, StringComparer.Ordinal) + .Select(path => JsonSerializer.Deserialize(File.ReadAllText(path), UpdateReportJsonContext.Default.UpdateReport))); + + handler.Bodies.Clear(); + handler.Statuses.Clear(); + handler.Respond = _ => Success(); + + await Create(handler).ReplayAsync(); + + Assert.Empty(Directory.GetFiles(_directory, "*.json")); + Assert.Equal(reports.Select(report => report.Status), handler.Statuses); + Assert.Equal(reports.Length, handler.Bodies.Count); + for (var index = 0; index < reports.Length; index++) + { + var json = handler.Bodies[index]; + var replayed = JsonSerializer.Deserialize(json, UpdateReportJsonContext.Default.UpdateReport); + Assert.Equal(reports[index], replayed); + + var legacy = JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + Assert.Equal((reports[index].RecordId, reports[index].Status, reports[index].Type), + (legacy!.RecordId, legacy.Status, legacy.Type)); + } + } + + [Fact] + public async Task LostAcknowledgementCanDuplicateButCannotSkipFailure() + { + var handler = new Handler(_ => throw new HttpRequestException("response lost after server accepted")); + await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(2, 3))); + handler.Respond = _ => Success(); + await Create(handler).ReplayAsync(); + Assert.Equal(new[] { 3, 3 }, handler.Statuses); + } + + [Fact] + public async Task ConcurrentReportersShareQueueAndNeverPersistCredentials() + { + var handler = new Handler(_ => throw new HttpRequestException("offline")); + var tasks = Enumerable.Range(1, 8).Select(async i => + { + await Assert.ThrowsAsync(() => Create(handler).ReportAsync(new UpdateReport(i, 3))); + }); + await Task.WhenAll(tasks); + var files = Directory.GetFiles(_directory, "*.json"); + Assert.Equal(8, files.Length); + foreach (var file in files) + { + var json = File.ReadAllText(file); + Assert.DoesNotContain("example.test", json); + Assert.DoesNotContain("secret", json); + } + handler.Respond = _ => Success(); + await Create(handler).ReplayAsync(); + Assert.Empty(Directory.GetFiles(_directory, "*.json")); + } + + [Fact] + public async Task StrictSenderRejectsUnconfiguredEndpoint() + { + await Assert.ThrowsAsync(() => new HttpUpdateReporter().SendAsync(new UpdateReport(1))); + } + + [Fact] + public async Task CorruptQueueStopsWithoutSendingOrDeleting() + { + Directory.CreateDirectory(_directory); + var path = Path.Combine(_directory, "00000000000000000001.json"); + File.WriteAllText(path, "{}"); + var handler = new Handler(_ => Success()); + await Assert.ThrowsAsync(() => Create(handler).ReplayAsync()); + Assert.True(File.Exists(path)); + Assert.Empty(handler.Statuses); + } + + [Fact] + public void BootstrapRegistersConfiguredInstanceAndAllowsReplacement() + { + var bootstrap = new TestBootstrap(); + var reporter = Create(new Handler(_ => Success())); + Assert.Same(reporter, bootstrap.UpdateReporter(reporter).ResolveReporter()); + Assert.IsType(bootstrap.UpdateReporter().ResolveReporter()); + } + + [Fact] + public async Task CancellationAfterCommitKeepsReport() + { + using var cts = new CancellationTokenSource(); + var handler = new Handler(_ => + { + cts.Cancel(); + throw new OperationCanceledException(cts.Token); + }); + await Assert.ThrowsAnyAsync(() => + Create(handler).ReportAsync(new UpdateReport(1, 3), cts.Token)); + Assert.Single(Directory.GetFiles(_directory, "*.json")); + } + + private PersistentUpdateReporter Create(Handler handler) => + new(_directory, new HttpUpdateReporter(new HttpClient(handler, false), "https://example.test/report?secret=value")); + + private static HttpResponseMessage Success() => + new(HttpStatusCode.OK) { Content = new StringContent("{\"code\":200,\"body\":true}", Encoding.UTF8, "application/json") }; + + private sealed class TestBootstrap : AbstractBootstrap + { + public IUpdateReporter? ResolveReporter() => ResolveExtension(); + public override Task LaunchAsync() => Task.FromResult(this); + } + + public void Dispose() + { + if (Directory.Exists(_directory)) Directory.Delete(_directory, true); + } + + private sealed class Handler(Func respond) : HttpMessageHandler + { + public Func Respond { get; set; } = respond; + public List Statuses { get; } = []; + public List Bodies { get; } = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var body = await request.Content!.ReadAsStringAsync(cancellationToken); + Bodies.Add(body); + using var json = JsonDocument.Parse(body); + Statuses.Add(json.RootElement.GetProperty("status").GetInt32()); + return Respond(request); + } + } + + private sealed class LegacyReport + { + public int RecordId { get; set; } + public int Status { get; set; } + public int Type { get; set; } + } +} diff --git a/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs b/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs index b67456b9..c36acc07 100644 --- a/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs +++ b/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs @@ -1,5 +1,7 @@ using System.Diagnostics; using System.IO.Compression; +using System.Net; +using System.Net.Sockets; using System.Text; using System.Text.Json; using GeneralUpdate.Core.Configuration; @@ -14,6 +16,7 @@ using GeneralUpdate.Core.StartupHealth; using GeneralUpdate.Core.Strategy; using Moq; +using Microsoft.Data.Sqlite; namespace CoreTest.StartupHealth; @@ -374,6 +377,110 @@ public void Child_process_requires_the_matching_attempt_contract_and_rejects_mis Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId)); } + [Fact] + public async Task Child_apply_failure_survives_restart_and_replays_exact_ordered_event_over_http() + { + var installPath = Path.Combine(_root, "install-ordered"); + var sourcePath = Path.Combine(_root, "source-ordered"); + var tempRoot = Path.Combine(_root, "ipc-ordered"); + var ipcDirectory = Path.Combine(tempRoot, "GeneralUpdate", "ipc"); + var queue = Path.Combine(_root, "queue"); + Directory.CreateDirectory(installPath); + Directory.CreateDirectory(sourcePath); + Directory.CreateDirectory(ipcDirectory); + File.WriteAllText(Path.Combine(sourcePath, "file.txt"), "snapshot"); + File.WriteAllText(Path.Combine(_root, "package.zip"), "invalid archive"); + var store = CreateBoundAttempt(installPath, sourcePath, out var attemptId); + var contract = CreateAttemptContract(installPath, attemptId, store.GetAttempt(attemptId).SnapshotPath!); + contract.UpdateVersions[0].RecordId = 303; + contract.ReportType = 2; + new EncryptedFileProcessContractProvider(ipcDirectory).Send(contract); + + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + using var server = new HttpListener(); + var url = $"http://127.0.0.1:{port}/report/"; + server.Prefixes.Add(url); + server.Start(); + + async Task RespondAsync(int status) + { + var request = await server.GetContextAsync().WaitAsync(TimeSpan.FromSeconds(30)); + using var reader = new StreamReader(request.Request.InputStream, Encoding.UTF8); + var body = await reader.ReadToEndAsync(); + request.Response.StatusCode = status; + var bytes = Encoding.UTF8.GetBytes("{\"code\":200,\"body\":true}"); + request.Response.ContentLength64 = bytes.Length; + await request.Response.OutputStream.WriteAsync(bytes); + request.Response.Close(); + return body; + } + + var firstResponse = RespondAsync(503); + var start = CreateProbeStart("attempt-apply-ordered", queue, url); + ConfigureProbeTemp(start, tempRoot); + start.EnvironmentVariables[DurableUpdateAttemptStore.RequiredAttemptIdEnvironmentVariable] = attemptId.ToString("D"); + string failedDelivery; + using (var child = Process.Start(start)!) + try + { + var stdout = child.StandardOutput.ReadToEndAsync(); + var stderr = child.StandardError.ReadToEndAsync(); + failedDelivery = await firstResponse; + await child.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30)); + Assert.True(child.ExitCode == 0, await stderr); + Assert.Contains("applied", await stdout); + } + finally + { + if (!child.HasExited) { child.Kill(entireProcessTree: true); child.WaitForExit(); } + } + using (var db = new SqliteConnection($"Data Source={Path.Combine(queue, "ordered-reports.db")};Mode=ReadOnly;Pooling=False")) + { + db.Open(); + using var command = db.CreateCommand(); + command.CommandText = "SELECT payload FROM outbox ORDER BY id;"; + using var records = command.ExecuteReader(); + Assert.True(records.Read()); + Assert.Equal(failedDelivery, records.GetString(0)); + Assert.False(records.Read()); + } + + var secondResponse = RespondAsync(200); + string replay; + using (var restarted = StartProbe("attempt-replay-ordered", queue, url)) + try + { + var stdout = restarted.StandardOutput.ReadToEndAsync(); + var stderr = restarted.StandardError.ReadToEndAsync(); + replay = await secondResponse; + await restarted.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30)); + Assert.True(restarted.ExitCode == 0, await stderr); + Assert.Contains("replayed", await stdout); + } + finally + { + if (!restarted.HasExited) { restarted.Kill(entireProcessTree: true); restarted.WaitForExit(); } + } + Assert.Equal(failedDelivery, replay); + using var document = JsonDocument.Parse(replay); + var report = document.RootElement; + Assert.Equal(303, report.GetProperty("recordId").GetInt32()); + Assert.Equal(2, report.GetProperty("type").GetInt32()); + Assert.Equal((int)UpdateStatus.Failure, report.GetProperty("status").GetInt32()); + Assert.Equal((int)FailureCategory.Extract, report.GetProperty("category").GetInt32()); + Assert.Equal("Extract", report.GetProperty("phase").GetString()); + Assert.Equal(1, report.GetProperty("sequence").GetInt64()); + Assert.NotEqual(Guid.Empty, report.GetProperty("eventId").GetGuid()); + using var reopened = new SqliteConnection($"Data Source={Path.Combine(queue, "ordered-reports.db")};Mode=ReadOnly;Pooling=False"); + reopened.Open(); + using var pending = reopened.CreateCommand(); + pending.CommandText = "SELECT COUNT(*) FROM outbox;"; + Assert.Equal(0L, (long)pending.ExecuteScalar()!); + } + [Fact] public void Competing_process_claims_are_fenced_and_stale_claim_cannot_complete() { @@ -501,6 +608,7 @@ private static void ConfigureProbeTemp(ProcessStartInfo start, string tempRoot) { start.EnvironmentVariables["TEMP"] = tempRoot; start.EnvironmentVariables["TMP"] = tempRoot; + start.EnvironmentVariables["TMPDIR"] = tempRoot; } private DurableUpdateAttemptStore CreateBoundAttempt(string installPath, string sourcePath, out Guid attemptId) diff --git a/tests/CoreTest/Strategy/FailureReportingTests.cs b/tests/CoreTest/Strategy/FailureReportingTests.cs new file mode 100644 index 00000000..0eda27c1 --- /dev/null +++ b/tests/CoreTest/Strategy/FailureReportingTests.cs @@ -0,0 +1,308 @@ +using System.Net; +using System.IO.Compression; +using System.Security.Cryptography; +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); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task RealFallback_CoveredChainCannotOverwriteFailureOrReportDurableSuccess(bool durable) + { + var packages = Path.Combine(_root, "packages"); + var install = Path.Combine(_root, "install"); + Directory.CreateDirectory(packages); + Directory.CreateDirectory(install); + var corrupt = Path.Combine(packages, "broken.zip"); + await File.WriteAllTextAsync(corrupt, "not a zip"); + var full = Path.Combine(packages, "full.zip"); + using (var archive = ZipFile.Open(full, ZipArchiveMode.Create)) + using (var writer = new StreamWriter(archive.CreateEntry("applied.txt").Open())) + writer.Write("fallback applied"); + static string Hash(string path) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))); + + var reporter = new RecordingReporter(); + var context = NewContext(); + context.InstallPath = install; + context.TempPath = packages; + context.ReportType = 2; + context.DurableUpdateAttemptId = durable ? Guid.NewGuid() : null; + context.DisableLegacyRollback = durable; + context.UpdateVersions = new() + { + new() { Name = "broken", Version = "1.5.0", RecordId = 303, AppType = (int)AppType.Client, + PackageType = (int)PackageType.Full, Hash = Hash(corrupt) }, + new() { Name = "missing-chain", Version = "2.0.0", RecordId = 101, AppType = (int)AppType.Upgrade, + PackageType = (int)PackageType.Chain, FallbackFullName = "full", + FallbackFullVersion = "3.0.0", FallbackFullHash = Hash(full) }, + new() { Name = "covered", Version = "2.5.0", RecordId = 303, AppType = (int)AppType.Client, + PackageType = (int)PackageType.Chain }, + new() { Name = "also-covered", Version = "3.0.0", RecordId = 404, AppType = (int)AppType.Upgrade, + PackageType = (int)PackageType.Chain } + }; + var platform = new WindowsStrategy { Reporter = reporter }; + platform.Create(context); + + await platform.ExecuteAsync(); + + Assert.Equal("fallback applied", await File.ReadAllTextAsync(Path.Combine(install, "applied.txt"))); + var failure = Assert.Single(reporter.Reports.Where(r => r.RecordId == 303)); + Assert.Equal((int)UpdateStatus.Failure, failure.Status); + Assert.Equal(2, failure.Type); + Assert.Equal(FailureCategory.Extract, failure.Category); + if (durable) + Assert.DoesNotContain(reporter.Reports, r => r.Status == (int)UpdateStatus.Success); + else + Assert.Equal(new[] { 101, 404 }, reporter.Reports.Where(r => r.Status == (int)UpdateStatus.Success) + .Select(r => r.RecordId)); + } + + [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); + } +} 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); + } +} diff --git a/tests/ReportWorker/Program.cs b/tests/ReportWorker/Program.cs new file mode 100644 index 00000000..efd1a059 --- /dev/null +++ b/tests/ReportWorker/Program.cs @@ -0,0 +1,45 @@ +using System.Net; +using System.Text.Json; +using GeneralUpdate.Core.Download.Reporting; + +namespace ReportWorker; + +public sealed class Marker; + +internal static class Program +{ + private static async Task Main(string[] args) + { + if (args.Length != 2) return 2; + using var client = new HttpClient(new Handler(args[1])); + var reporter = new OrderedUpdateReporter(args[0], client, "https://example.test/report", "tenant/database", true); + try + { + await reporter.ReportAsync(new UpdateReport(10, 3)); + } + catch (HttpRequestException) + { + return 0; + } + return 0; + } + + private sealed class Handler(string mode) : HttpMessageHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token) + { + using var json = JsonDocument.Parse(await request.Content!.ReadAsStringAsync(token)); + if (json.RootElement.GetProperty("eventId").GetGuid() == Guid.Empty || + json.RootElement.GetProperty("sequence").GetInt64() <= 0) + throw new InvalidDataException("Invalid ordered report."); + if (mode == "hold") + { + Console.WriteLine("committed"); + await Console.Out.FlushAsync(); + await Task.Delay(Timeout.InfiniteTimeSpan, token); + } + if (mode == "offline") throw new HttpRequestException("offline"); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{\"code\":200,\"body\":true}") }; + } + } +} diff --git a/tests/ReportWorker/ReportWorker.csproj b/tests/ReportWorker/ReportWorker.csproj new file mode 100644 index 00000000..601478a7 --- /dev/null +++ b/tests/ReportWorker/ReportWorker.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + enable + enable + + + + + diff --git a/tests/StartupHealthProbe/Program.cs b/tests/StartupHealthProbe/Program.cs index a8741e92..a607805e 100644 --- a/tests/StartupHealthProbe/Program.cs +++ b/tests/StartupHealthProbe/Program.cs @@ -7,6 +7,32 @@ using System.Diagnostics; using System.Reflection; +if (args.Length == 3 && args[0] == "attempt-apply-ordered") +{ + var bootstrap = new GeneralUpdateBootstrap(); + var context = (UpdateContext)typeof(GeneralUpdateBootstrap) + .GetField("_configInfo", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(bootstrap)!; + context.LaunchClientAfterUpdate = false; + using var client = new HttpClient(); + var strategy = new UpdateStrategy + { + Reporter = new OrderedUpdateReporter(args[1], client, args[2], "test-tenant/database", true) + }; + strategy.Create(context); + await strategy.ExecuteAsync(); + Console.WriteLine("applied"); + return; +} + +if (args.Length == 3 && args[0] == "attempt-replay-ordered") +{ + using var client = new HttpClient(); + await new OrderedUpdateReporter(args[1], client, args[2], "test-tenant/database", true).ReplayAsync(); + Console.WriteLine("replayed"); + return; +} + if (args.Length == 1 && args[0] == "attempt-contract") { try