Initial commit carried over from private repo. This is V2.
This commit is contained in:
47
code/MessengerApi/Handlers/HousekeepingHandler.cs
Normal file
47
code/MessengerApi/Handlers/HousekeepingHandler.cs
Normal file
@ -0,0 +1,47 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user