BotSharp/src/Infrastructure/BotSharp.OpenAPI/BackgroundServices/ConversationTimeoutService.cs

78 lines
2.7 KiB
C#
Raw Normal View History

2023-11-10 16:01:03 +00:00
using Microsoft.Extensions.Hosting;
2023-11-11 03:50:11 +00:00
namespace BotSharp.OpenAPI.BackgroundServices
2023-11-10 16:01:03 +00:00
{
public class ConversationTimeoutService : BackgroundService
{
private readonly IServiceProvider _services;
private readonly ILogger<ConversationTimeoutService> _logger;
public ConversationTimeoutService(IServiceProvider services, ILogger<ConversationTimeoutService> logger)
{
_services = services;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
2024-03-25 22:29:08 +00:00
_logger.LogInformation("Conversation Timeout Service is running...");
_ = Task.Run(async () =>
{
await DoWork(stoppingToken);
});
}
private async Task DoWork(CancellationToken stoppingToken)
{
_logger.LogInformation("Conversation Timeout Service is doing work...");
2023-11-10 16:01:03 +00:00
try
{
while (true)
{
stoppingToken.ThrowIfCancellationRequested();
2024-03-07 19:38:38 +00:00
var delay = Task.Delay(TimeSpan.FromHours(1));
2023-11-10 16:01:03 +00:00
try
{
2024-03-07 19:38:38 +00:00
await CleanIdleConversationsAsync();
2023-11-10 16:01:03 +00:00
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error occurred closing conversations.");
}
await delay;
}
}
catch (OperationCanceledException) { }
}
public override async Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Conversation Timeout Service is stopping.");
await base.StopAsync(stoppingToken);
}
2024-03-07 17:25:23 +00:00
private async Task CleanIdleConversationsAsync()
{
using var scope = _services.CreateScope();
2024-03-07 17:25:23 +00:00
var settings = scope.ServiceProvider.GetRequiredService<ConversationSetting>();
var cleanSetting = settings.CleanSetting;
if (cleanSetting == null || !cleanSetting.Enable) return;
var conversationService = scope.ServiceProvider.GetRequiredService<IConversationService>();
2024-09-11 21:08:46 +00:00
var batchSize = cleanSetting.BatchSize;
var limit = cleanSetting.MessageLimit;
var bufferHours = cleanSetting.BufferHours;
var excludeAgentIds = cleanSetting.ExcludeAgentIds ?? new List<string>();
var conversationIds = await conversationService.GetIdleConversations(batchSize, limit, bufferHours, excludeAgentIds);
if (!conversationIds.IsNullOrEmpty())
{
await conversationService.DeleteConversations(conversationIds);
}
}
2023-11-10 16:01:03 +00:00
}
}