Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ namespace ServiceControl.Audit.Persistence.EFCore.SqlServer;

using Microsoft.EntityFrameworkCore;
using ServiceControl.Audit.Persistence.EFCore.DbContexts;
using ServiceControl.Audit.Persistence.EFCore.Entities;
using ServiceControl.Audit.Persistence.EFCore.Infrastructure;
using ServiceControl.Audit.Persistence.EFCore.Infrastructure.Metrics;

Expand All @@ -13,35 +14,65 @@ public Task EnsurePartitions(AuditDbContext dbContext, DateTime fromHour, DateTi

public async Task<IReadOnlyList<DateTime>> ListExpired(AuditDbContext dbContext, AuditRetentionEntity entity, DateTime keepFrom, CancellationToken cancellationToken = default)
{
var hours = entity switch
// One seek on the clustered key for each expired hour.
var expired = new List<DateTime>();
DateTime? last = null;

while (true)
{
AuditRetentionEntity.AuditMessages => dbContext.AuditMessages.Where(message => message.CreatedOn < keepFrom).Select(message => message.CreatedOn),
AuditRetentionEntity.SagaSnapshots => dbContext.SagaSnapshots.Where(snapshot => snapshot.CreatedOn < keepFrom).Select(snapshot => snapshot.CreatedOn),
_ => throw new ArgumentOutOfRangeException(nameof(entity))
};
var after = last;
var hours = entity switch
{
AuditRetentionEntity.AuditMessages => dbContext.AuditMessages.Where(message => message.CreatedOn < keepFrom && (after == null || message.CreatedOn > after)).OrderBy(message => message.CreatedOn).Select(message => (DateTime?)message.CreatedOn),
AuditRetentionEntity.SagaSnapshots => dbContext.SagaSnapshots.Where(snapshot => snapshot.CreatedOn < keepFrom && (after == null || snapshot.CreatedOn > after)).OrderBy(snapshot => snapshot.CreatedOn).Select(snapshot => (DateTime?)snapshot.CreatedOn),
_ => throw new ArgumentOutOfRangeException(nameof(entity))
};

return await hours.Distinct().OrderBy(hour => hour).ToListAsync(cancellationToken);
var next = await hours.FirstOrDefaultAsync(cancellationToken);
if (next is null)
{
return expired;
}

expired.Add(next.Value);
last = next;
}
}

public Task DeleteBodies(IAuditBodyStoragePersistence bodyStorage, DateTime hour, CancellationToken cancellationToken = default) =>
bodyStorage.DeleteBodiesForHour(hour, cancellationToken);

public async Task<DropResult> DropExpired(AuditDbContext dbContext, AuditRetentionEntity entity, DateTime hour, int batchSize, CancellationToken cancellationToken = default)
{
var deleted = entity switch
var entityType = entity switch
{
AuditRetentionEntity.AuditMessages => await dbContext.AuditMessages
.Where(message => message.CreatedOn == hour)
.OrderBy(message => message.Id)
.Take(batchSize)
.ExecuteDeleteAsync(cancellationToken),
AuditRetentionEntity.SagaSnapshots => await dbContext.SagaSnapshots
.Where(snapshot => snapshot.CreatedOn == hour)
.OrderBy(snapshot => snapshot.Id)
.Take(batchSize)
.ExecuteDeleteAsync(cancellationToken),
AuditRetentionEntity.AuditMessages => dbContext.Model.FindEntityType(typeof(AuditMessageEntity))!,
AuditRetentionEntity.SagaSnapshots => dbContext.Model.FindEntityType(typeof(SagaSnapshotEntity))!,
_ => throw new ArgumentOutOfRangeException(nameof(entity))
};
var table = $"[{entityType.GetSchema()}].[{entityType.GetTableName()}]";

// Raw SQL because ExecuteDeleteAsync cannot add the hints.
#pragma warning disable EF1002 // The table name comes from the EF Core model.
var deleted = await dbContext.Database.ExecuteSqlRawAsync(
$"""
DELETE FROM [a]
FROM {table} AS [a]
WHERE EXISTS (
SELECT 1
FROM (
SELECT TOP (@p0) [a0].[CreatedOn], [a0].[Id]
FROM {table} AS [a0] WITH (FORCESEEK)
WHERE [a0].[CreatedOn] = @p1
ORDER BY [a0].[Id]
) AS [a1]
WHERE [a1].[CreatedOn] = [a].[CreatedOn] AND [a1].[Id] = [a].[Id]
)
OPTION (KEEPFIXED PLAN)
""",
[batchSize, hour],
cancellationToken);
#pragma warning restore EF1002

return new DropResult(deleted, Completed: deleted < batchSize);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ sealed class AuditRetention(
static readonly TimeSpan Interval = TimeSpan.FromHours(1);
static readonly TimeSpan InitialDelay = TimeSpan.FromMinutes(1);
static readonly TimeSpan BatchPause = TimeSpan.FromSeconds(1);
static readonly TimeSpan RetryBaseDelay = TimeSpan.FromSeconds(10);

// Before ingestion starts, which cannot insert into an hour that has no partition.
public override async Task StartAsync(CancellationToken cancellationToken = default)
Expand All @@ -48,27 +49,49 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken =

do
{
try
var attempt = 0;
while (!await TrySweep(cancellationToken))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also be reporting to the custom check when the sweep takes longer than the timer interval, because that will be causing an ever-growing database.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also be reporting to the custom check when the sweep takes longer than the timer interval, because that will be causing an ever-growing database.

@rbev I thought there was already a custom check for that? If there was no cleanup happening for a specific duration or something. I'll check.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rbev I understand your comment, the custom check was based on failure count... I refactored that to be based on time in the following PR. Also, the timestamp is based on data from the database so it also works then the instance is restarted/crashes. Previous implementation count was non-durable:

{
await Sweep(pace: true, cancellationToken);
}
#pragma warning disable PS0019 // Filtered on the token alone because SqlClient reports a cancelled command as a SqlException.
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
logger.LogError(ex, "Error during audit retention sweep");
var delay = RetryDelay(++attempt, Random.Shared.NextDouble());
logger.LogWarning("The audit retention sweep failed. Attempt {Attempt} starts in {Delay}", attempt + 1, delay);
await Task.Delay(delay, timeProvider, cancellationToken);
}
} while (await timer.WaitForNextTickAsync(cancellationToken));
}
#pragma warning disable PS0019 // Filtered on the token alone because SqlClient reports a cancelled command as a SqlException.
catch (Exception) when (cancellationToken.IsCancellationRequested)
{
logger.LogInformation("Stopping audit retention sweep");
}
#pragma warning restore PS0019
}

