Files
social-media/backend/Modules/Creators/Services/SlugPurger.cs

44 lines
1.3 KiB
C#

using Hutopy.Modules.Creators.Data;
namespace Hutopy.Modules.Creators.Services;
public class SlugPurger(CreatorsDbContext context)
{
private static readonly SemaphoreSlim Semaphore = new(1, 1);
private static DateTimeOffset s_lastPurgeTime = DateTimeOffset.MinValue;
private static readonly TimeSpan MinTimeBetweenPurges = TimeSpan.FromSeconds(10);
public async Task PurgeExpiredSlugsAsync(CancellationToken ct)
{
// Try to acquire the semaphore
if (!await Semaphore.WaitAsync(0, ct))
{
// Another purge operation is in progress, skip this one
return;
}
try
{
DateTimeOffset now = DateTimeOffset.UtcNow;
if (now - s_lastPurgeTime < MinTimeBetweenPurges)
{
// Not enough time has passed since the last purge
return;
}
// Delete expired slugs that are not in use
await context
.Slugs
.Where(s => s.ReservedUntil < now && s.UsedBy == null)
.ExecuteDeleteAsync(ct);
// Update the last purge time regardless of whether we found expired slugs or not
s_lastPurgeTime = now;
}
finally
{
Semaphore.Release();
}
}
}