diff --git a/docs/migration/ravendb-to-sql-migration-instructions.md b/docs/migration/ravendb-to-sql-migration-instructions.md index 6f908d8557..734a37f290 100644 --- a/docs/migration/ravendb-to-sql-migration-instructions.md +++ b/docs/migration/ravendb-to-sql-migration-instructions.md @@ -188,6 +188,8 @@ If the copy slows down your production work, raise `ServiceControl/Migration/Thr > [!IMPORTANT] > To give up an optional category, use [the abandon command](#to-abandon-a-category). +SQL retention deletes nothing until every category is Done or Abandoned, including while a category is Failed, so the SQL database grows past the retention period during that time. Retention resumes at the next hourly check after the last category finishes. The purge API answers `400` with status `error` and names the unfinished categories. If a category stays unfinished for a long time, retry or abandon it. + Keep RavenDB running until every category is Done or Abandoned. If RavenDB goes down after ServiceControl opens, ServiceControl keeps running. The optional categories wait for RavenDB to come back, or you can abandon them. ## Step 8: Finish the migration diff --git a/docs/migration/ravendb-to-sql-migration-overview.md b/docs/migration/ravendb-to-sql-migration-overview.md index 5e9cf80b22..312324e9e0 100644 --- a/docs/migration/ravendb-to-sql-migration-overview.md +++ b/docs/migration/ravendb-to-sql-migration-overview.md @@ -101,6 +101,7 @@ flowchart LR - **The [free abort](#going-back-to-ravendb) window runs from the first `--start-data-migration` invocation until ServiceControl opens.** A successful command does not end this window; starting ServiceControl does. - **While required data is still copying, none of ServiceControl's own clean-up runs**: the retention sweep, the purge API, the heartbeat settings sync and throughput collection. The offline command never starts the host, and normal startup refuses while a required category is unfinished. +- **While any category is unfinished, SQL retention deletes nothing.** The hourly sweep, the manual purge API and every other sweep check the persisted category checkpoints before they delete a row. An unfinished category is any checkpoint that is not Complete or Abandoned: not started, in progress, blocked, halted, or complete with errors. A category the running version does not know counts as unfinished until it is Complete or Abandoned. A database with no checkpoints is not paused. ## Design @@ -159,7 +160,7 @@ There are nineteen *categories*: fifteen required and four optional. | Custom checks, with their last status | Required | Not every check reports again. An endpoint that is down never does, and a check with no repeat interval reports only when its endpoint starts. Leaving one out could hide a known failure until that endpoint restarts. Results of the six checks the RavenDB persister runs about its own database, matched on id and category, are left out, as harmless skips | | Failed error imports, with bodies | Required | Messages taken off the error queue but not ingested. They exist nowhere else and never expire. After the move the "Error Message Ingestion" custom check keeps flagging them and `--import-failed-errors` imports them into SQL. Importing them on RavenDB first is better still | | Unresolved failed messages, with bodies | Optional | Copied once ServiceControl has opened, whatever the age of the message, because an operator is waiting on each one. It has no window and no setting turns it off. A message the required category already copied, because it holds a retry claim or is one of the recent errors, counts as already present, and the copy leaves its row, groups, body and claim as they are. An existing SQL row always wins, see [Writing to SQL](#writing-to-sql). Group retry, archive and unarchive act only on the messages copied so far, an accepted edge case | -| Group comments | Optional | Copied in the background right after the unresolved failed messages, before the event log and the archived and resolved messages. It has no window and no setting turns it off. A comment is missing from SQL until this copy reaches it. Blank comments are not copied. The next retention sweep removes a copied comment on a group with no failed message in SQL, see [Rows removed after the copy](#rows-removed-after-the-copy) | +| Group comments | Optional | Copied in the background right after the unresolved failed messages, before the event log and the archived and resolved messages. It has no window and no setting turns it off. A comment is missing from SQL until this copy reaches it. Blank comments are not copied. Retention is paused until every category is finished. After that, a sweep removes a copied comment on a group with no failed message in SQL, see [Rows removed after the copy](#rows-removed-after-the-copy) | | Event log | Optional | The history behind the ServicePulse activity feed. On a busy instance it holds a row for every failure, retry and submission | | Archived and resolved failed messages, with bodies | Optional | The biggest category by far, and most of the copying time | @@ -252,7 +253,7 @@ A value SQL can hold only after changing it is not a skip. Those rows are copied - **Rows RavenDB expires during the copy are not skips either.** Only archived or resolved failed messages and event log items expire, plus some unresolved messages from 6.18 or earlier (see [Open decisions](#rows-removed-after-the-copy)). - A message that expires between the copy reading it and reading its body is a `BodyMissing` fault skip. A retry gets past it. - If the message a stopped copy was at expires before the next start, the category stops with an error naming the missing id. `--migration-retry` gets past it. - - A window shorter than the retention period keeps the background copy clear of the expiry sweep. + - A window shorter than the retention period keeps the background copy clear of RavenDB's expiry. SQL retention does not delete during the copy. ### Startup checks @@ -302,7 +303,7 @@ flowchart LR - **A failed message is written as one row**, with its status unchanged. Its older attempts are dropped, see [Open decisions](#values-that-change-or-merge-in-sql). - **An existing SQL row always wins.** The copy never updates a row and counts an existing row as already present, not as a skip. When ingestion created the row first, its attempt count and first failure time can omit earlier RavenDB failures, and it can hold an older payload than RavenDB's newest attempt. These outcomes are accepted. -- **The copy accepts unlikely races with live operations.** A delayed retry confirmation can be consumed before an unresolved message whose claim a re-failure removed arrives, leaving it unresolved, unless the message is among the recent errors. A message archived or resolved in SQL and then deleted by retention before the copy reaches it can arrive again as unresolved. A queued edit-and-retry is discarded if its original message has not arrived. +- **The copy accepts unlikely races with live operations.** A delayed retry confirmation can be consumed before an unresolved message whose claim a re-failure removed arrives, leaving it unresolved, unless the message is among the recent errors. A queued edit-and-retry is discarded if its original message has not arrived. - **Bodies are immutable and written only if absent.** The body store keeps one body per `UniqueMessageId`, and each backend refuses to replace one that exists: the file system through an exclusive move, Azure Blob and S3 through a conditional upload. The first writer wins, so a body the copy stores just before ingestion does is the body that stays. That is safe only because every attempt of one message carries the same body bytes, which ingestion already assumes. An S3-compatible store that ignores `If-None-Match` falls back to a check followed by an unconditional upload, which can replace a live body. - **A failed message keeps its failure groups and its last-modified time**, so filtered lists show the same messages as before. A failure group with no id is the exception, see [Open decisions](#values-that-change-or-merge-in-sql). - **`UniqueMessageId` keeps its value** but becomes a `uniqueidentifier`. It is the primary key, the ServicePulse URL, the retry key and the body key. @@ -511,7 +512,7 @@ The dry run counts the subscription and endpoint settings merges before anything ### Rows removed after the copy -- **The next retention sweep removes a copied group comment whose group has no failed message in SQL**, because the sweep deletes a comment whose group has no row. The group has none when its messages are archived or resolved, when they are gone from RavenDB, or when the copy skipped them. Comments wait until the unresolved failed messages category is Done or Abandoned, so waiting for that copy alone does not cause comment loss. Abandoning it can leave groups without messages in SQL. Nothing keeps a comment on a group with only archived or resolved messages, even when those messages copy later. The copy names each such comment, in a warning starting `Changed GroupComment/ in category GroupComments on the way into SQL: The group '' has no copied failed message`, which also quotes the whole comment. +- **After every category is finished, a retention sweep removes a copied group comment whose group has no failed message in SQL**, because the sweep deletes a comment whose group has no row. The group has none when its messages are archived or resolved and were not copied, when they are gone from RavenDB, when the copy skipped them, or when the copy of the unresolved or archived and resolved messages was abandoned. Retention is paused while any category is unfinished, so a comment survives while the messages of its group are still copying. The copy names each comment on a group with no copied failed message, in a warning starting `Changed GroupComment/ in category GroupComments on the way into SQL: The group '' has no copied failed message`, which also quotes the whole comment. - **A `MessageFailed` event still waiting to be sent for a message outside the recent errors, retry-issued messages and claim holders is lost when the message is archived, resolved or not yet copied.** ServiceControl looks the message up when it sends the event. Archived and resolved messages last modified before the cutoff arrive only with the background copy, so the lookup finds nothing, and the event is deleted with no log line. RavenDB would have sent it. The same lookup can fail for an older unresolved message the background copy has not reached yet. The required copy covers the events for messages last modified at or after one hour before the anchor, with no upper bound, or messages that are retry-issued or hold a claim, and nothing else covers the rest, an accepted gap. - **Unresolved messages from version 6.18 or earlier can expire during the copy.** On those versions, a message that failed again after being archived or resolved kept its expiry. One deleted before the copy reads it is not copied and not counted. No log line names these messages yet. diff --git a/docs/migration/ravendb-to-sql-migration-system-design.md b/docs/migration/ravendb-to-sql-migration-system-design.md index 9dace474bb..114960e092 100644 --- a/docs/migration/ravendb-to-sql-migration-system-design.md +++ b/docs/migration/ravendb-to-sql-migration-system-design.md @@ -160,6 +160,14 @@ Windowing for the other two: `MigrationEngineOptions.WindowFor` supplies the win `Migration/ThrottlePauseMilliseconds` inserts a delay between optional-category batches, skipping the first batch of each category. Required categories are never throttled. +## Retention during migration + +`RetentionSweeper` reads every checkpoint through `IMigrationCheckpointStore` before it records a start or deletes a row, on the hourly tick, in `SweepNow` and in `TryStartManualSweep`. A checkpoint whose state is not `IsFinished` pauses it, an unknown category included. No copier flag is involved, so a restart pauses and resumes from the persisted checkpoints alone. + +The check happens before the sweeper takes its single-flight lock. An unfinished category causes the check to log and return without recording a run, so `GetStatus` reports not running. `TryStartManualSweep` returns `Error` with a reason, and the controller maps it to 400. + +A failed read deletes nothing. The hourly path logs the error and tries again on the next tick, and the manual path throws. + ## Copying a batch `MigrationEngine.RunCategoryAsync` is the per-category loop. Every store-specific step is delegated. @@ -289,7 +297,7 @@ Every reader derives from `MigrationCategoryReader` and every writer | 14 | `CustomChecks` | Required | `CustomChecksReader`, `CustomChecksWriter` | The RavenDB reader flags a check whose id and category match one of the RavenDB persister's own six checks with the `SourceStorageCheck` metadata key, and the writer skips a flagged row as `SourceStorageCheck` without knowing any id. A RavenDB audit instance's dirty memory result reports under another category, so it is copied | | 15 | `FailedErrorImports` | Required | `FailedErrorImportsReader`, `FailedErrorImportsWriter` | Carries bodies inline in `Read`, never calls `ReadBody` | | 1 | `UnresolvedFailedMessages` | Optional | `UnresolvedFailedMessagesReader`, `UnresolvedFailedMessagesWriter` | Carries bodies, no window, and attaches no claim state. `MigrationEngineOptions.FromSettings` always selects it, and the engine runs it as optional: it throttles between batches, and an exception leaves it copying with `LastError` until the next start. `FailedMessagesWriterBase` inserts only messages the target lacks. The writer counts unresolved rows. `RavenMigrationSource.ReadBody` reads the body attachment for both failed-message categories | -| 2 | `GroupComments` | Optional | `GroupCommentsReader`, `GroupCommentsWriter` | Unwindowed and always selected, with `MustFollow` set to `UnresolvedFailedMessages`, not a data link, so the retention sweep does not find a comment before the unresolved messages of its group. The engine blocks it until that category is `IsFinished`. A comment is absent from SQL until this copy reaches it. Skips blanks as `BlankGroupComment`. Reports group ids that differ only in trailing spaces as merges on SQL Server. Reports each copied comment on a group with no copied failed message as a change. Abandoning the unresolved failed messages copy can leave such groups. Nothing protects a comment on a group with only archived or resolved messages | +| 2 | `GroupComments` | Optional | `GroupCommentsReader`, `GroupCommentsWriter` | Unwindowed and always selected, with `MustFollow` set to `UnresolvedFailedMessages`, not a data link, so the copy does not add a comment before the unresolved messages of its group. The engine blocks it until that category is `IsFinished`. A comment is absent from SQL until this copy reaches it. Skips blanks as `BlankGroupComment`. Reports group ids that differ only in trailing spaces as merges on SQL Server. Reports each copied comment on a group with no copied failed message as a change. Abandoning the unresolved failed messages copy can leave such groups. Retention is paused until every category is finished, so a comment on a group with only archived or resolved messages survives while those copy, and a sweep after the pause removes it if the group still has no message | | 3 | `EventLog` | Optional | `EventLogReader`, `EventLogWriter` | Windowed, store-keyed, abandon-only. Skips as `PastRetention` | | 4 | `ArchivedAndResolvedFailedMessages` | Optional | `ArchivedAndResolvedFailedMessagesReader`, `ArchivedAndResolvedFailedMessagesWriter` | Windowed, carries bodies, shares `FailedMessagesWriter` preparation. Skips as `PastRetention` | diff --git a/src/ServiceControl.Api/Contracts/RetentionPurgeResponse.cs b/src/ServiceControl.Api/Contracts/RetentionPurgeResponse.cs index bcf9edf47a..f459019e52 100644 --- a/src/ServiceControl.Api/Contracts/RetentionPurgeResponse.cs +++ b/src/ServiceControl.Api/Contracts/RetentionPurgeResponse.cs @@ -4,8 +4,8 @@ namespace ServiceControl.Api.Contracts; /// /// Response body for POST /api/maintenance/retention/purge. The Status field signals the -/// outcome: started (202), already-running (409), or -/// not-supported (501). +/// outcome: started (202), alreadyRunning (409), +/// error (400, with a Reason), or notSupported (501). /// public class RetentionPurgeResponse { @@ -17,6 +17,6 @@ public class RetentionPurgeResponse public DateTime? EventsCutoff { get; set; } - /// A human-readable reason included when the operation is not supported. + /// A human-readable reason included when the operation is not supported or cannot start. public string Reason { get; set; } } \ No newline at end of file diff --git a/src/ServiceControl.Migration.AcceptanceTests/GroupCommentsMigrationTests.cs b/src/ServiceControl.Migration.AcceptanceTests/GroupCommentsMigrationTests.cs index eefb0e1485..4b9a7598e0 100644 --- a/src/ServiceControl.Migration.AcceptanceTests/GroupCommentsMigrationTests.cs +++ b/src/ServiceControl.Migration.AcceptanceTests/GroupCommentsMigrationTests.cs @@ -4,9 +4,11 @@ namespace ServiceControl.Migration.AcceptanceTests; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; using NUnit.Framework; using ServiceControl.Hosting.Commands; using ServiceControl.MessageFailures; +using ServiceControl.Persistence; using ServiceControl.Persistence.DataMigration; using ServiceControl.Persistence.Infrastructure; using ServiceControl.Persistence.Tests; @@ -59,13 +61,17 @@ public async Task A_comment_on_an_unresolved_group_survives_a_retention_sweep_be await MigrateCommand.Run(Settings, AllowingAnUnreleasedMigration()); - // The sweep that runs once ServiceControl opens, before the background copy has reached the unresolved message. - await RunRetentionSweep(); + // A sweep that runs once ServiceControl opens, before the background copy has reached the unresolved message. + Assert.That((await TryRetentionSweep()).Outcome, Is.EqualTo(RetentionSweepStatus.Error), "no category is finished, so nothing is deleted"); await RunHostUntilTheApiAnswers(); await WaitUntil( async () => (await ReadCheckpoint(MigrationCategoryIds.GroupComments))?.State.IsFinished() == true, "the group comments copy finished", TimeSpan.FromMinutes(1)); + await WaitUntil( + async () => (await QueryTarget(dbContext => dbContext.MigrationCheckpoints.AsNoTracking().Select(checkpoint => checkpoint.State).ToListAsync())).All(state => state.IsFinished()), + "every migration category finished", + TimeSpan.FromMinutes(1)); await RunRetentionSweep(); var comments = (await GroupsStore.GetUnresolvedGroupsByClassifier(unresolved.Groups.Single().Type, null, new PagingInfo())).ToDictionary(view => view.Id, view => view.Comment); diff --git a/src/ServiceControl.Migration.AcceptanceTests/MigrationAcceptanceTest.cs b/src/ServiceControl.Migration.AcceptanceTests/MigrationAcceptanceTest.cs index 082ffff66b..a78353fb5c 100644 --- a/src/ServiceControl.Migration.AcceptanceTests/MigrationAcceptanceTest.cs +++ b/src/ServiceControl.Migration.AcceptanceTests/MigrationAcceptanceTest.cs @@ -593,13 +593,17 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except // Resolved from the target services, whose hosted sweeper never starts, so a test decides when a sweep runs. protected async Task RunRetentionSweep() { - var sweeper = targetServices.GetRequiredService(); - var attempt = sweeper.TryStartManualSweep(null, null); + var attempt = await TryRetentionSweep(); Assert.That(attempt.Outcome, Is.EqualTo(RetentionSweepStatus.Started)); + var sweeper = targetServices.GetRequiredService(); await WaitUntil(() => Task.FromResult(!sweeper.GetStatus().IsRunning), "the retention sweep finished", TimeSpan.FromMinutes(1)); Assert.That(sweeper.GetStatus().LastOutcome, Is.EqualTo(RetentionSweepOutcome.Succeeded)); } + // Retention does not delete while a migration category is unfinished, so a test that sweeps then asks for this. + protected Task TryRetentionSweep() => + targetServices.GetRequiredService().TryStartManualSweep(null, null); + sealed class UnstartedApplicationLifetime : IHostApplicationLifetime { public CancellationToken ApplicationStarted => CancellationToken.None; diff --git a/src/ServiceControl.Migration.AcceptanceTests/When_a_retention_purge_is_requested_during_the_background_copy.cs b/src/ServiceControl.Migration.AcceptanceTests/When_a_retention_purge_is_requested_during_the_background_copy.cs new file mode 100644 index 0000000000..1f5e24dc90 --- /dev/null +++ b/src/ServiceControl.Migration.AcceptanceTests/When_a_retention_purge_is_requested_during_the_background_copy.cs @@ -0,0 +1,39 @@ +namespace ServiceControl.Migration.AcceptanceTests; + +using System.Net; +using System.Net.Http.Json; +using System.Threading.Tasks; +using NUnit.Framework; +using ServiceControl.Api.Contracts; +using ServiceControl.Infrastructure.WebApi; +using ServiceControl.Persistence.DataMigration; + +[TestFixture] +[NonParallelizable] +class When_a_retention_purge_is_requested_during_the_background_copy : MigrationAcceptanceTest +{ + [Test] + public async Task The_purge_answers_400_naming_the_unfinished_category_and_runs_nothing() + { + await SeedSourceKnownEndpoints("Sales"); + await RunRequiredCopy(leaveOptionalIncomplete: true); + + using var purge = await HttpClient.PostAsJsonAsync("api/maintenance/retention/purge", new RetentionPurgeRequest(), SerializerOptions.Default); + var body = await purge.Content.ReadFromJsonAsync(SerializerOptions.Default); + + using var statusResponse = await HttpClient.GetAsync("api/maintenance/retention/purge/status"); + var status = await statusResponse.Content.ReadFromJsonAsync(SerializerOptions.Default); + + using (Assert.EnterMultipleScope()) + { + Assert.That(purge.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); + Assert.That(body.Status, Is.EqualTo(RetentionPurgeStatus.Error)); + Assert.That(body.Reason, Does.Contain(MigrationCategoryIds.EventLog)); + Assert.That(body.StartedAt, Is.Null); + Assert.That(statusResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(status.IsRunning, Is.False); + Assert.That(status.LastStartedAt, Is.Null, "a refused purge is not a run"); + Assert.That(status.LastOutcome, Is.Null); + } + } +} diff --git a/src/ServiceControl.Persistence.EFCore/Infrastructure/RetentionSweeper.cs b/src/ServiceControl.Persistence.EFCore/Infrastructure/RetentionSweeper.cs index ad5082de5c..75b5662391 100644 --- a/src/ServiceControl.Persistence.EFCore/Infrastructure/RetentionSweeper.cs +++ b/src/ServiceControl.Persistence.EFCore/Infrastructure/RetentionSweeper.cs @@ -6,6 +6,7 @@ namespace ServiceControl.Persistence.EFCore.Infrastructure; using Microsoft.Extensions.Logging; using ServiceControl.MessageFailures; using ServiceControl.Persistence; +using ServiceControl.Persistence.DataMigration; using ServiceControl.Persistence.EFCore.Abstractions; using ServiceControl.Persistence.EFCore.DbContexts; using ServiceControl.Persistence.EFCore.Entities; @@ -16,12 +17,13 @@ namespace ServiceControl.Persistence.EFCore.Infrastructure; // every run so a changed retention setting takes effect without rewriting any row. // // A manual sweep can be triggered via the API (see IRetentionSweeper / IRetentionApi) with -// caller-supplied cutoffs. -class RetentionSweeper( +// caller-supplied cutoffs. +partial class RetentionSweeper( ILogger logger, TimeProvider timeProvider, IServiceScopeFactory serviceScopeFactory, IBodyStoragePersistence bodyStorage, + IMigrationCheckpointStore checkpointStore, RetentionMetrics metrics, RetentionSweepCustomCheck.State retentionState, EFPersisterSettings settings, @@ -76,11 +78,19 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken = public Task SweepNow(CancellationToken cancellationToken = default) => Sweep(errorCutoff: null, eventsCutoff: null, pace: false, cancellationToken); - public ManualSweepAttempt TryStartManualSweep(DateTime? errorCutoff, DateTime? eventsCutoff, CancellationToken cancellationToken = default) + public async Task TryStartManualSweep(DateTime? errorCutoff, DateTime? eventsCutoff, CancellationToken cancellationToken = default) { + var unfinished = await ReadUnfinishedMigrationCategories(cancellationToken); + if (unfinished is not null) + { + LogPaused(unfinished); + return new ManualSweepAttempt(RetentionSweepStatus.Error, null, errorCutoff, eventsCutoff, + $"Retention cannot run until these migration categories are Complete or Abandoned: {unfinished}."); + } + // Try to acquire the single-flight lock without waiting if a scheduled or manual sweep is // already running (holding the lock) - if (!sweepLock.Wait(0, cancellationToken)) + if (!await sweepLock.WaitAsync(0, cancellationToken)) { return new ManualSweepAttempt(RetentionSweepStatus.AlreadyRunning, status.LastStartedAt, errorCutoff, eventsCutoff); } @@ -118,11 +128,28 @@ async Task SweepWithoutAcquiringLock() async Task Sweep(DateTime? errorCutoff, DateTime? eventsCutoff, bool pace, CancellationToken cancellationToken) { + var unfinished = await ReadUnfinishedMigrationCategories(cancellationToken); + if (unfinished is not null) + { + LogPaused(unfinished); + return; + } + await sweepLock.WaitAsync(cancellationToken); var running = RecordStart(errorCutoff, eventsCutoff); await SweepBody(running, errorCutoff, eventsCutoff, pace, cancellationToken); } + async Task ReadUnfinishedMigrationCategories(CancellationToken cancellationToken) + { + var checkpoints = await checkpointStore.ReadAll(cancellationToken); + var ids = checkpoints.Where(c => !c.State.IsFinished()).Select(c => c.CategoryId).Order(StringComparer.Ordinal).ToList(); + return ids.Count == 0 ? null : string.Join(", ", ids); + } + + [LoggerMessage(LogLevel.Warning, "Retention is paused because there are unfinished database migration categories: {Categories}. Complete or Abandon these to resume the cleanup process.")] + partial void LogPaused(string categories); + // A new snapshot leaves out the previous run's finish time and outcome so they are never read as this run's. RetentionSweepCurrentStatus RecordStart(DateTime? errorCutoff, DateTime? eventsCutoff) { diff --git a/src/ServiceControl.Persistence.Tests/EFCore/ErrorIngestionTestBase.cs b/src/ServiceControl.Persistence.Tests/EFCore/ErrorIngestionTestBase.cs index fd84861ed2..b7adfed3b8 100644 --- a/src/ServiceControl.Persistence.Tests/EFCore/ErrorIngestionTestBase.cs +++ b/src/ServiceControl.Persistence.Tests/EFCore/ErrorIngestionTestBase.cs @@ -9,6 +9,7 @@ namespace ServiceControl.Persistence.Tests; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using NUnit.Framework; +using ServiceControl.Persistence.DataMigration; using ServiceControl.Persistence.EFCore.Abstractions; using ServiceControl.Persistence.EFCore.DbContexts; using ServiceControl.Persistence.EFCore.Entities; @@ -60,6 +61,15 @@ protected async Task Store(params T[] entities) where T : class protected Task CountRetryRows(Guid uniqueMessageId) => Query(dbContext => dbContext.FailedMessageRetries.AsNoTracking().CountAsync(r => r.UniqueMessageId == uniqueMessageId)); + protected async Task SetCheckpoint(string categoryId, MigrationCategoryState state) + { + var store = ServiceProvider.GetRequiredService(); + var existing = await store.Read(categoryId); + await store.Upsert(existing is null + ? new MigrationCheckpoint(categoryId, state, null, 0, 0, null, null, null, null, null, null) + : existing with { State = state }); + } + protected Task RunRetentionSweep() => ServiceProvider.GetServices().OfType().Single().SweepNow(TestContext.CurrentContext.CancellationToken); diff --git a/src/ServiceControl.Persistence.Tests/EFCore/RetentionScheduleTests.cs b/src/ServiceControl.Persistence.Tests/EFCore/RetentionScheduleTests.cs new file mode 100644 index 0000000000..4581ba464b --- /dev/null +++ b/src/ServiceControl.Persistence.Tests/EFCore/RetentionScheduleTests.cs @@ -0,0 +1,88 @@ +namespace ServiceControl.Persistence.Tests; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Time.Testing; +using NUnit.Framework; +using ServiceControl.Persistence.DataMigration; +using ServiceControl.Persistence.EFCore.Entities; +using ServiceControl.Persistence.EFCore.Infrastructure; + +// Fires the hosted sweeper through its own clock, so the tick does not also fire the sweepers of the tests running in parallel. +class RetentionScheduleTests : ErrorIngestionTestBase +{ + readonly SweeperLog sweeperLog = new(); + FakeTimeProvider clock; + + public RetentionScheduleTests() + { + var registerServices = RegisterServices; + RegisterServices = services => + { + registerServices(services); + clock = new FakeTimeProvider(PersistenceTestsContext.FakeTime.GetUtcNow()); + services.AddSingleton(clock); + services.AddSingleton(sweeperLog); + }; + } + + [Test] + public async Task The_hourly_sweep_stays_paused_until_every_category_is_finished_and_then_deletes() + { + await Store(new GroupCommentEntity { GroupId = "orphaned-group", Comment = "Raised with the shipping team" }); + await SetCheckpoint(MigrationCategoryIds.EventLog, MigrationCategoryState.InProgress); + + await WaitUntil(() => + { + clock.Advance(TimeSpan.FromMinutes(1)); + return Task.FromResult(sweeperLog.Messages.Any(message => message.Contains("paused"))); + }, "the first sweep to pause", TimeSpan.FromSeconds(60)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(await FindGroupComment("orphaned-group"), Is.Not.Null); + Assert.That(ServiceProvider.GetRequiredService().GetStatus().LastStartedAt, Is.Null, "a paused tick is not a sweep"); + } + + clock.Advance(TimeSpan.FromHours(1)); + await WaitUntil(() => Task.FromResult(sweeperLog.Messages.Count(message => message.Contains("paused")) >= 2), + "the next hourly sweep to pause", TimeSpan.FromSeconds(60)); + Assert.That(await FindGroupComment("orphaned-group"), Is.Not.Null); + + await SetCheckpoint(MigrationCategoryIds.EventLog, MigrationCategoryState.Complete); + clock.Advance(TimeSpan.FromHours(1)); + await WaitUntil(async () => await FindGroupComment("orphaned-group") is null, "the next hourly sweep to delete", TimeSpan.FromSeconds(60)); + + Assert.That(sweeperLog.Messages.Count(message => message.Contains("paused")), Is.GreaterThanOrEqualTo(2)); + } + + sealed class SweeperLog : ILoggerProvider + { + readonly ConcurrentQueue messages = new(); + + public IReadOnlyList Messages => [.. messages]; + + public ILogger CreateLogger(string categoryName) => + categoryName == typeof(RetentionSweeper).FullName ? new Recorder(messages) : NullLogger.Instance; + + public void Dispose() + { + } + + sealed class Recorder(ConcurrentQueue messages) : ILogger + { + 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) => + messages.Enqueue(formatter(state, exception)); + } + } +} diff --git a/src/ServiceControl.Persistence.Tests/EFCore/RetentionSweepTests.cs b/src/ServiceControl.Persistence.Tests/EFCore/RetentionSweepTests.cs index 4319cff284..cf34f6ba41 100644 --- a/src/ServiceControl.Persistence.Tests/EFCore/RetentionSweepTests.cs +++ b/src/ServiceControl.Persistence.Tests/EFCore/RetentionSweepTests.cs @@ -13,6 +13,7 @@ namespace ServiceControl.Persistence.Tests; using NUnit.Framework; using ServiceControl.EventLog; using ServiceControl.MessageFailures; +using ServiceControl.Persistence.DataMigration; using ServiceControl.Persistence.EFCore.Entities; using ServiceControl.Persistence.EFCore.Infrastructure; using ServiceControl.Persistence.EFCore.Infrastructure.Metrics; @@ -22,6 +23,7 @@ class RetentionSweepTests : ErrorIngestionTestBase { readonly CancelAfterBatchDelete cancelAfterBatchDelete = new(); readonly CancelDuringNextQuery cancelDuringNextQuery = new(); + readonly FailCheckpointReads failCheckpointReads = new(); public RetentionSweepTests() { @@ -31,6 +33,7 @@ public RetentionSweepTests() registerBodyStorage(services); PersistenceTestsContext.InterceptDatabaseCommands(services, cancelAfterBatchDelete); PersistenceTestsContext.InterceptDatabaseCommands(services, cancelDuringNextQuery); + PersistenceTestsContext.InterceptDatabaseCommands(services, failCheckpointReads); }; } @@ -499,7 +502,7 @@ public async Task Manual_sweep_uses_the_caller_supplied_error_cutoff_to_delete_e // A caller-supplied cutoff of 15 days ago is earlier than the message, so the manual sweep deletes it. var message = await SeedFailedMessage(FailedMessageStatus.Resolved, Now.AddDays(-20)); - var attempt = GetSweeper().TryStartManualSweep(Now.AddDays(-15), null); + var attempt = await GetSweeper().TryStartManualSweep(Now.AddDays(-15), null); await WaitForManualSweepToFinish(); @@ -520,7 +523,7 @@ public async Task Manual_sweep_uses_the_caller_supplied_events_cutoff() await Store(EventLogRow("to-delete", Now.AddDays(-10))); await Store(EventLogRow("to-keep", Now.AddDays(-3))); - GetSweeper().TryStartManualSweep(null, Now.AddDays(-5)); + await GetSweeper().TryStartManualSweep(null, Now.AddDays(-5)); await WaitForManualSweepToFinish(); @@ -540,7 +543,7 @@ public async Task Manual_sweep_with_null_cutoffs_keeps_the_default_derivation() var withinRetention = await SeedFailedMessage(FailedMessageStatus.Resolved, Now.AddDays(-29)); var pastRetention = await SeedFailedMessage(FailedMessageStatus.Resolved, Now.AddDays(-31)); - GetSweeper().TryStartManualSweep(null, null); + await GetSweeper().TryStartManualSweep(null, null); await WaitForManualSweepToFinish(); @@ -557,7 +560,7 @@ public async Task Manual_sweep_runs_in_the_background_and_reports_status() await SeedFailedMessage(FailedMessageStatus.Resolved, Now.AddDays(-31)); var sweeper = GetSweeper(); - var attempt = sweeper.TryStartManualSweep(Now.AddDays(-30), null); + var attempt = await sweeper.TryStartManualSweep(Now.AddDays(-30), null); Assert.That(attempt.Outcome, Is.EqualTo(RetentionSweepStatus.Started)); Assert.That(attempt.StartedAt, Is.Not.Null); @@ -585,7 +588,7 @@ public async Task Manual_sweep_with_failing_passes_reports_failed_with_every_err EFSettings.EventsRetentionPeriod = TimeSpan.FromDays(1_000_000); var sweeper = GetSweeper(); - sweeper.TryStartManualSweep(null, null); + await sweeper.TryStartManualSweep(null, null); await WaitForManualSweepToFinish(); @@ -627,7 +630,7 @@ public async Task A_cancelled_sweep_keeps_the_errors_of_passes_that_failed_first cancelAfterBatchDelete.Cancellation = cancellation; var sweeper = GetSweeper(); - sweeper.TryStartManualSweep(null, null, cancellation.Token); + await sweeper.TryStartManualSweep(null, null, cancellation.Token); await WaitForManualSweepToFinish(); @@ -646,14 +649,14 @@ public async Task Starting_a_sweep_clears_the_previous_run_s_outcome() EFSettings.ErrorRetentionPeriod = TimeSpan.FromDays(1_000_000); var sweeper = GetSweeper(); - sweeper.TryStartManualSweep(null, null); + await sweeper.TryStartManualSweep(null, null); await WaitForManualSweepToFinish(); var previous = sweeper.GetStatus(); EFSettings.ErrorRetentionPeriod = TimeSpan.FromDays(30); - var second = sweeper.TryStartManualSweep(null, null); + var second = await sweeper.TryStartManualSweep(null, null); var running = sweeper.GetStatus(); await WaitForManualSweepToFinish(); @@ -680,9 +683,9 @@ public async Task A_second_manual_sweep_is_refused_while_one_is_running() await SeedMoreThanOneBatchOfExpiredMessages(); var sweeper = GetSweeper(); - var first = sweeper.TryStartManualSweep(Now.AddDays(-30), null); + var first = await sweeper.TryStartManualSweep(Now.AddDays(-30), null); // Immediately request a second sweep on the same thread while the first is still deleting. - var second = sweeper.TryStartManualSweep(Now.AddDays(-30), null); + var second = await sweeper.TryStartManualSweep(Now.AddDays(-30), null); await WaitForManualSweepToFinish(); @@ -705,7 +708,7 @@ public async Task A_sweep_cancelled_between_batches_is_recorded_as_cancelled() using var recorded = ListenToRetentionMetrics(); var sweeper = GetSweeper(); - sweeper.TryStartManualSweep(Now.AddDays(-30), null, cancellation.Token); + await sweeper.TryStartManualSweep(Now.AddDays(-30), null, cancellation.Token); await WaitForManualSweepToFinish(); @@ -731,7 +734,7 @@ public async Task An_event_log_pass_cancelled_between_batches_is_recorded_as_can using var recorded = ListenToRetentionMetrics(); var sweeper = GetSweeper(); - sweeper.TryStartManualSweep(null, null, cancellation.Token); + await sweeper.TryStartManualSweep(null, null, cancellation.Token); await WaitForManualSweepToFinish(); @@ -753,6 +756,7 @@ public void DisarmInterceptors() { cancelAfterBatchDelete.Cancellation = null; cancelDuringNextQuery.Arm(null, null); + failCheckpointReads.Armed = false; } [Test] @@ -764,7 +768,7 @@ public async Task A_sweep_cancelled_while_a_query_runs_reports_cancelled_without cancelDuringNextQuery.Arm(cancellation, PersistenceTestsContext.SqlToDelayFor(TimeSpan.FromSeconds(20))); var sweeper = GetSweeper(); - sweeper.TryStartManualSweep(null, null, cancellation.Token); + await sweeper.TryStartManualSweep(null, null, cancellation.Token); await WaitForManualSweepToFinish(); @@ -789,6 +793,208 @@ public async Task A_failed_pass_reports_only_the_first_line_of_its_error() Assert.That(GetSweeper().GetStatus().LastError, Is.EqualTo($"FailedMessages: Simulated body storage failure for {unluckyBody}")); } + static readonly MigrationCategoryState[] UnfinishedStates = [.. Enum.GetValues().Where(state => !state.IsFinished())]; + + // One of everything the sweep deletes: an expired failed message, an expired event, and a comment on a group that has no message. + async Task<(Guid Message, string Comment)> SeedEverythingExpired() + { + EFSettings.EventsRetentionPeriod = TimeSpan.FromDays(14); + var message = await SeedFailedMessage(FailedMessageStatus.Resolved, Now.AddDays(-31), bodyStoredExternally: true); + await Store(EventLogRow("expired", Now.AddDays(-15))); + var commentGroup = Guid.NewGuid().ToString(); + await Store(new GroupCommentEntity { GroupId = commentGroup, Comment = "Raised with the shipping team" }); + return (message, commentGroup); + } + + async Task AssertNothingWasDeleted((Guid Message, string Comment) seeded) + { + using (Assert.EnterMultipleScope()) + { + Assert.That(await FindFailedMessage(seeded.Message), Is.Not.Null, "the failed message"); + Assert.That(RecordedBodies.Deleted, Is.Empty, "the body"); + Assert.That(await GetRemainingMarkers(), Does.Contain("expired"), "the event log item"); + Assert.That(await FindGroupComment(seeded.Comment), Is.Not.Null, "the group comment"); + } + } + + async Task AssertEverythingWasDeleted((Guid Message, string Comment) seeded) + { + using (Assert.EnterMultipleScope()) + { + Assert.That(await FindFailedMessage(seeded.Message), Is.Null, "the failed message"); + Assert.That(await GetRemainingMarkers(), Does.Not.Contain("expired"), "the event log item"); + Assert.That(await FindGroupComment(seeded.Comment), Is.Null, "the group comment"); + } + } + + [Test] + public async Task A_sweep_deletes_nothing_while_a_category_is_unfinished([ValueSource(nameof(UnfinishedStates))] MigrationCategoryState state) + { + var seeded = await SeedEverythingExpired(); + await SetCheckpoint(MigrationCategoryIds.EventLog, state); + + await RunRetentionSweep(); + + var status = GetSweeper().GetStatus(); + using (Assert.EnterMultipleScope()) + { + Assert.That(status.LastStartedAt, Is.Null, "a deferred check is not a sweep"); + Assert.That(status.IsRunning, Is.False); + Assert.That(status.LastOutcome, Is.Null); + } + + await AssertNothingWasDeleted(seeded); + } + + [Test] + public async Task A_manual_purge_deletes_nothing_and_says_why_while_a_category_is_unfinished([ValueSource(nameof(UnfinishedStates))] MigrationCategoryState state) + { + var seeded = await SeedEverythingExpired(); + await SetCheckpoint(MigrationCategoryIds.EventLog, state); + + var attempt = await GetSweeper().TryStartManualSweep(Now.AddDays(-1), Now.AddDays(-1)); + + var status = GetSweeper().GetStatus(); + using (Assert.EnterMultipleScope()) + { + Assert.That(attempt.Outcome, Is.EqualTo(RetentionSweepStatus.Error)); + Assert.That(attempt.StartedAt, Is.Null); + Assert.That(attempt.Reason, Does.Contain(MigrationCategoryIds.EventLog)); + Assert.That(status.LastStartedAt, Is.Null); + Assert.That(status.IsRunning, Is.False); + } + + await AssertNothingWasDeleted(seeded); + } + + [Test] + public async Task A_category_the_sweeper_does_not_know_pauses_deletion_until_it_is_finished() + { + var seeded = await SeedEverythingExpired(); + await SetCheckpoint("CategoryFromANewerRelease", MigrationCategoryState.InProgress); + + await RunRetentionSweep(); + await AssertNothingWasDeleted(seeded); + + await SetCheckpoint("CategoryFromANewerRelease", MigrationCategoryState.Complete); + await RunRetentionSweep(); + await AssertEverythingWasDeleted(seeded); + } + + [Test] + public async Task Deletion_resumes_once_every_category_is_complete_or_abandoned([Values(MigrationCategoryState.Complete, MigrationCategoryState.Abandoned)] MigrationCategoryState finished) + { + var seeded = await SeedEverythingExpired(); + await SetCheckpoint(MigrationCategoryIds.GroupComments, MigrationCategoryState.Complete); + await SetCheckpoint(MigrationCategoryIds.EventLog, MigrationCategoryState.InProgress); + + await RunRetentionSweep(); + await AssertNothingWasDeleted(seeded); + + await SetCheckpoint(MigrationCategoryIds.EventLog, finished); + await RunRetentionSweep(); + + await AssertEverythingWasDeleted(seeded); + Assert.That(GetSweeper().GetStatus().LastOutcome, Is.EqualTo(RetentionSweepOutcome.Succeeded)); + } + + [Test] + public async Task A_manual_purge_runs_once_every_category_is_finished() + { + var seeded = await SeedEverythingExpired(); + await SetCheckpoint(MigrationCategoryIds.EventLog, MigrationCategoryState.Halted); + + var paused = await GetSweeper().TryStartManualSweep(null, null); + + await SetCheckpoint(MigrationCategoryIds.EventLog, MigrationCategoryState.Abandoned); + var resumed = await GetSweeper().TryStartManualSweep(null, null); + await WaitForManualSweepToFinish(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(paused.Outcome, Is.EqualTo(RetentionSweepStatus.Error)); + Assert.That(resumed.Outcome, Is.EqualTo(RetentionSweepStatus.Started), "a refused purge must not take the single-flight lock"); + } + + await AssertEverythingWasDeleted(seeded); + } + + [Test] + public async Task A_failed_category_keeps_deletion_paused_however_many_others_are_finished() + { + var seeded = await SeedEverythingExpired(); + await SetCheckpoint(MigrationCategoryIds.GroupComments, MigrationCategoryState.Complete); + await SetCheckpoint(MigrationCategoryIds.EventLog, MigrationCategoryState.Abandoned); + await SetCheckpoint(MigrationCategoryIds.ArchivedAndResolvedFailedMessages, MigrationCategoryState.CompleteWithErrors); + + await RunRetentionSweep(); + await RunRetentionSweep(); + + await AssertNothingWasDeleted(seeded); + } + + [Test] + public async Task An_orphaned_comment_survives_until_the_remaining_categories_finish() + { + var group = Guid.NewGuid().ToString(); + await Store(new GroupCommentEntity { GroupId = group, Comment = "Raised with the shipping team" }); + await SetCheckpoint(MigrationCategoryIds.GroupComments, MigrationCategoryState.Complete); + await SetCheckpoint(MigrationCategoryIds.ArchivedAndResolvedFailedMessages, MigrationCategoryState.InProgress); + + await RunRetentionSweep(); + Assert.That(await FindGroupComment(group), Is.Not.Null, "a category is still unfinished"); + + await SetCheckpoint(MigrationCategoryIds.ArchivedAndResolvedFailedMessages, MigrationCategoryState.Complete); + await RunRetentionSweep(); + Assert.That(await FindGroupComment(group), Is.Null); + } + + [Test] + public async Task A_sweeper_created_after_a_restart_still_finds_the_category_unfinished() + { + var seeded = await SeedEverythingExpired(); + await SetCheckpoint(MigrationCategoryIds.EventLog, MigrationCategoryState.InProgress); + + var restarted = ActivatorUtilities.CreateInstance(ServiceProvider); + await restarted.SweepNow(TestContext.CurrentContext.CancellationToken); + var attempt = await restarted.TryStartManualSweep(null, null); + + Assert.That(attempt.Outcome, Is.EqualTo(RetentionSweepStatus.Error)); + await AssertNothingWasDeleted(seeded); + } + + [Test] + public async Task A_sweep_that_cannot_read_the_checkpoints_deletes_nothing_and_does_not_take_the_lock() + { + var seeded = await SeedEverythingExpired(); + failCheckpointReads.Armed = true; + + Assert.ThrowsAsync(() => RunRetentionSweep()); + await AssertNothingWasDeleted(seeded); + + failCheckpointReads.Armed = false; + await RunRetentionSweep(); + await AssertEverythingWasDeleted(seeded); + } + + [Test] + public async Task A_manual_purge_that_cannot_read_the_checkpoints_deletes_nothing_and_does_not_take_the_lock() + { + var seeded = await SeedEverythingExpired(); + failCheckpointReads.Armed = true; + + Assert.ThrowsAsync(() => GetSweeper().TryStartManualSweep(null, null)); + Assert.That(GetSweeper().GetStatus().LastStartedAt, Is.Null); + await AssertNothingWasDeleted(seeded); + + failCheckpointReads.Armed = false; + var attempt = await GetSweeper().TryStartManualSweep(null, null); + await WaitForManualSweepToFinish(); + + Assert.That(attempt.Outcome, Is.EqualTo(RetentionSweepStatus.Started)); + await AssertEverythingWasDeleted(seeded); + } + async Task SeedMoreThanOneBatchOfExpiredMessages() { var rows = new List(); @@ -815,6 +1021,25 @@ async Task SeedMoreThanOneBatchOfExpiredMessages() await Store([.. rows]); } + // PostgreSQL names the table migration_checkpoints and SQL Server MigrationCheckpoints. + static bool ReadsCheckpoints(DbCommand command) => command.CommandText.Replace("_", "").Contains("MigrationCheckpoint", StringComparison.OrdinalIgnoreCase); + + // Fails the read of the migration checkpoints, which is the read the sweep makes before it deletes anything. + class FailCheckpointReads : DbCommandInterceptor + { + public volatile bool Armed; + + public override ValueTask> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + if (Armed && ReadsCheckpoints(command)) + { + throw new InvalidOperationException("Simulated checkpoint read failure"); + } + + return base.ReaderExecutingAsync(command, eventData, result, cancellationToken); + } + } + // Slows the next query down on the server and cancels while it runs, where SqlClient reports the // cancellation as a SqlException rather than an OperationCanceledException. class CancelDuringNextQuery : DbCommandInterceptor @@ -830,7 +1055,8 @@ public void Arm(CancellationTokenSource cancellation, string delaySql) public override ValueTask> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) { - if (Interlocked.Exchange(ref cancellation, null) is { } armed) + // The sweep reads the migration checkpoints before its first query, and that read is not the one under test. + if (!ReadsCheckpoints(command) && Interlocked.Exchange(ref cancellation, null) is { } armed) { command.CommandText = delaySql + Environment.NewLine + command.CommandText; armed.CancelAfter(TimeSpan.FromMilliseconds(500)); diff --git a/src/ServiceControl.Persistence/IRetentionSweeper.cs b/src/ServiceControl.Persistence/IRetentionSweeper.cs index 96b52112c9..5159c43de1 100644 --- a/src/ServiceControl.Persistence/IRetentionSweeper.cs +++ b/src/ServiceControl.Persistence/IRetentionSweeper.cs @@ -2,6 +2,7 @@ namespace ServiceControl.Persistence; using System; using System.Threading; +using System.Threading.Tasks; /// /// A persister-agnostic retention sweep operation. Only persisters that actually scan and @@ -15,8 +16,8 @@ public interface IRetentionSweeper /// /// Starts a full retention sweep on a background task /// - /// A snapshot describing the run that was started; will respond with a status of AlreadyRunning if there is already a sweep running. - ManualSweepAttempt TryStartManualSweep(DateTime? errorCutoff, DateTime? eventsCutoff, CancellationToken cancellationToken = default); + /// A snapshot describing the run, or AlreadyRunning or Error when no run starts. + Task TryStartManualSweep(DateTime? errorCutoff, DateTime? eventsCutoff, CancellationToken cancellationToken = default); /// /// A point-in-time snapshot of current sweep execution state for status polling. diff --git a/src/ServiceControl.Persistence/ManualSweepAttempt.cs b/src/ServiceControl.Persistence/ManualSweepAttempt.cs index 451f59c66d..e093f7cbfb 100644 --- a/src/ServiceControl.Persistence/ManualSweepAttempt.cs +++ b/src/ServiceControl.Persistence/ManualSweepAttempt.cs @@ -7,4 +7,5 @@ public sealed record ManualSweepAttempt( RetentionSweepStatus Outcome, DateTime? StartedAt, DateTime? ErrorCutoff, - DateTime? EventsCutoff); \ No newline at end of file + DateTime? EventsCutoff, + string? Reason = null); \ No newline at end of file diff --git a/src/ServiceControl.Persistence/RetentionSweepStatus.cs b/src/ServiceControl.Persistence/RetentionSweepStatus.cs index b7a1f9ca52..0aedda5cbd 100644 --- a/src/ServiceControl.Persistence/RetentionSweepStatus.cs +++ b/src/ServiceControl.Persistence/RetentionSweepStatus.cs @@ -6,5 +6,7 @@ public enum RetentionSweepStatus /// The sweep was started on a background task. Started, /// A sweep is already running. - AlreadyRunning + AlreadyRunning, + /// The sweep could not start; the reason describes the error. + Error } \ No newline at end of file diff --git a/src/ServiceControl.UnitTests/Infrastructure/RetentionApiTests.cs b/src/ServiceControl.UnitTests/Infrastructure/RetentionApiTests.cs index 9d239f829d..c7677effd2 100644 --- a/src/ServiceControl.UnitTests/Infrastructure/RetentionApiTests.cs +++ b/src/ServiceControl.UnitTests/Infrastructure/RetentionApiTests.cs @@ -31,6 +31,22 @@ public async Task A_running_sweep_reports_no_outcome() Assert.That(response.LastOutcome, Is.Null); } + [Test] + public async Task A_refused_purge_is_reported_as_an_error_with_its_reason_and_no_start_time() + { + var attempt = new ManualSweepAttempt(RetentionSweepStatus.Error, null, null, null, "Migration category EventLog is unfinished"); + var services = new ServiceCollection().AddSingleton(new StubSweeper(null, attempt)).BuildServiceProvider(); + + var response = await new RetentionApi(services).Sweep(new ServiceControl.Api.Contracts.RetentionPurgeRequest()); + + using (Assert.EnterMultipleScope()) + { + Assert.That(response.Status, Is.EqualTo(ServiceControl.Api.Contracts.RetentionPurgeStatus.Error)); + Assert.That(response.Reason, Is.EqualTo(attempt.Reason)); + Assert.That(response.StartedAt, Is.Null); + } + } + static Task GetStatus(RetentionSweepOutcome? outcome, string error) { var status = new RetentionSweepCurrentStatus(outcome is null, DateTime.UtcNow, null, null, null, outcome, error); @@ -39,10 +55,10 @@ public async Task A_running_sweep_reports_no_outcome() return new RetentionApi(services).GetStatus(); } - class StubSweeper(RetentionSweepCurrentStatus status) : IRetentionSweeper + class StubSweeper(RetentionSweepCurrentStatus status, ManualSweepAttempt attempt = null) : IRetentionSweeper { - public ManualSweepAttempt TryStartManualSweep(DateTime? errorCutoff, DateTime? eventsCutoff, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); + public Task TryStartManualSweep(DateTime? errorCutoff, DateTime? eventsCutoff, CancellationToken cancellationToken = default) => + attempt is null ? throw new NotSupportedException() : Task.FromResult(attempt); public RetentionSweepCurrentStatus GetStatus() => status; } diff --git a/src/ServiceControl/Infrastructure/Api/RetentionApi.cs b/src/ServiceControl/Infrastructure/Api/RetentionApi.cs index 1a64dd6a7b..3c2f41c01c 100644 --- a/src/ServiceControl/Infrastructure/Api/RetentionApi.cs +++ b/src/ServiceControl/Infrastructure/Api/RetentionApi.cs @@ -17,14 +17,14 @@ class RetentionApi(IServiceProvider serviceProvider) : IRetentionApi public const string NotSupportedReason = "The currently configured storage has no retention sweeper."; - public Task Sweep(RetentionPurgeRequest request, CancellationToken cancellationToken = default) + public async Task Sweep(RetentionPurgeRequest request, CancellationToken cancellationToken = default) { // Resolve the sweeper lazily and optionally — never required via constructor injection, or // a RavenDB-backed instance would throw at resolve time. Absent => 501 Not Implemented. var sweeper = serviceProvider.GetService(); if (sweeper is null) { - return Task.FromResult((RetentionPurgeResponse)new() { Status = RetentionPurgeStatus.NotSupported, Reason = NotSupportedReason }); + return new() { Status = RetentionPurgeStatus.NotSupported, Reason = NotSupportedReason }; } @@ -35,14 +35,18 @@ public Task Sweep(RetentionPurgeRequest request, Cancell if (!TryValidateCutoff(request.ErrorCutoff, out var errorCutoff, out var error) || !TryValidateCutoff(request.EventsCutoff, out var eventsCutoff, out error)) { - return Task.FromResult((RetentionPurgeResponse)new() { Status = RetentionPurgeStatus.Error, Reason = error }); + return new() { Status = RetentionPurgeStatus.Error, Reason = error }; } - var attempt = sweeper.TryStartManualSweep(errorCutoff, eventsCutoff, cancellationToken); + var attempt = await sweeper.TryStartManualSweep(errorCutoff, eventsCutoff, cancellationToken); - return Task.FromResult(attempt.Outcome == RetentionSweepStatus.Started - ? new RetentionPurgeResponse { Status = RetentionPurgeStatus.Started, StartedAt = attempt.StartedAt, ErrorCutoff = attempt.ErrorCutoff, EventsCutoff = attempt.EventsCutoff } - : new RetentionPurgeResponse { Status = RetentionPurgeStatus.AlreadyRunning, StartedAt = attempt.StartedAt }); + return attempt.Outcome switch + { + RetentionSweepStatus.Started => new RetentionPurgeResponse { Status = RetentionPurgeStatus.Started, StartedAt = attempt.StartedAt, ErrorCutoff = attempt.ErrorCutoff, EventsCutoff = attempt.EventsCutoff }, + RetentionSweepStatus.AlreadyRunning => new RetentionPurgeResponse { Status = RetentionPurgeStatus.AlreadyRunning, StartedAt = attempt.StartedAt }, + RetentionSweepStatus.Error => new RetentionPurgeResponse { Status = RetentionPurgeStatus.Error, Reason = attempt.Reason }, + _ => throw new ArgumentOutOfRangeException(nameof(attempt), attempt.Outcome, "Unknown retention sweep status.") + }; } public Task GetStatus(CancellationToken cancellationToken = default) diff --git a/src/ServiceControl/Retention/Api/SystemMaintenanceController.cs b/src/ServiceControl/Retention/Api/SystemMaintenanceController.cs index 9b2496dc30..938034977c 100644 --- a/src/ServiceControl/Retention/Api/SystemMaintenanceController.cs +++ b/src/ServiceControl/Retention/Api/SystemMaintenanceController.cs @@ -19,7 +19,7 @@ public class SystemMaintenanceController(IRetentionApi retentionApi, ICurrentUse { // Starts a full retention purge with caller-supplied cutoffs. The delete work runs in the // background on a host-lifetime token; this returns as soon as the run is accepted (202), - // already running (409), unsupported by the persister (501), or the cutoff was invalid (400). + // already running (409), unsupported by the persister (501), or refused (400). [Authorize(Policy = Permissions.ErrorRetentionPurge)] [Route("retention/purge")] [HttpPost]