From f1618368d4763f91629705e2d03fd59b26f30379 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Mon, 23 Nov 2026 08:33:08 +0800 Subject: [PATCH] Add default-off standalone diagnostic outbox host Replay cooperative cases on startup, retry scans independently of upgrades, and expose cancellation and errors without inferred attempt association. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/diagnostic-outbox.yml | 34 +++ docs/diagnostic-artifact-transport.md | 104 +++++++- .../Diagnostics/DiagnosticOutboxConsumer.cs | 2 +- .../Diagnostics/DiagnosticOutboxHost.cs | 169 +++++++++++++ .../GeneralUpdate.Diagnostics.Host.csproj | 14 ++ src/GeneralUpdate.Diagnostics.Host/Program.cs | 62 +++++ .../DiagnosticOutboxConsumerTests.cs | 232 ++++++++++++++++++ tests/OutboxAotSmoke/Program.cs | 21 +- 8 files changed, 634 insertions(+), 4 deletions(-) create mode 100644 src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxHost.cs create mode 100644 src/GeneralUpdate.Diagnostics.Host/GeneralUpdate.Diagnostics.Host.csproj create mode 100644 src/GeneralUpdate.Diagnostics.Host/Program.cs diff --git a/.github/workflows/diagnostic-outbox.yml b/.github/workflows/diagnostic-outbox.yml index beafb65d..4da476e5 100644 --- a/.github/workflows/diagnostic-outbox.yml +++ b/.github/workflows/diagnostic-outbox.yml @@ -27,6 +27,40 @@ jobs: run: dotnet test tests/CoreTest/CoreTest.csproj -c Release --filter FullyQualifiedName~Diagnostics - name: Build integration harness run: dotnet build tests/OutboxConsumerHarness/OutboxConsumerHarness.csproj -c Release + - name: Build all compatible Core targets + run: dotnet build src/GeneralUpdate.Core/GeneralUpdate.Core.csproj -c Release + - name: Publish standalone Native AOT host + run: dotnet publish src/GeneralUpdate.Diagnostics.Host/GeneralUpdate.Diagnostics.Host.csproj -c Release -r ${{ matrix.rid }} -o diagnostic-host-aot + - name: Run default-off host (Windows) + if: runner.os == 'Windows' + run: ./diagnostic-host-aot/GeneralUpdate.Diagnostics.Host.exe + - name: Run default-off host (Linux) + if: runner.os == 'Linux' + run: ./diagnostic-host-aot/GeneralUpdate.Diagnostics.Host + - name: Run enabled native host lifecycle (Linux) + if: runner.os == 'Linux' + shell: bash + run: | + root=$(mktemp -d) + export GENERALUPDATE_DIAGNOSTICS_ENABLED=true + export GENERALUPDATE_DIAGNOSTICS_TENANT=ci-tenant + export GENERALUPDATE_DIAGNOSTICS_APP_KEY=ci-app + export GENERALUPDATE_DIAGNOSTICS_SCAN_SECONDS=0.1 + ./diagnostic-host-aot/GeneralUpdate.Diagnostics.Host "$root" https://localhost:1/Fault/UploadArtifact > "$root/host.log" 2> "$root/error.log" & + pid=$! + trap 'kill -TERM "$pid" 2>/dev/null || true' EXIT + for i in {1..100}; do + if grep -q ScanCompleted "$root/host.log"; then break; fi + sleep 0.1 + done + grep -q ScanCompleted "$root/host.log" + kill -TERM "$pid" + wait "$pid" + grep -q Stopped "$root/host.log" + test ! -s "$root/error.log" + rm "$root/host.log" "$root/error.log" + rmdir "$root" + trap - EXIT - name: Publish Native AOT smoke run: dotnet publish tests/OutboxAotSmoke/OutboxAotSmoke.csproj -c Release -r ${{ matrix.rid }} -o outbox-aot - name: Run Native AOT smoke (Windows) diff --git a/docs/diagnostic-artifact-transport.md b/docs/diagnostic-artifact-transport.md index b3f51627..94b4a1e5 100644 --- a/docs/diagnostic-artifact-transport.md +++ b/docs/diagnostic-artifact-transport.md @@ -3,7 +3,8 @@ `ArtifactUploadClient` is an opt-in transport for an already prepared Bowl schema 2 crash ZIP. `DiagnosticOutboxConsumer` separately implements the cooperative Bowl `outboxProtocol: 1` case lifecycle. Neither component is integrated into -`LaunchAsync`; the host explicitly schedules and retries cases. +`LaunchAsync`. The default-off standalone `GeneralUpdate.Diagnostics.Host` +now schedules startup replay and periodic retries independently of upgrades. The host must provide a stable ZIP snapshot, `manifest.json` at its root, and matching metadata. Retain the **same ZIP bytes** for retries, including after a @@ -76,6 +77,107 @@ during deletion cannot trigger a regenerated upload. The host must also enumerat the same stripe lock. Tombstones count against Bowl's admission limits until removed; a cleanup failure can therefore cause exit-code-only degradation. +## Standalone host (default off) + +Publish the executable separately from the application and upgrade worker. It +must not be a download/pipeline hook or a child whose completion is awaited by +`LaunchAsync`. Existing update APIs, reports, hooks and IPC are unchanged. A +supervisor starts the diagnostic process after consent/configuration deployment +and restarts it when it exits unexpectedly; Windows service integration is the +supervisor's responsibility (this is a foreground executable, not a Windows +Service). Use .NET 10 for managed deployment, or publish its Native AOT binary: + +```powershell +dotnet publish src\GeneralUpdate.Diagnostics.Host -c Release -r win-x64 -o diagnostic-host +# Environment values must come from trusted deployment configuration, never a case manifest. +$env:GENERALUPDATE_DIAGNOSTICS_ENABLED = 'true' +$env:GENERALUPDATE_DIAGNOSTICS_TENANT = 'configured-tenant' +$env:GENERALUPDATE_DIAGNOSTICS_APP_KEY = 'configured-app' +$env:GENERALUPDATE_DIAGNOSTICS_SCAN_SECONDS = '60' +$env:GENERALUPDATE_DIAGNOSTICS_UPLOAD_SECONDS = '30' +.\diagnostic-host\GeneralUpdate.Diagnostics.Host.exe ` + 'C:\application\fail' 'https://gateway.example/Fault/UploadArtifact' +``` + +Unset or `false` enablement exits successfully with `Disabled` without checking +arguments, touching the outbox, or making HTTP requests. Any other enablement +value is a configuration error. Enabled mode requires an explicit root, HTTPS +endpoint, nonempty tenant and app key. Scan interval is 0.1 seconds through one +day; upload timeout is positive and at most two minutes. Numeric environment +values use invariant decimal seconds. Options are copied at construction, not +read from evidence. The executable rejects redirects, disables proxies, and uses +normal system TLS trust; it has no certificate-validation bypass. Install the +deployment CA in the OS trust store and secure/authenticate the gateway. + +On startup it immediately enumerates version/GUID directories, skips `.locks` +and non-case names, and finishes confirmed tombstones under their stripe lock. +It scans serially, with a full configured interval after each scan, so scans +never overlap and each case has at most one attempt per scan. Recoverable disk, +manifest, HTTP and upload-timeout errors are reported per case/directory and +preserve evidence; malformed cases do not prevent other cases being processed. +A missing root is reported and retried, not created automatically. Directory +chains are checked for links/reparse points before enumeration and consumption; +streaming enumeration checks cancellation between entries. An inaccessible or +changed directory can defer the rest of that directory to the next scan. The +same private-local-filesystem/ACL and protocol-1 deployment prerequisites apply; +these checks do not defeat a hostile local writer racing path replacement. +Legacy unmarked cases remain skipped: the executable offers no legacy override. + +`Started`, `ScanStarted`, `ScanCompleted`, `ConfirmedAndDeleted`, +`TombstoneDeleted`, `Deferred` and `Stopped` are timestamped on stdout; errors +include exception type and message on stderr. Paths/messages may contain +sensitive information: protect and retain these logs appropriately. `Deferred` +means busy, incomplete, unmarked or unconfirmed, not success. A failed scan will +still emit `ScanCompleted`; inspect `Error` events, not that marker alone. +Configuration/unexpected process errors exit 1; ordinary scan errors keep +retrying. Ctrl+C and Unix SIGTERM cancel the scan/upload and emit `Stopped`; +supervisors must allow the handler to finish before force-killing. Force-kill +releases OS locks, and next startup replays persisted snapshots/tombstones. +Cancellation cannot interrupt a synchronous filesystem operation or a broken +HTTP handler that ignores its token; shutdown grace must account for this. + +Applications with their own long-lived process can instead explicitly construct +`DiagnosticOutboxHost(options, observer, httpClient)` and retain the task from +`StartAsync(shutdownToken)`. `StartAsync` queues work and returns immediately; +await that task only at host shutdown, not in the upgrade lifecycle. The caller +owns the HTTP client and policies and must keep it alive until completion. +Observer callbacks must be quick and thread-safe. Observer failures and +unexpected faults fail the completion task, so callers must observe it. Host +cancellation completes normally; upload timeout is an observable case error. +Do not dynamically change tenant/app/endpoint for an existing outbox. + +### No inferred attempt association + +Core's version-response/report `RecordId` and IPC do **not** provide a durable +mapping to a Bowl case. `BowlContext` and schema-2 manifests provide no trustworthy +attempt record. Consequently this host sends no `RecordId`/`RecordType`, never +reports an upgrade failure, and does not associate an arbitrary crash with an +upgrade or push. Tenant/app configuration identifies the upload destination, +not a particular attempt. + +Only opt in for a dedicated outbox whose ordinary crashes may be uploaded +**without association**. If a deployment requires attempt association, leave +this host disabled for that outbox until a trusted, persistent binding exists +and is fixed before first send. GeneralSpace's duplicate-GUID path checks tenant +and ZIP hash, but does not add or repair record/AppKey associations later; a +successful unassociated first upload cannot be repaired by retrying it with +record fields. Do not fabricate a record from version, current/latest attempt, +process environment, or untrusted manifest data. This PR deliberately does not +implement a record-context API in the absence of a trustworthy source. + +### Verification boundary + +Diagnostic unit tests cover startup replay, periodic discovery/retry, missing +root recovery, per-case errors, timeout/cancellation, another process holding the +stripe, trusted configuration, no record fields, and tombstone recovery. Native +AOT smoke covers the scheduler and consumer; CI publishes the production host +on Windows and Linux. These use local fixtures/mock HTTP and are **not** evidence +of real Bowl watchdog/dump capture or a deployed GeneralSpace service. +The cross-repository follow-up reuses GeneralSpace #326's +`diagnostic-three-repo.yml`/`eng/diagnostic-three-repo.py` with exact source SHAs +and must separately report real writer/API verification versus complete +watchdog/dump coverage. + The lock is `{fail}/.locks/{first two lowercase GUID hex characters}.lock`, opened with `FileShare.None` and never deleted. It remains held through snapshot, upload and cleanup. The required upload timeout is at most two minutes; the HTTP diff --git a/src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxConsumer.cs b/src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxConsumer.cs index aec513eb..d99e9edb 100644 --- a/src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxConsumer.cs +++ b/src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxConsumer.cs @@ -290,7 +290,7 @@ private static void RejectLinkIfExists(string path) throw new InvalidDataException("Outbox links and reparse points are not allowed."); } - private static void CheckDirectoryChain(string path) + internal static void CheckDirectoryChain(string path) { var current = new DirectoryInfo(path); while (current != null) diff --git a/src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxHost.cs b/src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxHost.cs new file mode 100644 index 00000000..c3ee04cf --- /dev/null +++ b/src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxHost.cs @@ -0,0 +1,169 @@ +using System; +using System.IO; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace GeneralUpdate.Core.Diagnostics; + +/// Explicit configuration for a standalone diagnostic scheduler, disabled by default. +public sealed class DiagnosticOutboxHostOptions +{ + public bool Enabled { get; set; } + public string FailDirectory { get; set; } = string.Empty; + public Uri? Endpoint { get; set; } + public string TenantId { get; set; } = string.Empty; + public string AppKey { get; set; } = string.Empty; + public TimeSpan ScanInterval { get; set; } = TimeSpan.FromMinutes(1); + public TimeSpan UploadTimeout { get; set; } = TimeSpan.FromSeconds(30); +} + +public enum DiagnosticOutboxHostStatus +{ + Disabled, Started, ScanStarted, ConfirmedAndDeleted, TombstoneDeleted, + Deferred, Error, ScanCompleted, Stopped +} + +/// Scheduler notifications never report update success or failure. +public sealed class DiagnosticOutboxHostEvent +{ + internal DiagnosticOutboxHostEvent(DiagnosticOutboxHostStatus status, string? path = null, Exception? error = null) + { + Status = status; + Path = path; + Error = error; + } + + public DiagnosticOutboxHostStatus Status { get; } + public string? Path { get; } + public Exception? Error { get; } +} + +/// +/// Replays on startup and scans periodically without running on the caller's update thread. +/// The caller owns HTTP policies, cancellation, notifications and the returned completion task. +/// +public sealed class DiagnosticOutboxHost +{ + private const string TombstonePrefix = ".generalupdate-uploaded-"; + private readonly string _root; + private readonly TimeSpan _interval; + private readonly DiagnosticOutboxConsumer? _consumer; + private readonly Action _notify; + private int _started; + + public DiagnosticOutboxHost(DiagnosticOutboxHostOptions options, + Action notify, HttpClient? httpClient = null) + { + if (options == null) throw new ArgumentNullException(nameof(options)); + _notify = notify ?? throw new ArgumentNullException(nameof(notify)); + _root = string.Empty; + _interval = options.ScanInterval; + if (!options.Enabled) return; + if (_interval < TimeSpan.FromMilliseconds(100) || _interval > TimeSpan.FromDays(1)) + throw new ArgumentOutOfRangeException(nameof(options.ScanInterval)); + if (httpClient == null) throw new ArgumentNullException(nameof(httpClient)); + var upload = new ArtifactUploadClient(httpClient, + options.Endpoint ?? throw new ArgumentException("An explicit endpoint is required.", nameof(options)), + options.TenantId, options.AppKey); + _consumer = new DiagnosticOutboxConsumer(options.FailDirectory, upload, options.UploadTimeout); + _root = Path.GetFullPath(options.FailDirectory); + } + + /// + /// Starts once and returns immediately. Await the task at shutdown; observer exceptions + /// and unexpected scheduler faults propagate through it. Expected case errors are notified. + /// + public Task StartAsync(CancellationToken cancellationToken = default) + { + if (Interlocked.Exchange(ref _started, 1) != 0) + throw new InvalidOperationException("The diagnostic host has already been started."); + return Task.Run(() => RunAsync(cancellationToken)); + } + + private async Task RunAsync(CancellationToken token) + { + if (_consumer == null) + { + Report(DiagnosticOutboxHostStatus.Disabled); + return; + } + Report(DiagnosticOutboxHostStatus.Started); + try + { + while (true) + { + token.ThrowIfCancellationRequested(); + Report(DiagnosticOutboxHostStatus.ScanStarted); + try { await ScanAsync(token).ConfigureAwait(false); } + catch (Exception error) when (IsRecoverable(error, token)) + { + Report(DiagnosticOutboxHostStatus.Error, _root, error); + } + Report(DiagnosticOutboxHostStatus.ScanCompleted); + await Task.Delay(_interval, token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + // Host cancellation is normal shutdown, not an update failure. + } + finally { Report(DiagnosticOutboxHostStatus.Stopped); } + } + + private async Task ScanAsync(CancellationToken token) + { + DiagnosticOutboxConsumer.CheckDirectoryChain(_root); + foreach (var versionPath in Directory.EnumerateDirectories(_root)) + { + token.ThrowIfCancellationRequested(); + var version = Path.GetFileName(versionPath); + if (version.Equals(".locks", StringComparison.OrdinalIgnoreCase)) continue; + try + { + DiagnosticOutboxConsumer.CheckDirectoryChain(versionPath); + foreach (var casePath in Directory.EnumerateDirectories(versionPath)) + { + token.ThrowIfCancellationRequested(); + var name = Path.GetFileName(casePath); + var tombstone = name.StartsWith(TombstonePrefix, StringComparison.Ordinal); + var id = tombstone ? name.Substring(TombstonePrefix.Length) : name; + if (!Guid.TryParseExact(id, "D", out _)) continue; + try + { + DiagnosticOutboxConsumer.CheckDirectoryChain(casePath); + var deleted = tombstone + ? _consumer!.CleanupConfirmedCase(version, id) + : await _consumer!.ProcessCaseAsync(version, id, token).ConfigureAwait(false); + Report(deleted + ? (tombstone ? DiagnosticOutboxHostStatus.TombstoneDeleted : DiagnosticOutboxHostStatus.ConfirmedAndDeleted) + : DiagnosticOutboxHostStatus.Deferred, casePath); + } + catch (Exception error) when (IsRecoverable(error, token)) + { + Report(DiagnosticOutboxHostStatus.Error, casePath, error); + } + } + } + catch (Exception error) when (IsRecoverable(error, token)) + { + Report(DiagnosticOutboxHostStatus.Error, versionPath, error); + } + } + } + + private static bool IsRecoverable(Exception error, CancellationToken token) => + error is IOException || error is InvalidDataException || error is UnauthorizedAccessException || + error is ArgumentException || error is JsonException || error is HttpRequestException || + error is OperationCanceledException && !token.IsCancellationRequested; + + private void Report(DiagnosticOutboxHostStatus status, string? path = null, Exception? error = null) + { + try { _notify(new DiagnosticOutboxHostEvent(status, path, error)); } + catch (Exception observerError) + { + throw new InvalidOperationException("The diagnostic host observer failed.", observerError); + } + } +} diff --git a/src/GeneralUpdate.Diagnostics.Host/GeneralUpdate.Diagnostics.Host.csproj b/src/GeneralUpdate.Diagnostics.Host/GeneralUpdate.Diagnostics.Host.csproj new file mode 100644 index 00000000..8fcb55cb --- /dev/null +++ b/src/GeneralUpdate.Diagnostics.Host/GeneralUpdate.Diagnostics.Host.csproj @@ -0,0 +1,14 @@ + + + Exe + net10.0 + enable + enable + true + true + true + + + + + diff --git a/src/GeneralUpdate.Diagnostics.Host/Program.cs b/src/GeneralUpdate.Diagnostics.Host/Program.cs new file mode 100644 index 00000000..307f451b --- /dev/null +++ b/src/GeneralUpdate.Diagnostics.Host/Program.cs @@ -0,0 +1,62 @@ +using System.Globalization; +using System.Runtime.InteropServices; +using GeneralUpdate.Core.Diagnostics; + +try +{ + var enabled = Environment.GetEnvironmentVariable("GENERALUPDATE_DIAGNOSTICS_ENABLED"); + if (enabled == null || enabled.Equals("false", StringComparison.OrdinalIgnoreCase)) + { + Console.WriteLine("Disabled"); + return 0; + } + if (!enabled.Equals("true", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("GENERALUPDATE_DIAGNOSTICS_ENABLED must be true or false."); + if (args.Length != 2) + throw new ArgumentException("Usage: GeneralUpdate.Diagnostics.Host "); + + var options = new DiagnosticOutboxHostOptions + { + Enabled = true, + FailDirectory = args[0], + Endpoint = new Uri(args[1], UriKind.Absolute), + TenantId = Environment.GetEnvironmentVariable("GENERALUPDATE_DIAGNOSTICS_TENANT") ?? string.Empty, + AppKey = Environment.GetEnvironmentVariable("GENERALUPDATE_DIAGNOSTICS_APP_KEY") ?? string.Empty, + ScanInterval = Seconds("GENERALUPDATE_DIAGNOSTICS_SCAN_SECONDS", 60), + UploadTimeout = Seconds("GENERALUPDATE_DIAGNOSTICS_UPLOAD_SECONDS", 30) + }; + using var stop = new CancellationTokenSource(); + using var terminate = OperatingSystem.IsWindows() ? null : + PosixSignalRegistration.Create(PosixSignal.SIGTERM, context => { context.Cancel = true; stop.Cancel(); }); + ConsoleCancelEventHandler cancel = (_, e) => { e.Cancel = true; stop.Cancel(); }; + Console.CancelKeyPress += cancel; + try + { + using var handler = new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false }; + using var http = new HttpClient(handler) { Timeout = Timeout.InfiniteTimeSpan }; + var host = new DiagnosticOutboxHost(options, e => + { + var line = $"{DateTimeOffset.UtcNow:O} {e.Status} {e.Path}"; + if (e.Error == null) Console.WriteLine(line); + else Console.Error.WriteLine($"{line} {e.Error.GetType().Name}: {e.Error.Message}"); + }, http); + await host.StartAsync(stop.Token); + return 0; + } + finally { Console.CancelKeyPress -= cancel; } +} +catch (Exception error) +{ + Console.Error.WriteLine($"{error.GetType().Name}: {error.Message}"); + return 1; +} + +static TimeSpan Seconds(string variable, int fallback) +{ + var text = Environment.GetEnvironmentVariable(variable); + if (text == null) return TimeSpan.FromSeconds(fallback); + if (!double.TryParse(text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var seconds) || + double.IsNaN(seconds) || double.IsInfinity(seconds) || seconds <= 0 || seconds > 86400) + throw new ArgumentException($"{variable} must be a positive number of seconds no greater than 86400."); + return TimeSpan.FromSeconds(seconds); +} diff --git a/tests/CoreTest/Diagnostics/DiagnosticOutboxConsumerTests.cs b/tests/CoreTest/Diagnostics/DiagnosticOutboxConsumerTests.cs index 88446f7d..4d02d922 100644 --- a/tests/CoreTest/Diagnostics/DiagnosticOutboxConsumerTests.cs +++ b/tests/CoreTest/Diagnostics/DiagnosticOutboxConsumerTests.cs @@ -140,6 +140,8 @@ public async Task TimeoutKeepsSnapshotAndReleasesLock() public async Task AnotherProcessHoldingStripeMakesConsumerSkip() { CreateCase(); + var tombstone = Path.Combine(_root, "2.0", ".generalupdate-uploaded-" + Id); + Directory.CreateDirectory(tombstone); Directory.CreateDirectory(Path.Combine(_root, ".locks")); var path = Path.Combine(_root, ".locks", "86.lock"); var start = new ProcessStartInfo @@ -162,6 +164,15 @@ public async Task AnotherProcessHoldingStripeMakesConsumerSkip() Assert.Equal("ready", await process.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(15))); using var blockedHttp = Http((_, _) => throw new Exception("Unexpected upload")); Assert.False(await Consumer(blockedHttp).ProcessCaseAsync("1.0", Id)); + using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + var events = new List(); + await Host(blockedHttp, e => + { + events.Add(e); + if (e.Status == DiagnosticOutboxHostStatus.ScanCompleted) stop.Cancel(); + }).StartAsync(stop.Token); + Assert.Contains(events, e => e.Status == DiagnosticOutboxHostStatus.Deferred); + Assert.True(Directory.Exists(tombstone)); Assert.True(Directory.Exists(CasePath)); } finally @@ -178,6 +189,9 @@ public async Task AnotherProcessHoldingStripeMakesConsumerSkip() }); Assert.True(await Consumer(http).ProcessCaseAsync("1.0", Id)); Assert.False(Directory.Exists(CasePath)); + var recovered = await ScanOnce(http); + Assert.Contains(recovered, e => e.Status == DiagnosticOutboxHostStatus.TombstoneDeleted); + Assert.False(Directory.Exists(tombstone)); } [Fact] @@ -195,6 +209,224 @@ public void ConfirmedTombstoneCanBeCleanedWithoutTouchingPendingCase() Assert.False(consumer.CleanupConfirmedCase("1.0", Id)); } + [Fact] + public async Task DisabledHostDoesNotRequireConfigurationOrTouchDiskOrNetwork() + { + using var http = Http((_, _) => throw new Exception("Unexpected upload")); + var events = new List(); + var host = new DiagnosticOutboxHost(new DiagnosticOutboxHostOptions + { + FailDirectory = _root, ScanInterval = TimeSpan.Zero, UploadTimeout = TimeSpan.Zero + }, events.Add, http); + await host.StartAsync(); + Assert.False(Directory.Exists(_root)); + Assert.Equal(DiagnosticOutboxHostStatus.Disabled, Assert.Single(events).Status); + Assert.Throws(() => { _ = host.StartAsync(); }); + } + + [Theory] + [InlineData("endpoint")] + [InlineData("tenant")] + [InlineData("app")] + [InlineData("http")] + [InlineData("interval")] + [InlineData("timeout")] + public void EnabledHostRequiresExplicitTrustedConfiguration(string missing) + { + using var http = Http((_, _) => throw new Exception("Unexpected upload")); + var options = HostOptions(); + switch (missing) + { + case "endpoint": options.Endpoint = null; break; + case "tenant": options.TenantId = ""; break; + case "app": options.AppKey = ""; break; + case "interval": options.ScanInterval = TimeSpan.Zero; break; + case "timeout": options.UploadTimeout = TimeSpan.FromMinutes(3); break; + } + Assert.ThrowsAny(() => + new DiagnosticOutboxHost(options, _ => { }, missing == "http" ? null : http)); + Assert.False(Directory.Exists(_root)); + } + + [Fact] + public async Task StartupReplayPreservesBytesAcrossHostRestartAndDoesNotAttributeCrash() + { + CreateCase(); + var attempts = new List(); + using var http = Http(async (request, _) => + { + Assert.Equal("tenant", Assert.Single(request.Headers.GetValues("X-Tenant-Id"))); + var form = (MultipartFormDataContent)request.Content!; + Assert.DoesNotContain(form, p => p.Headers.ContentDisposition!.Name is "RecordId" or "RecordType"); + Assert.Equal("app", await form.Single(p => p.Headers.ContentDisposition!.Name == "AppKey").ReadAsStringAsync()); + var bytes = await form.Single(p => p.Headers.ContentDisposition!.Name == "file").ReadAsByteArrayAsync(); + attempts.Add(bytes); + return attempts.Count == 1 ? new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) : + Response(Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant()); + }); + var first = await ScanOnce(http); + Assert.Contains(first, e => e.Status == DiagnosticOutboxHostStatus.Error && e.Error is HttpRequestException); + Assert.True(Directory.Exists(CasePath)); + var second = await ScanOnce(http); + Assert.Contains(second, e => e.Status == DiagnosticOutboxHostStatus.ConfirmedAndDeleted); + Assert.False(Directory.Exists(CasePath)); + Assert.Equal(2, attempts.Count); + Assert.Equal(attempts[0], attempts[1]); + } + + [Fact] + public async Task PeriodicScanFindsNewCaseAndRetriesUnconfirmedSnapshot() + { + Directory.CreateDirectory(_root); + var attempts = 0; + var scans = 0; + using var http = Http(async (request, _) => + { + var file = ((MultipartFormDataContent)request.Content!).Single(p => p.Headers.ContentDisposition!.Name == "file"); + var bytes = await file.ReadAsByteArrayAsync(); + return Response(++attempts == 1 ? null : Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant()); + }); + using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + var events = new List(); + var host = Host(http, e => + { + events.Add(e); + if (e.Status != DiagnosticOutboxHostStatus.ScanCompleted) return; + if (++scans == 1) CreateCase(); + if (scans == 3) stop.Cancel(); + }); + await host.StartAsync(stop.Token); + Assert.Equal(3, scans); + Assert.Equal(2, attempts); + Assert.Contains(events, e => e.Status == DiagnosticOutboxHostStatus.Deferred); + Assert.False(Directory.Exists(CasePath)); + } + + [Fact] + public async Task TombstoneRecoveryAndInvalidCaseAreIsolated() + { + CreateCase(); + File.WriteAllText(Path.Combine(CasePath, "manifest.json"), "invalid"); + var tombstone = Path.Combine(_root, "2.0", ".generalupdate-uploaded-" + Id); + Directory.CreateDirectory(tombstone); + File.WriteAllText(Path.Combine(tombstone, "remaining.txt"), "confirmed"); + using var http = Http((_, _) => throw new Exception("Unexpected upload")); + var events = await ScanOnce(http); + Assert.Contains(events, e => e.Status == DiagnosticOutboxHostStatus.Error && e.Path == CasePath); + Assert.Contains(events, e => e.Status == DiagnosticOutboxHostStatus.TombstoneDeleted); + Assert.True(Directory.Exists(CasePath)); + Assert.False(Directory.Exists(tombstone)); + } + + [Fact] + public async Task MissingRootIsObservableAndRecoveredOnNextScan() + { + using var http = Http((_, _) => throw new Exception("Unexpected upload")); + using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + var scans = 0; + var events = new List(); + await Host(http, e => + { + events.Add(e); + if (e.Status != DiagnosticOutboxHostStatus.ScanCompleted) return; + if (++scans == 1) Directory.CreateDirectory(_root); + else stop.Cancel(); + }).StartAsync(stop.Token); + Assert.Equal(2, scans); + Assert.Single(events, e => e.Status == DiagnosticOutboxHostStatus.Error); + } + + [Fact] + public async Task CancellationStopsInFlightUploadWithoutBlockingStartOrDeletingEvidence() + { + CreateCase(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var http = Http(async (_, token) => + { + entered.SetResult(); + await Task.Delay(Timeout.InfiniteTimeSpan, token); + throw new Exception("Unexpected upload completion"); + }); + using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + var events = new List(); + var completion = Host(http, events.Add).StartAsync(stop.Token); + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.False(completion.IsCompleted); + stop.Cancel(); + await completion.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal(DiagnosticOutboxHostStatus.Stopped, events.Last().Status); + Assert.DoesNotContain(events, e => e.Status == DiagnosticOutboxHostStatus.Error); + Assert.True(Directory.Exists(CasePath)); + using var stripe = new FileStream(Path.Combine(_root, ".locks", "86.lock"), FileMode.Open, FileAccess.ReadWrite, FileShare.None); + } + + [Fact] + public async Task UploadTimeoutIsObservableAndRetainsEvidence() + { + CreateCase(); + using var http = Http(async (_, token) => + { + await Task.Delay(Timeout.InfiniteTimeSpan, token); + throw new Exception("Unexpected upload completion"); + }); + var options = HostOptions(); + options.UploadTimeout = TimeSpan.FromMilliseconds(100); + var events = await ScanOnce(http, options); + Assert.Contains(events, e => e.Status == DiagnosticOutboxHostStatus.Error && e.Error is OperationCanceledException); + Assert.True(Directory.Exists(CasePath)); + } + + [Fact] + public async Task UnsafeVersionAndCaseLinksAreNotFollowed() + { + if (OperatingSystem.IsWindows()) return; // Windows symlink creation requires deployment-specific privileges. + CreateCase(); + var external = Path.Combine(_root, "external"); + Directory.CreateDirectory(external); + var sentinel = Path.Combine(external, "sentinel"); + File.WriteAllText(sentinel, "preserve"); + Directory.CreateSymbolicLink(Path.Combine(_root, "linked-version"), external); + Directory.CreateSymbolicLink(Path.Combine(_root, "1.0", "76c1ae61-89e9-450d-93b0-a7f512c06768"), external); + using var http = Http((_, _) => Task.FromResult(Response(null))); + var events = await ScanOnce(http); + Assert.Equal(2, events.Count(e => e.Status == DiagnosticOutboxHostStatus.Error)); + Assert.Equal("preserve", File.ReadAllText(sentinel)); + } + + [Fact] + public async Task ObserverFailureFaultsCompletionRatherThanBeingTreatedAsCaseError() + { + Directory.CreateDirectory(_root); + using var http = Http((_, _) => throw new Exception("Unexpected upload")); + var error = await Assert.ThrowsAsync(() => Host(http, e => + { + if (e.Status == DiagnosticOutboxHostStatus.ScanCompleted) throw new ArgumentException("observer failed"); + }).StartAsync()); + Assert.IsType(error.InnerException); + } + + private DiagnosticOutboxHostOptions HostOptions() => new() + { + Enabled = true, FailDirectory = _root, Endpoint = new Uri("https://example.test/upload"), + TenantId = "tenant", AppKey = "app", ScanInterval = TimeSpan.FromMilliseconds(100) + }; + + private DiagnosticOutboxHost Host(HttpClient http, Action notify) => + new(HostOptions(), notify, http); + + private async Task> ScanOnce(HttpClient http, DiagnosticOutboxHostOptions? options = null) + { + using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + var events = new List(); + await new DiagnosticOutboxHost(options ?? HostOptions(), e => + { + events.Add(e); + if (e.Status == DiagnosticOutboxHostStatus.ScanCompleted) stop.Cancel(); + }, http).StartAsync(stop.Token); + Assert.Contains(events, e => e.Status == DiagnosticOutboxHostStatus.ScanCompleted); + return events; + } + private void CreateCase(bool marked = true, string evidenceName = "log.txt") { Directory.CreateDirectory(CasePath); diff --git a/tests/OutboxAotSmoke/Program.cs b/tests/OutboxAotSmoke/Program.cs index 25644e10..6306cd3d 100644 --- a/tests/OutboxAotSmoke/Program.cs +++ b/tests/OutboxAotSmoke/Program.cs @@ -18,8 +18,25 @@ var consumer = new DiagnosticOutboxConsumer(root, client, TimeSpan.FromSeconds(5)); if (await consumer.ProcessCaseAsync("1.0", id) || !Directory.Exists(casePath)) throw new InvalidOperationException("Unconfirmed evidence was deleted."); - if (!await consumer.ProcessCaseAsync("1.0", id) || Directory.Exists(casePath) || handler.Attempts != 2) - throw new InvalidOperationException("Confirmed retry did not complete."); + var tombstone = Path.Combine(root, "2.0", ".generalupdate-uploaded-" + id); + Directory.CreateDirectory(tombstone); + using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + var recovered = false; + var host = new DiagnosticOutboxHost(new DiagnosticOutboxHostOptions + { + Enabled = true, FailDirectory = root, Endpoint = new Uri("https://example.test/upload"), + TenantId = "tenant", AppKey = "app" + }, e => + { + if (e.Status == DiagnosticOutboxHostStatus.Error) throw e.Error!; + if (e.Status == DiagnosticOutboxHostStatus.TombstoneDeleted) recovered = true; + if (e.Status == DiagnosticOutboxHostStatus.ScanCompleted) stop.Cancel(); + }, http); + await host.StartAsync(stop.Token); + if (Directory.Exists(casePath) || handler.Attempts != 2) + throw new InvalidOperationException("Host did not replay the persisted snapshot."); + if (!recovered || Directory.Exists(tombstone)) + throw new InvalidOperationException("Host did not recover a confirmed tombstone."); Console.WriteLine("Outbox Native AOT smoke passed."); } finally