async Task<bool> TrySweep(CancellationToken cancellationToken)
{
try
{
return await Sweep(pace: true, cancellationToken);
}
#pragma warning disable PS0019 // Filtered on the token alone because SqlClient reports a cancelled command as a SqlException.
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
logger.LogError(ex, "Error during audit retention sweep");
return false;
}
#pragma warning restore PS0019
}

// Exponential back-off with jitter, capped at the sweep interval. jitter is in [0, 1).
internal static TimeSpan RetryDelay(int attempt, double jitter)
{
var exponential = TimeSpan.FromTicks(Math.Min(Interval.Ticks, RetryBaseDelay.Ticks << Math.Min(attempt - 1, 16)));
return (exponential / 2) + (exponential / 2 * jitter);
}

internal Task SweepNow(CancellationToken cancellationToken = default) => Sweep(pace: false, cancellationToken);

async Task Sweep(bool pace, CancellationToken cancellationToken)
// Returns false when a pass failed.
async Task<bool> Sweep(bool pace, CancellationToken cancellationToken)
{
var passesStarted = false;
try
Expand All @@ -79,7 +102,7 @@ async Task Sweep(bool pace, CancellationToken cancellationToken)
if (handle is null)
{
logger.LogWarning("Skipping the audit retention sweep because another instance holds the retention lock. Only one audit instance should own a database.");
return;
return true;
}

var now = timeProvider.GetUtcNow().UtcDateTime;
Expand All @@ -99,11 +122,11 @@ async Task Sweep(bool pace, CancellationToken cancellationToken)
if (passFailures.Count > 0)
{
retentionState.SweepFailed(string.Join("; ", passFailures));
return false;
}
else
{
retentionState.SweepSucceeded();
}

retentionState.SweepSucceeded();
return true;
}
#pragma warning disable PS0019 // Filtered on the token alone because SqlClient reports a cancelled command as a SqlException.
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
namespace ServiceControl.Audit.Persistence.Tests
{
using System;
using NUnit.Framework;
using ServiceControl.Audit.Persistence.EFCore.Implementation;

[TestFixture]
class AuditRetentionRetryDelayTests
{
[TestCase(1, 5, 10)]
[TestCase(2, 10, 20)]
[TestCase(3, 20, 40)]
[TestCase(6, 160, 320)]
public void Doubles_with_each_attempt_and_stays_within_the_jitter_range(int attempt, int minSeconds, int maxSeconds)
{
using (Assert.EnterMultipleScope())
{
Assert.That(AuditRetention.RetryDelay(attempt, 0), Is.EqualTo(TimeSpan.FromSeconds(minSeconds)));
Assert.That(AuditRetention.RetryDelay(attempt, 0.5), Is.EqualTo(TimeSpan.FromSeconds((minSeconds + maxSeconds) / 2.0)));
Assert.That(AuditRetention.RetryDelay(attempt, 0.999999), Is.LessThan(TimeSpan.FromSeconds(maxSeconds)));
}
}

[TestCase(10)]
[TestCase(100)]
[TestCase(int.MaxValue)]
public void Never_exceeds_the_sweep_interval(int attempt) =>
Assert.That(AuditRetention.RetryDelay(attempt, 0.999999), Is.LessThan(TimeSpan.FromHours(1)).And.GreaterThanOrEqualTo(TimeSpan.FromMinutes(30)));
}
}
Loading