From ebbaca49d661236d3f328486790bd7ea18602d0a Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Sun, 22 Nov 2026 08:03:59 +1100 Subject: [PATCH] feat(collector): add crash resilience watchdog, opt-in DLQ expiry ledger, and volume health (#138) --- deploy/systemd/bower.service | 3 +- docs/operations/fleet-and-queue-integrity.md | 5 +- docs/operations/queue-v5-durability.md | 22 ++ src/Bower.Collector/CollectorApplication.cs | 45 ++- src/Bower.Collector/CollectorJson.cs | 12 + src/Bower.Collector/CollectorSettings.cs | 33 +++ .../Jobs/ManagementHeartbeatJob.cs | 16 +- src/Bower.Collector/Jobs/QueueRetentionJob.cs | 46 ++++ src/Bower.Collector/QueueStorageMonitor.cs | 32 +++ src/Bower.Collector/SystemdWatchdog.cs | 122 +++++++++ src/Bower.Persistence/SqliteEventQueue.cs | 2 +- .../SqliteEventStore.DeadLetterRetention.cs | 259 ++++++++++++++++++ .../CrashResilienceAndDiskHygieneTests.cs | 232 ++++++++++++++++ 13 files changed, 818 insertions(+), 11 deletions(-) create mode 100644 src/Bower.Collector/SystemdWatchdog.cs create mode 100644 src/Bower.Persistence/SqliteEventStore.DeadLetterRetention.cs create mode 100644 tests/Bower.UnitTests/CrashResilienceAndDiskHygieneTests.cs diff --git a/deploy/systemd/bower.service b/deploy/systemd/bower.service index e7e0adc4..1bcc0dcc 100644 --- a/deploy/systemd/bower.service +++ b/deploy/systemd/bower.service @@ -5,7 +5,7 @@ After=network-online.target Wants=network-online.target [Service] -# The collector does not send sd_notify readiness, so systemd must not wait for it. +# Sends sd_notify READY=1 / WATCHDOG=1 / STOPPING=1 when NOTIFY_SOCKET is present. Type=exec User=bower Group=bower @@ -13,6 +13,7 @@ WorkingDirectory=/opt/bower ExecStart=/opt/bower/Bower.Collector Restart=on-failure RestartSec=5s +WatchdogSec=60s Environment=BOWER_LISTEN_URL=http://127.0.0.1:4319 Environment=BOWER_QUEUE_PATH=/var/lib/bower/queue.db Environment=BOWER_POLICY_DIRECTORY=/etc/bower/policies diff --git a/docs/operations/fleet-and-queue-integrity.md b/docs/operations/fleet-and-queue-integrity.md index 0938c8ac..a972bfeb 100644 --- a/docs/operations/fleet-and-queue-integrity.md +++ b/docs/operations/fleet-and-queue-integrity.md @@ -241,7 +241,10 @@ bower queue replay --database /var/lib/bower/queue.db --code preflight- # or - ``` Replay resets the attempt count and returns events to the queue. Heartbeats report -the dead-letter count, which the console shows per collector and fleet-wide. +the dead-letter count, `oldestDeadLetterAgeSeconds` and `recovery` state, which the +console shows per collector and fleet-wide. Automatic dead-letter expiry is disabled by +default; when `BOWER_DEAD_LETTER_RETENTION_DAYS` is opted into, every purge writes a +hash-chained evidence entry in `queue_dead_letter_purges` before removing expired rows. ## Tamper-evident queue ledger diff --git a/docs/operations/queue-v5-durability.md b/docs/operations/queue-v5-durability.md index 4e560742..b3cd64fb 100644 --- a/docs/operations/queue-v5-durability.md +++ b/docs/operations/queue-v5-durability.md @@ -253,6 +253,28 @@ privacy profile cache writers) older than one hour, from the queue directory and recursively, at most 1,000 per run. The AMA spool and the archive already clean their own temporaries when they open. No other file is touched. +## Dead-letter retention, auxiliary volumes and service watchdogs + +- **Opt-in dead-letter retention.** Dead-lettered rows are kept indefinitely by default + so unresolved delivery failures cannot disappear silently. Set + `BOWER_DEAD_LETTER_RETENTION_DAYS` (`1`–`3650`) to enable automatic expiry of dead-lettered + rows older than the configured age. Before deleting any expired dead-letter row, the + retention job logs a pre-expiry warning (`EventId 1510`) for rows within 24 hours of + expiry, records a hash-chained `queue_dead_letter_purges` ledger evidence entry (count, + cutoff, failure-code summary, oldest/newest timestamps and chain hash), and logs + `EventId 1511` with metadata only. +- **Auxiliary volume health.** When `BOWER_OUTPUT=ama-spool` or `BOWER_ARCHIVE_PATH` is + configured, the collector monitors free space on the spool and archive volumes using the + same `BOWER_STORAGE_*` watermarks as the queue volume. `/v1/status` reports auxiliary + volume state under `volumes`, and a critical auxiliary volume degrades `/health` and + `/v1/status` to `degraded`. +- **Service watchdogs and crash recovery.** `deploy/systemd/bower.service` sets + `WatchdogSec=60s` alongside `Restart=always`, and the collector sends `READY=1`, + periodic `WATCHDOG=1` heartbeats (at half `WATCHDOG_USEC`), and `STOPPING=1` over + `NOTIFY_SOCKET` without external native dependencies. The Windows MSI configures three + automatic service-recovery restart actions. Heartbeats carry `recovery` (from unclean + shutdown detection) and `oldestDeadLetterAgeSeconds` alongside dead-letter counts. + ## SQL Server timestamp cursor v3 and allocation bounds Timestamp cursor v3 keeps forward `(eventTime, sequence)` progress separate from a diff --git a/src/Bower.Collector/CollectorApplication.cs b/src/Bower.Collector/CollectorApplication.cs index 9bcd74bd..36303351 100644 --- a/src/Bower.Collector/CollectorApplication.cs +++ b/src/Bower.Collector/CollectorApplication.cs @@ -97,6 +97,28 @@ public static WebApplication Build( settings.StorageWatermarks, services.GetService(), services.GetRequiredService())); + builder.Services.AddSingleton(services => + { + IDiskSpaceProbe? probe = services.GetService(); + TimeProvider clock = services.GetRequiredService(); + List<(string Name, StorageGuard Guard)> extra = []; + if (string.Equals(settings.OutputType, "ama-spool", StringComparison.Ordinal) + && !string.IsNullOrWhiteSpace(settings.AmaSpoolPath)) + { + extra.Add(("spool", new StorageGuard(Path.Combine(settings.AmaSpoolPath, ".volume"), settings.StorageWatermarks, probe, clock))); + } + + if (!string.IsNullOrWhiteSpace(settings.ArchivePath)) + { + extra.Add(("archive", new StorageGuard(Path.Combine(settings.ArchivePath, ".volume"), settings.StorageWatermarks, probe, clock))); + } + + return new MonitoredVolumes(extra); + }); + builder.Services.AddSingleton(_ => SystemdWatchdogOptions.FromEnvironment()); + builder.Services.AddSingleton(services => + new UnixSystemdNotifier(services.GetRequiredService().NotifySocket)); + builder.Services.AddHostedService(); builder.Services.AddSingleton(); builder.Services.AddSingleton(services => new SqliteEventStore( @@ -573,12 +595,12 @@ result.PolicyDecision is null // Readiness and status for probes: status only, no queue metadata without a token. app.MapGet( "/health", - async (IDurableEventStore eventQueue, SourceHealth sources, StorageGuard storage, HttpContext context, CancellationToken cancellationToken) => + async (IDurableEventStore eventQueue, SourceHealth sources, StorageGuard storage, MonitoredVolumes volumes, HttpContext context, CancellationToken cancellationToken) => { QueueSnapshot snapshot = await eventQueue.GetSnapshotAsync(cancellationToken); bool wecSilent = context.RequestServices.GetService()?.HasSilentSubscriptions() == true; return Results.Json( - new HealthResponse(Status(snapshot, sources.Evaluate(), storage.Evaluate().State, wecSilent)), + new HealthResponse(Status(snapshot, sources.Evaluate(), storage.Evaluate().State, wecSilent, volumes.AnyCritical())), CollectorJsonContext.Default.HealthResponse); }); @@ -594,6 +616,7 @@ result.PolicyDecision is null PipelineTelemetry telemetry, SourceHealth sourceHealth, StorageGuard storage, + MonitoredVolumes volumes, QueueStoragePressure pressure, TimeProvider clock, HttpContext context, @@ -609,7 +632,7 @@ result.PolicyDecision is null WindowsEventLogSource? windowsEventLog = context.RequestServices.GetService(); IReadOnlyList? wecRuntime = context.RequestServices.GetService()?.Snapshot(); StatusResponse status = new( - Status(snapshot, sources, storage.Evaluate().State, windowsEventLog?.HasSilentSubscriptions() == true), + Status(snapshot, sources, storage.Evaluate().State, windowsEventLog?.HasSilentSubscriptions() == true, volumes.AnyCritical()), settings.Version, new StatusPolicyResponse( bundle.Hash, @@ -658,7 +681,8 @@ [.. pack.Parsers.Select(parser => parser.Runtime is null ? "inactive-preview-onl activity.LastSuccessfulDeliveryAt, lastFailure?.Code, lastFailure?.At), Storage = await QueueStorageStatus.TryCaptureAsync( eventQueue, snapshot, pressure, telemetry, clock.GetUtcNow(), pages, cancellationToken), - Recovery = context.RequestServices.GetRequiredService().Last + Recovery = context.RequestServices.GetRequiredService().Last, + Volumes = volumes.HasVolumes ? volumes.Evaluate() : null }; return Results.Json(status, CollectorJsonContext.Default.StatusResponse); }) @@ -711,8 +735,17 @@ healthy with } } - private static string Status(QueueSnapshot snapshot, IReadOnlyList sources, StorageState storage, bool subscriptionSilent = false) => - snapshot.DeadLettered > 0 || sources.Any(source => source.IsOverdue) || storage == StorageState.Critical || subscriptionSilent + private static string Status( + QueueSnapshot snapshot, + IReadOnlyList sources, + StorageState storage, + bool subscriptionSilent = false, + bool auxiliaryVolumeCritical = false) => + snapshot.DeadLettered > 0 + || sources.Any(source => source.IsOverdue) + || storage == StorageState.Critical + || subscriptionSilent + || auxiliaryVolumeCritical ? "degraded" : "healthy"; diff --git a/src/Bower.Collector/CollectorJson.cs b/src/Bower.Collector/CollectorJson.cs index 966573fe..be99f721 100644 --- a/src/Bower.Collector/CollectorJson.cs +++ b/src/Bower.Collector/CollectorJson.cs @@ -104,6 +104,10 @@ internal sealed record StatusResponse( /// Unclean-shutdown check and temporary-file cleanup at the last start. Metadata only. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public CrashRecoveryStatus? Recovery { get; init; } + + /// Free-space health for configured spool and archive volumes. Metadata only. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public IReadOnlyList? Volumes { get; init; } } /// First server-sent event of a tap session: its effective filters and caps. @@ -231,6 +235,14 @@ internal sealed record CollectorHeartbeat( /// WEC runtime status per configured WEC subscription (additive). Metadata only. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public IReadOnlyList? WecRuntime { get; init; } + + /// Age in seconds of the oldest dead-lettered event, if any (additive). Metadata only. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? OldestDeadLetterAgeSeconds { get; init; } + + /// Last start's unclean-shutdown and recovery check (additive). Metadata only. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public CrashRecoveryStatus? Recovery { get; init; } } /// diff --git a/src/Bower.Collector/CollectorSettings.cs b/src/Bower.Collector/CollectorSettings.cs index 0058944f..753882bd 100644 --- a/src/Bower.Collector/CollectorSettings.cs +++ b/src/Bower.Collector/CollectorSettings.cs @@ -33,6 +33,9 @@ public sealed record CollectorSettings /// How long acknowledged events stay in the queue for duplicate detection. public TimeSpan DeliveredRetention { get; init; } = TimeSpan.FromDays(7); + /// Opt-in dead-letter retention (BOWER_DEAD_LETTER_RETENTION_DAYS, 1–3650). Null disables dead-letter purging. + public TimeSpan? DeadLetterRetention { get; init; } + /// /// Acknowledged events younger than this are kept even under storage pressure /// (BOWER_QUEUE_PRESSURE_RETENTION_MINUTES, default 60, at most the retention). Older @@ -346,6 +349,7 @@ public static CollectorSettings FromEnvironment(Func? read = nu PressureRetentionFloor = TimeSpan.FromMinutes(ReadInt64(read, "BOWER_QUEUE_PRESSURE_RETENTION_MINUTES", 60)), DeliveredRetention = TimeSpan.FromHours( ReadInt64(read, "BOWER_QUEUE_RETENTION_HOURS", 7 * 24)), + DeadLetterRetention = ReadOptionalDays(read, "BOWER_DEAD_LETTER_RETENTION_DAYS"), IngestToken = string.IsNullOrWhiteSpace(token) ? null : token, IngestTokensFile = Blank(read("BOWER_INGEST_TOKENS_FILE")), ProducerScopesFile = Blank(read("BOWER_PRODUCER_SCOPES_FILE")), @@ -500,6 +504,13 @@ public void Validate() "BOWER_QUEUE_RETENTION_HOURS must be between 1 and 2160."); } + if (DeadLetterRetention is { } dlqRetention + && (dlqRetention < TimeSpan.FromDays(1) || dlqRetention > TimeSpan.FromDays(3650))) + { + throw new InvalidOperationException( + "BOWER_DEAD_LETTER_RETENTION_DAYS must be between 1 and 3650."); + } + if (PressureRetentionFloor < TimeSpan.FromMinutes(1) || PressureRetentionFloor > DeliveredRetention) { throw new InvalidOperationException( @@ -915,6 +926,12 @@ public string ConfigurationHash() + PressureRetentionFloor.TotalMinutes.ToString(CultureInfo.InvariantCulture); } + if (DeadLetterRetention is { } dlqRetention) + { + material += '\u001f' + "dead-letter-retention-days:" + + dlqRetention.TotalDays.ToString(CultureInfo.InvariantCulture); + } + if (StorageWatermarks != new Bower.Persistence.StorageWatermarkOptions()) { material += '\u001f' + "storage-watermarks:" @@ -1105,6 +1122,22 @@ private static int ReadInt32(Func read, string name, int fallba : throw new InvalidOperationException($"{name} must be an integer between {int.MinValue} and {int.MaxValue}."); } + private static TimeSpan? ReadOptionalDays(Func read, string name) + { + string? raw = Blank(read(name)); + if (raw is null) + { + return null; + } + + if (!long.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out long days)) + { + throw new InvalidOperationException($"{name} must be an integer number of days."); + } + + return days == 0 ? null : TimeSpan.FromDays(days); + } + private static long ReadInt64(Func read, string name, long fallback) { string? value = read(name); diff --git a/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs b/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs index d4618694..f90ae2ec 100644 --- a/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs +++ b/src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs @@ -30,7 +30,8 @@ public sealed partial class ManagementHeartbeatJob( PipelineTelemetry? telemetry = null, QueueStoragePressure? storagePressure = null, WindowsEventLogSource? windowsEventLog = null, - WecRuntimeStatusTracker? wecRuntime = null) + WecRuntimeStatusTracker? wecRuntime = null, + CrashRecoveryState? crashRecovery = null) { public const string Id = "management-heartbeat"; public const string HttpClientName = "bower-management"; @@ -89,6 +90,15 @@ private async Task ReportAsync(CancellationToken cancellationToken) Bower.Persistence.QueuePageUsage? pages = await QueueStorageStatus.TryReadPagesAsync(eventStore, cancellationToken); QueueStorageStatus? storage = await QueueStorageStatus.TryCaptureAsync( eventStore, snapshot, storagePressure, telemetry, now, pages, cancellationToken); + long? oldestDeadLetterAge = null; + if (snapshot.DeadLettered > 0 && eventStore is Bower.Persistence.SqliteEventStore sqliteStore) + { + Bower.Persistence.DeadLetterHealth dlqHealth = await sqliteStore.GetDeadLetterHealthAsync(cancellationToken); + if (dlqHealth.OldestReceivedAt is { } oldestDlq) + { + oldestDeadLetterAge = Math.Max(0, (long)(now - oldestDlq).TotalSeconds); + } + } string deliveryStatus = DeliveryHealth.Evaluate(settings.OutputType, snapshot, settings.MaximumQueueBytes, now, storage?.IntakePaused ?? false, pages?.UsedPercent); // Finished command results stay pending until management acknowledges them. @@ -178,7 +188,9 @@ private async Task ReportAsync(CancellationToken cancellationToken) CommandResults = results, Redactions = telemetry?.RedactionSnapshot(), Storage = storage, - WecRuntime = wecSnapshots.Count > 0 ? wecSnapshots : null + WecRuntime = wecSnapshots.Count > 0 ? wecSnapshots : null, + OldestDeadLetterAgeSeconds = oldestDeadLetterAge, + Recovery = crashRecovery?.Last }, CollectorJsonContext.Default.CollectorHeartbeat)); // One budget for the whole exchange, body included: a stalled body cannot hold the diff --git a/src/Bower.Collector/Jobs/QueueRetentionJob.cs b/src/Bower.Collector/Jobs/QueueRetentionJob.cs index 17bd19a4..ac111b87 100644 --- a/src/Bower.Collector/Jobs/QueueRetentionJob.cs +++ b/src/Bower.Collector/Jobs/QueueRetentionJob.cs @@ -65,6 +65,9 @@ public async Task RunAsync(CancellationToken cancellationToken) if (queue is SqliteEventStore store) { + // Opt-in dead-letter retention: warn before expiry and write a ledger evidence record before purge. + await HandleDeadLetterRetentionAsync(store, now, cancellationToken); + // Unverified archive coverage purges nothing, but pages already free still go back. if (total >= 0) { @@ -75,6 +78,37 @@ public async Task RunAsync(CancellationToken cancellationToken) } } + private async Task HandleDeadLetterRetentionAsync(SqliteEventStore store, DateTimeOffset now, CancellationToken cancellationToken) + { + if (settings.DeadLetterRetention is not { } retention) + { + return; + } + + DeadLetterHealth health = await store.GetDeadLetterHealthAsync(cancellationToken); + if (health.Count == 0 || health.OldestReceivedAt is null) + { + return; + } + + TimeSpan lead = TimeSpan.FromHours(Math.Min(24, Math.Max(1, retention.TotalHours * 0.25))); + DateTimeOffset expiresAt = health.OldestReceivedAt.Value + retention; + if (expiresAt > now && expiresAt - now <= lead) + { + LogDeadLettersApproachingExpiry(logger, health.Count, (long)Math.Max(0, (expiresAt - now).TotalMinutes)); + } + + DeadLetterPurgeEvidence? evidence = await store.PurgeExpiredDeadLettersAsync( + now - retention, + BatchSize, + now, + cancellationToken); + if (evidence is not null) + { + LogDeadLettersPurged(logger, evidence.PurgedCount, evidence.LedgerSequence); + } + } + /// Pages returned to the file system per step (8 MiB at 4 KiB pages), so the WAL stays small. public const int ReleaseStepPages = 2_048; @@ -290,4 +324,16 @@ private static partial void LogPressurePurged( Level = LogLevel.Warning, Message = "Queue retention stopped before purging: archive coverage is not verified ({Reason}; first {FirstSequence}, through {ThroughSequence}).")] private static partial void LogCoverageRefused(ILogger logger, string? reason, long firstSequence, long throughSequence); + + [LoggerMessage( + EventId = 1510, + Level = LogLevel.Warning, + Message = "Dead-lettered events ({Count}) are approaching retention expiry; oldest expires in {RemainingMinutes} minute(s). Inspect with 'bower queue dead-letters' or replay before expiry.")] + private static partial void LogDeadLettersApproachingExpiry(ILogger logger, long count, long remainingMinutes); + + [LoggerMessage( + EventId = 1511, + Level = LogLevel.Warning, + Message = "Opt-in dead-letter retention purged {Count} expired dead-lettered event(s); evidence recorded at queue ledger sequence {LedgerSequence}.")] + private static partial void LogDeadLettersPurged(ILogger logger, int count, long ledgerSequence); } diff --git a/src/Bower.Collector/QueueStorageMonitor.cs b/src/Bower.Collector/QueueStorageMonitor.cs index fc5de1f3..573435d0 100644 --- a/src/Bower.Collector/QueueStorageMonitor.cs +++ b/src/Bower.Collector/QueueStorageMonitor.cs @@ -6,6 +6,38 @@ namespace Bower.Collector; +public sealed record VolumeHealthStatus( + string Volume, + string State, + long? FreeBytes, + long? TotalBytes, + double? FreePercent); + +/// +/// Free-space health across auxiliary Bower volumes (AMA spool and queue archive when configured), +/// evaluated alongside the queue volume so a full spool or archive volume degrades /health. +/// Metadata only: never exposes directory paths. +/// +public sealed class MonitoredVolumes(IReadOnlyList<(string Name, StorageGuard Guard)> volumes) +{ + public bool HasVolumes => volumes.Count > 0; + + public bool AnyCritical() => + volumes.Any(item => item.Guard.Evaluate().State == StorageState.Critical); + + public IReadOnlyList Evaluate() => + [.. volumes.Select(item => + { + StorageWatermarkSnapshot snapshot = item.Guard.Evaluate(); + return new VolumeHealthStatus( + item.Name, + StorageWatermarkSnapshot.Name(snapshot.State), + snapshot.FreeBytes, + snapshot.TotalBytes, + snapshot.FreePercent); + })]; +} + /// /// Storage pressure facts shared by the monitor, the retention job and status: acknowledged /// rows purged early under pressure. In memory; resets on restart. diff --git a/src/Bower.Collector/SystemdWatchdog.cs b/src/Bower.Collector/SystemdWatchdog.cs new file mode 100644 index 00000000..2b2f188c --- /dev/null +++ b/src/Bower.Collector/SystemdWatchdog.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using System.Net.Sockets; +using System.Text; + +namespace Bower.Collector; + +/// Sends systemd sd_notify state messages. Swapped in tests. +public interface ISystemdNotifier +{ + bool Notify(string state); +} + +/// +/// Reads NOTIFY_SOCKET and WATCHDOG_USEC from the systemd unit environment. +/// Inert when NOTIFY_SOCKET is unset. +/// +public sealed record SystemdWatchdogOptions(string? NotifySocket, TimeSpan? WatchdogInterval) +{ + public static readonly TimeSpan MinimumInterval = TimeSpan.FromSeconds(1); + + public bool IsEnabled => !string.IsNullOrWhiteSpace(NotifySocket); + + public static SystemdWatchdogOptions FromEnvironment(Func? read = null) + { + read ??= Environment.GetEnvironmentVariable; + string? socket = read("NOTIFY_SOCKET"); + if (string.IsNullOrWhiteSpace(socket)) + { + return new SystemdWatchdogOptions(null, null); + } + + TimeSpan? interval = null; + if (long.TryParse(read("WATCHDOG_USEC"), NumberStyles.Integer, CultureInfo.InvariantCulture, out long usec) + && usec > 0) + { + // Keepalive at half the configured WatchdogSec, clamped to at least 1 second. + TimeSpan half = TimeSpan.FromMicroseconds(usec / 2.0); + interval = half < MinimumInterval ? MinimumInterval : half; + } + + return new SystemdWatchdogOptions(socket, interval); + } +} + +/// +/// Pure-.NET Unix domain datagram sd_notify sender (no native libsystemd dependency). +/// Supports both filesystem paths (/run/systemd/notify) and Linux abstract sockets +/// (@...). Never throws on delivery failure. +/// +public sealed class UnixSystemdNotifier(string? socketPath) : ISystemdNotifier +{ + public bool Notify(string state) + { + if (string.IsNullOrWhiteSpace(socketPath) || string.IsNullOrWhiteSpace(state) || OperatingSystem.IsWindows()) + { + return false; + } + + try + { + string address = socketPath[0] == '@' ? "\0" + socketPath[1..] : socketPath; + using Socket socket = new(AddressFamily.Unix, SocketType.Dgram, ProtocolType.Unspecified); + socket.SendTo(Encoding.UTF8.GetBytes(state), SocketFlags.None, new UnixDomainSocketEndPoint(address)); + return true; + } + catch (Exception exception) when (exception is SocketException or IOException or PlatformNotSupportedException or ArgumentException) + { + return false; + } + } +} + +/// +/// Sends READY=1 on startup, periodic WATCHDOG=1 keepalives when +/// WATCHDOG_USEC is set, and STOPPING=1 on graceful shutdown. No-op when +/// NOTIFY_SOCKET is unset. +/// +public sealed class SystemdWatchdogService( + SystemdWatchdogOptions options, + ISystemdNotifier notifier, + IHostApplicationLifetime lifetime, + TimeProvider clock) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + if (!options.IsEnabled) + { + return; + } + + using CancellationTokenRegistration started = lifetime.ApplicationStarted.Register(() => notifier.Notify("READY=1")); + using CancellationTokenRegistration stopping = lifetime.ApplicationStopping.Register(() => notifier.Notify("STOPPING=1")); + + if (options.WatchdogInterval is not { } interval) + { + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, stoppingToken); + } + catch (OperationCanceledException) + { + // Stopping. + } + + return; + } + + while (!stoppingToken.IsCancellationRequested) + { + try + { + await Task.Delay(interval, clock, stoppingToken); + } + catch (OperationCanceledException) + { + break; + } + + notifier.Notify("WATCHDOG=1"); + } + } +} diff --git a/src/Bower.Persistence/SqliteEventQueue.cs b/src/Bower.Persistence/SqliteEventQueue.cs index 0eeaf42e..716b42ae 100644 --- a/src/Bower.Persistence/SqliteEventQueue.cs +++ b/src/Bower.Persistence/SqliteEventQueue.cs @@ -141,7 +141,7 @@ public async Task InitializeAsync(CancellationToken cancellationToken = default) CREATE INDEX IF NOT EXISTS ix_queue_events_state_bytes ON queue_events_v5(state, payload_bytes, received_at); INSERT OR IGNORE INTO schema_history(version, applied_at, hash) VALUES (4, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'), 'bower-queue-v4-capacity-index'); - """ + AuxiliarySchema; + """ + AuxiliarySchema + DeadLetterPurgeSchema; await check.ExecuteNonQueryAsync(cancellationToken); await repair.CommitAsync(cancellationToken); ApplyRestrictivePermissions(); diff --git a/src/Bower.Persistence/SqliteEventStore.DeadLetterRetention.cs b/src/Bower.Persistence/SqliteEventStore.DeadLetterRetention.cs new file mode 100644 index 00000000..ed09a183 --- /dev/null +++ b/src/Bower.Persistence/SqliteEventStore.DeadLetterRetention.cs @@ -0,0 +1,259 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using Bower.Abstractions; +using Microsoft.Data.Sqlite; + +namespace Bower.Persistence; + +/// Dead-letter count and oldest timestamp for pre-expiry warnings and heartbeats. +public sealed record DeadLetterHealth(long Count, DateTimeOffset? OldestReceivedAt); + +/// +/// Metadata-only evidence record written to the queue ledger before opt-in dead-letter +/// retention purges expired dead letters (#138). Never carries event payloads. +/// +public sealed record DeadLetterPurgeEvidence( + long LedgerSequence, + string ChainHash, + DateTimeOffset PurgedAt, + int PurgedCount, + IReadOnlyDictionary ReasonCounts, + DateTimeOffset? OldestReceivedAt, + DateTimeOffset? NewestReceivedAt, + string EvidenceSha256); + +public sealed partial class SqliteEventStore +{ + internal const string DeadLetterPurgeSchema = + """ + CREATE TABLE IF NOT EXISTS queue_dead_letter_purges ( + ledger_sequence INTEGER PRIMARY KEY NOT NULL, + chain_hash TEXT NOT NULL, + purged_at TEXT NOT NULL, + purged_count INTEGER NOT NULL, + reason_counts_json TEXT NOT NULL, + oldest_received_at TEXT NULL, + newest_received_at TEXT NULL, + evidence_sha256 TEXT NOT NULL + ); + """; + + public async Task GetDeadLetterHealthAsync(CancellationToken cancellationToken = default) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = + """ + SELECT COUNT(*), MIN(received_at) + FROM queue_events_v5 + WHERE state = $dead_lettered; + """; + command.Parameters.AddWithValue("$dead_lettered", (int)QueueState.DeadLettered); + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + if (!await reader.ReadAsync(cancellationToken)) + { + return new DeadLetterHealth(0, null); + } + + long count = reader.GetInt64(0); + DateTimeOffset? oldest = reader.IsDBNull(1) + ? null + : DateTimeOffset.Parse(reader.GetString(1), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); + return new DeadLetterHealth(count, oldest); + } + + /// + /// Opt-in dead-letter retention purge: selects up to + /// dead-lettered rows older than , appends a hash-chained + /// metadata-only evidence entry to queue_ledger and queue_dead_letter_purges, + /// marks the purged events' ledger entries as purged, and deletes those rows inside one + /// transaction. Returns null when no dead-lettered rows qualify. + /// + public async Task PurgeExpiredDeadLettersAsync( + DateTimeOffset olderThan, + int maximumCount, + DateTimeOffset? at = null, + CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(maximumCount, 1); + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = await BeginWriteAsync(connection, checkCapacity: false, cancellationToken); + + List<(string EventId, string Reason, string ReceivedAt)> victims = []; + await using (SqliteCommand select = connection.CreateCommand()) + { + select.Transaction = transaction; + select.CommandText = + """ + SELECT event_id, COALESCE(last_failure_code, 'unknown'), received_at + FROM queue_events_v5 + WHERE state = $dead_lettered + AND received_at < $older_than + ORDER BY received_at ASC, event_id ASC + LIMIT $maximum_count; + """; + select.Parameters.AddWithValue("$dead_lettered", (int)QueueState.DeadLettered); + select.Parameters.AddWithValue( + "$older_than", + olderThan.ToUniversalTime().ToString(TimestampFormat, CultureInfo.InvariantCulture)); + select.Parameters.AddWithValue("$maximum_count", maximumCount); + await using SqliteDataReader reader = await select.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + victims.Add((reader.GetString(0), reader.GetString(1), reader.GetString(2))); + } + } + + if (victims.Count == 0) + { + return null; + } + + DateTimeOffset now = (at ?? clock.GetUtcNow()).ToUniversalTime(); + string purgedAtText = now.ToString(TimestampFormat, CultureInfo.InvariantCulture); + + SortedDictionary reasons = new(StringComparer.Ordinal); + foreach ((_, string reason, _) in victims) + { + string key = string.IsNullOrWhiteSpace(reason) ? "unknown" : reason; + reasons[key] = reasons.TryGetValue(key, out int existing) ? existing + 1 : 1; + } + + string oldestText = victims[0].ReceivedAt; + string newestText = victims[^1].ReceivedAt; + DateTimeOffset oldest = DateTimeOffset.Parse(oldestText, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); + DateTimeOffset newest = DateTimeOffset.Parse(newestText, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); + + string reasonsJson = JsonSerializer.Serialize(reasons, DeadLetterEvidenceJsonContext.Default.SortedDictionaryStringInt32); + string evidencePayload = JsonSerializer.Serialize( + new DeadLetterPurgeLedgerPayload("dead_letter_purge", purgedAtText, victims.Count, oldestText, newestText, reasons), + DeadLetterEvidenceJsonContext.Default.DeadLetterPurgeLedgerPayload); + string evidenceSha256 = QueueLedger.PayloadHash(evidencePayload); + + // Append a hash-chained evidence record to queue_ledger (marked purged at creation since + // it has no row in queue_events_v5, keeping VerifyLedgerAsync intact) before deleting rows. + (long previousSequence, string previousHash) = await QueueLedger.HeadAsync(connection, transaction, cancellationToken); + long evidenceSequence = previousSequence + 1; + string evidenceEventId = $"dead-letter-purge:{evidenceSequence.ToString(CultureInfo.InvariantCulture)}"; + string chainHash = QueueLedger.Chain(previousHash, evidenceSequence, evidenceEventId, evidenceSha256, purgedAtText); + + await using (SqliteCommand appendEvidence = connection.CreateCommand()) + { + appendEvidence.Transaction = transaction; + appendEvidence.CommandText = + """ + INSERT INTO queue_ledger (sequence, event_id, payload_sha256, received_at, chain_hash, purged_at) + VALUES ($sequence, $event_id, $payload_sha256, $received_at, $chain_hash, $purged_at); + """; + appendEvidence.Parameters.AddWithValue("$sequence", evidenceSequence); + appendEvidence.Parameters.AddWithValue("$event_id", evidenceEventId); + appendEvidence.Parameters.AddWithValue("$payload_sha256", evidenceSha256); + appendEvidence.Parameters.AddWithValue("$received_at", purgedAtText); + appendEvidence.Parameters.AddWithValue("$chain_hash", chainHash); + appendEvidence.Parameters.AddWithValue("$purged_at", purgedAtText); + await appendEvidence.ExecuteNonQueryAsync(cancellationToken); + } + + await using (SqliteCommand recordEvidence = connection.CreateCommand()) + { + recordEvidence.Transaction = transaction; + recordEvidence.CommandText = + """ + INSERT INTO queue_dead_letter_purges ( + ledger_sequence, chain_hash, purged_at, purged_count, + reason_counts_json, oldest_received_at, newest_received_at, evidence_sha256) + VALUES ( + $ledger_sequence, $chain_hash, $purged_at, $purged_count, + $reason_counts_json, $oldest_received_at, $newest_received_at, $evidence_sha256); + """; + recordEvidence.Parameters.AddWithValue("$ledger_sequence", evidenceSequence); + recordEvidence.Parameters.AddWithValue("$chain_hash", chainHash); + recordEvidence.Parameters.AddWithValue("$purged_at", purgedAtText); + recordEvidence.Parameters.AddWithValue("$purged_count", victims.Count); + recordEvidence.Parameters.AddWithValue("$reason_counts_json", reasonsJson); + recordEvidence.Parameters.AddWithValue("$oldest_received_at", oldestText); + recordEvidence.Parameters.AddWithValue("$newest_received_at", newestText); + recordEvidence.Parameters.AddWithValue("$evidence_sha256", evidenceSha256); + await recordEvidence.ExecuteNonQueryAsync(cancellationToken); + } + + string[] eventIds = [.. victims.Select(item => item.EventId)]; + await using (SqliteCommand delete = connection.CreateCommand()) + { + delete.Transaction = transaction; + delete.CommandText = "DELETE FROM queue_events_v5 WHERE event_id = $event_id AND state = $dead_lettered;"; + SqliteParameter idParam = delete.Parameters.Add("$event_id", SqliteType.Text); + delete.Parameters.AddWithValue("$dead_lettered", (int)QueueState.DeadLettered); + foreach (string eventId in eventIds) + { + idParam.Value = eventId; + await delete.ExecuteNonQueryAsync(cancellationToken); + } + } + + long through = await QueueLedger.MarkPurgedAsync(connection, transaction, eventIds, purgedAtText, cancellationToken); + await QueueLedger.CompactAsync(connection, transaction, purgedAtText, Math.Max(through, evidenceSequence), cancellationToken); + await transaction.CommitAsync(cancellationToken); + + return new DeadLetterPurgeEvidence( + evidenceSequence, + chainHash, + now, + victims.Count, + reasons, + oldest, + newest, + evidenceSha256); + } + + public async Task> ListDeadLetterPurgesAsync( + int maximumCount = 50, + CancellationToken cancellationToken = default) + { + ArgumentOutOfRangeException.ThrowIfLessThan(maximumCount, 1); + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = + """ + SELECT ledger_sequence, chain_hash, purged_at, purged_count, + reason_counts_json, oldest_received_at, newest_received_at, evidence_sha256 + FROM queue_dead_letter_purges + ORDER BY ledger_sequence DESC + LIMIT $maximum_count; + """; + command.Parameters.AddWithValue("$maximum_count", maximumCount); + List records = []; + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + SortedDictionary reasons = JsonSerializer.Deserialize( + reader.GetString(4), + DeadLetterEvidenceJsonContext.Default.SortedDictionaryStringInt32) ?? []; + records.Add(new DeadLetterPurgeEvidence( + reader.GetInt64(0), + reader.GetString(1), + DateTimeOffset.Parse(reader.GetString(2), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind), + reader.GetInt32(3), + reasons, + reader.IsDBNull(5) ? null : DateTimeOffset.Parse(reader.GetString(5), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind), + reader.IsDBNull(6) ? null : DateTimeOffset.Parse(reader.GetString(6), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind), + reader.GetString(7))); + } + + return records; + } + + internal sealed record DeadLetterPurgeLedgerPayload( + string Kind, + string PurgedAt, + int Count, + string OldestReceivedAt, + string NewestReceivedAt, + SortedDictionary Reasons); +} + +[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)] +[JsonSerializable(typeof(SortedDictionary))] +[JsonSerializable(typeof(SqliteEventStore.DeadLetterPurgeLedgerPayload))] +internal sealed partial class DeadLetterEvidenceJsonContext : JsonSerializerContext; diff --git a/tests/Bower.UnitTests/CrashResilienceAndDiskHygieneTests.cs b/tests/Bower.UnitTests/CrashResilienceAndDiskHygieneTests.cs new file mode 100644 index 00000000..bf2d5c8e --- /dev/null +++ b/tests/Bower.UnitTests/CrashResilienceAndDiskHygieneTests.cs @@ -0,0 +1,232 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using Bower.Abstractions; +using Bower.Collector; +using Bower.Collector.Jobs; +using Bower.Persistence; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Bower.UnitTests; + +/// +/// Collector crash resilience and disk hygiene (#138): opt-in dead-letter retention with +/// ledger evidence and pre-expiry warning, systemd sd_notify watchdog, and spool/archive +/// volume free-space health. +/// +public sealed class CrashResilienceAndDiskHygieneTests +{ + private static readonly DateTimeOffset BaseTime = new(2026, 11, 22, 2, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task DeadLetterRetention_DisabledByDefault_NeverRemovesDeadLetters() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory directory = new(); + StepClock clock = new(BaseTime); + SqliteEventStore store = new(Path.Combine(directory.Path, "queue.db"), 1024 * 1024, clock); + await store.InitializeAsync(cancellation); + + await store.EnqueueAsync(new QueuedEvent("dlq-keep-1", "fp-keep-1", "{\"eventId\":\"dlq-keep-1\",\"secret\":\"none\"}", BaseTime.AddDays(-60)), cancellation); + IReadOnlyList leased = await store.LeaseAsync(1, TimeSpan.FromMinutes(1), cancellation); + await store.MarkDeadLetteredAsync(leased[0].EventId, "preflight-invalid", leased[0].LeaseToken!, cancellation); + + CollectorSettings settings = new() + { + CollectorId = "dlq-keep-01", + ListenUrl = "http://127.0.0.1:4319", + PolicyDirectory = Path.Combine(AppContext.BaseDirectory, "policies", "default"), + QueuePath = Path.Combine(directory.Path, "queue.db"), + DeadLetterRetention = null + }; + RecordingLogger logger = new(); + QueueRetentionJob job = new(store, clock, settings, logger); + await job.RunAsync(cancellation); + + Assert.Equal(1, (await store.GetSnapshotAsync(cancellation)).DeadLettered); + Assert.Empty(await store.ListDeadLetterPurgesAsync(cancellationToken: cancellation)); + Assert.True((await store.VerifyLedgerAsync(cancellation)).Intact); + } + + [Fact] + public async Task DeadLetterRetention_OptIn_WarnsBeforeExpiryAndWritesLedgerEvidenceBeforePurge() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory directory = new(); + StepClock clock = new(BaseTime); + SqliteEventStore store = new(Path.Combine(directory.Path, "queue.db"), 1024 * 1024, clock); + await store.InitializeAsync(cancellation); + + // One dead letter approaching expiry (29.5 days old on a 30-day retention -> warns, not purged). + await store.EnqueueAsync(new QueuedEvent("dlq-warn-1", "fp-warn-1", "{\"eventId\":\"dlq-warn-1\",\"raw\":\"must-not-leak\"}", BaseTime.AddDays(-29.5)), cancellation); + // One dead letter past expiry (31 days old -> purged with ledger evidence). + await store.EnqueueAsync(new QueuedEvent("dlq-old-1", "fp-old-1", "{\"eventId\":\"dlq-old-1\",\"raw\":\"also-must-not-leak\"}", BaseTime.AddDays(-31)), cancellation); + IReadOnlyList leased = await store.LeaseAsync(2, TimeSpan.FromMinutes(1), cancellation); + QueuedEvent warnEvent = leased.Single(e => e.EventId == "dlq-warn-1"); + QueuedEvent oldEvent = leased.Single(e => e.EventId == "dlq-old-1"); + await store.MarkDeadLetteredAsync(warnEvent.EventId, "payload-invalid-json", warnEvent.LeaseToken!, cancellation); + await store.MarkDeadLetteredAsync(oldEvent.EventId, "azure-http-400", oldEvent.LeaseToken!, cancellation); + + CollectorSettings settings = new() + { + CollectorId = "dlq-optin-01", + ListenUrl = "http://127.0.0.1:4319", + PolicyDirectory = Path.Combine(AppContext.BaseDirectory, "policies", "default"), + QueuePath = Path.Combine(directory.Path, "queue.db"), + DeadLetterRetention = TimeSpan.FromDays(30) + }; + RecordingLogger logger = new(); + QueueRetentionJob job = new(store, clock, settings, logger); + await job.RunAsync(cancellation); + + // Old one purged, approaching-expiry one retained, and warning logged. + QueueSnapshot after = await store.GetSnapshotAsync(cancellation); + Assert.Equal(1, after.DeadLettered); + IReadOnlyList remaining = await store.ListDeadLetteredAsync(10, cancellation); + Assert.Equal("dlq-warn-1", Assert.Single(remaining).EventId); + + // Ledger evidence recorded and chain stays 100% intact. + LedgerVerification verification = await store.VerifyLedgerAsync(cancellation); + Assert.True(verification.Intact, string.Join("; ", verification.Issues.Select(issue => $"{issue.Code}: {issue.Detail}"))); + + IReadOnlyList purges = await store.ListDeadLetterPurgesAsync(cancellationToken: cancellation); + DeadLetterPurgeEvidence evidence = Assert.Single(purges); + Assert.Equal(1, evidence.PurgedCount); + Assert.Equal(1, evidence.ReasonCounts["azure-http-400"]); + Assert.True(evidence.LedgerSequence > 0); + Assert.Contains(logger.EventIds, id => id == 1511); + + // Next run sees dlq-warn-1 as oldest (0.5 days left -> inside 24h warning window). + await job.RunAsync(cancellation); + Assert.Contains(logger.EventIds, id => id == 1510); + } + + [Fact] + public async Task SystemdWatchdog_ParsesEnvironmentAndSendsReadyWatchdogAndStopping() + { + SystemdWatchdogOptions options = SystemdWatchdogOptions.FromEnvironment(name => name switch + { + "NOTIFY_SOCKET" => "/run/systemd/notify", + "WATCHDOG_USEC" => "60000000", + _ => null + }); + Assert.True(options.IsEnabled); + Assert.Equal(TimeSpan.FromSeconds(30), options.WatchdogInterval); + + SystemdWatchdogOptions disabled = SystemdWatchdogOptions.FromEnvironment(_ => null); + Assert.False(disabled.IsEnabled); + + if (!OperatingSystem.IsWindows()) + { + // Real Unix domain datagram socket test (short /tmp path to stay under macOS 104-char sun_path limit). + string socketPath = Path.Combine("/tmp", $"bower-sd-{Guid.NewGuid():N}"[..24] + ".sock"); + try + { + using Socket server = new(AddressFamily.Unix, SocketType.Dgram, ProtocolType.Unspecified); + server.Bind(new UnixDomainSocketEndPoint(socketPath)); + + UnixSystemdNotifier notifier = new(socketPath); + Assert.True(notifier.Notify("READY=1")); + Assert.True(notifier.Notify("WATCHDOG=1")); + + byte[] buffer = new byte[64]; + int first = await server.ReceiveAsync(buffer, SocketFlags.None, TestContext.Current.CancellationToken); + Assert.Equal("READY=1", Encoding.UTF8.GetString(buffer, 0, first)); + int second = await server.ReceiveAsync(buffer, SocketFlags.None, TestContext.Current.CancellationToken); + Assert.Equal("WATCHDOG=1", Encoding.UTF8.GetString(buffer, 0, second)); + } + finally + { + if (File.Exists(socketPath)) + { + File.Delete(socketPath); + } + } + } + } + + [Fact] + public async Task Collector_AuxiliaryArchiveVolumeCritical_DegradesHealthAndReportsVolumesInStatus() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory directory = new(); + string archiveDir = Path.Combine(directory.Path, "archive"); + Directory.CreateDirectory(archiveDir); + const string token = "disk-hygiene-test-token-0123456789abcdef"; + + // Queue volume healthy (50 GiB free), archive volume critically low (10 MiB free). + PerDirectoryDiskProbe probe = new(archiveDir, new DiskSpace(10L * 1024 * 1024, 10L * 1024 * 1024 * 1024)); + CollectorSettings settings = new() + { + CollectorId = "disk-hygiene-01", + Environment = "test", + ListenUrl = "http://127.0.0.1:4319", + PolicyDirectory = Path.Combine(AppContext.BaseDirectory, "policies", "default"), + QueuePath = Path.Combine(directory.Path, "queue.db"), + ArchivePath = archiveDir, + OutputType = "none", + IngestToken = token + }; + + await using WebApplication app = CollectorApplication.Build( + settings, + configure: builder => + { + builder.WebHost.UseTestServer(); + builder.Services.AddSingleton(probe); + }); + await CollectorApplication.InitializeAsync(app, cancellation); + await app.StartAsync(cancellation); + + try + { + using HttpClient client = app.GetTestClient(); + using HttpResponseMessage healthResponse = await client.GetAsync("/health", cancellation); + Assert.Equal(HttpStatusCode.OK, healthResponse.StatusCode); + using JsonDocument health = JsonDocument.Parse(await healthResponse.Content.ReadAsStringAsync(cancellation)); + Assert.Equal("degraded", health.RootElement.GetProperty("status").GetString()); + + using HttpRequestMessage statusRequest = new(HttpMethod.Get, "/v1/status"); + statusRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + using HttpResponseMessage statusResponse = await client.SendAsync(statusRequest, cancellation); + using JsonDocument status = JsonDocument.Parse(await statusResponse.Content.ReadAsStringAsync(cancellation)); + Assert.Equal("degraded", status.RootElement.GetProperty("status").GetString()); + JsonElement archiveVolume = status.RootElement.GetProperty("volumes")[0]; + Assert.Equal("archive", archiveVolume.GetProperty("volume").GetString()); + Assert.Equal("critical", archiveVolume.GetProperty("state").GetString()); + } + finally + { + await app.StopAsync(cancellation); + } + } + + private sealed class PerDirectoryDiskProbe(string criticalDirectory, DiskSpace criticalSpace) : IDiskSpaceProbe + { + public DiskSpace? Measure(string directory) => + directory.StartsWith(criticalDirectory, StringComparison.OrdinalIgnoreCase) + ? criticalSpace + : new DiskSpace(50L * 1024 * 1024 * 1024, 100L * 1024 * 1024 * 1024); + } + + private sealed class StepClock(DateTimeOffset start) : TimeProvider + { + private DateTimeOffset current = start; + public override DateTimeOffset GetUtcNow() => current; + } + + private sealed class RecordingLogger : ILogger + { + public ConcurrentBag EventIds { get; } = []; + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + EventIds.Add(eventId.Id); + } +}