Files
messengerapi/code/MessengerApi/Handlers/HousekeepingHandler.cs
masiton 4393977389
All checks were successful
Build and Push Docker Image / build (push) Successful in 1m3s
Build and Push Docker Image / docker (push) Successful in 43s
Initial commit carried over from private repo. This is V2.
2025-07-04 21:24:12 +02:00

48 lines
1.9 KiB
C#

using MessengerApi.Configuration.Model;
using MessengerApi.Contracts.Factories;
using Microsoft.EntityFrameworkCore;
namespace MessengerApi.Handlers
{
public class HousekeepingHandler
{
private readonly ILogger logger;
private readonly MessengerConfiguration configuration;
private readonly IDbContextFactory dbContextFactory;
public HousekeepingHandler(
ILogger logger,
IDbContextFactory dbContextFactory,
MessengerConfiguration configuration)
{
this.logger = logger;
this.dbContextFactory = dbContextFactory;
this.configuration = configuration;
}
public async Task RemoveOldMessages()
{
this.logger.Trace($"Executing {nameof(this.RemoveOldMessages)}.");
var timestamp = DateTime.UtcNow;
var cutoff = timestamp.AddMinutes(-this.configuration.HousekeepingMessageAgeInMinutes);
using var ctx = this.dbContextFactory.CreateDbContext();
await ctx.Messages.Where(x => x.CreatedUtc < cutoff).ExecuteDeleteAsync();
if (this.configuration.HousekeepingMessageState != Configuration.Enums.HousekeepingMessageStates.None)
{
this.logger.Trace($"Executing additional message state cleaning in {nameof(this.RemoveOldMessages)}.");
if (this.configuration.HousekeepingMessageState == Configuration.Enums.HousekeepingMessageStates.Delivered)
{
await ctx.Messages.Where(x => x.IsDelivered).ExecuteDeleteAsync();
}
else if (this.configuration.HousekeepingMessageState == Configuration.Enums.HousekeepingMessageStates.Acknowledged)
{
await ctx.Messages.Where(x => x.IsAcknowledged).ExecuteDeleteAsync();
}
}
}
}
}