|
| 1 | +using BotSharp.Abstraction.Conversations.Settings; |
| 2 | +using BotSharp.Abstraction.Repositories; |
| 3 | +using Microsoft.Extensions.DependencyInjection; |
| 4 | +using Microsoft.Extensions.Hosting; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using System; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | + |
| 10 | +namespace BotSharp.OpenAPI.BackgroundServices |
| 11 | +{ |
| 12 | + public class ConversationLogCleanupService : BackgroundService |
| 13 | + { |
| 14 | + private readonly IServiceProvider _services; |
| 15 | + private readonly ILogger<ConversationLogCleanupService> _logger; |
| 16 | + |
| 17 | + public ConversationLogCleanupService(IServiceProvider services, ILogger<ConversationLogCleanupService> logger) |
| 18 | + { |
| 19 | + _services = services; |
| 20 | + _logger = logger; |
| 21 | + } |
| 22 | + |
| 23 | + protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| 24 | + { |
| 25 | + _logger.LogInformation("Conversation Log Cleanup Service is running..."); |
| 26 | + |
| 27 | + _ = Task.Run(async () => |
| 28 | + { |
| 29 | + await DoWork(stoppingToken); |
| 30 | + }); |
| 31 | + } |
| 32 | + |
| 33 | + private async Task DoWork(CancellationToken stoppingToken) |
| 34 | + { |
| 35 | + _logger.LogInformation("Conversation Log Cleanup Service is doing work..."); |
| 36 | + |
| 37 | + try |
| 38 | + { |
| 39 | + while (true) |
| 40 | + { |
| 41 | + stoppingToken.ThrowIfCancellationRequested(); |
| 42 | + // Run once a day |
| 43 | + var delay = Task.Delay(TimeSpan.FromHours(24), stoppingToken); |
| 44 | + try |
| 45 | + { |
| 46 | + await CleanOldLogsAsync(); |
| 47 | + } |
| 48 | + catch (Exception ex) |
| 49 | + { |
| 50 | + _logger.LogError(ex, $"Error occurred cleaning old conversation logs."); |
| 51 | + } |
| 52 | + await delay; |
| 53 | + } |
| 54 | + } |
| 55 | + catch (OperationCanceledException) { } |
| 56 | + } |
| 57 | + |
| 58 | + public override async Task StopAsync(CancellationToken stoppingToken) |
| 59 | + { |
| 60 | + _logger.LogInformation("Conversation Log Cleanup Service is stopping."); |
| 61 | + await base.StopAsync(stoppingToken); |
| 62 | + } |
| 63 | + |
| 64 | + private async Task CleanOldLogsAsync() |
| 65 | + { |
| 66 | + using var scope = _services.CreateScope(); |
| 67 | + var settings = scope.ServiceProvider.GetRequiredService<ConversationSetting>(); |
| 68 | + var cleanSetting = settings.CleanSetting; |
| 69 | + |
| 70 | + if (cleanSetting == null || !cleanSetting.Enable || cleanSetting.LogRetentionDays <= 0) return; |
| 71 | + |
| 72 | + var locker = scope.ServiceProvider.GetRequiredService<BotSharp.Abstraction.Infrastructures.IDistributedLocker>(); |
| 73 | + var lockResource = nameof(ConversationLogCleanupService); |
| 74 | + await locker.LockAsync(lockResource, async () => |
| 75 | + { |
| 76 | + await ExecuteCleanup(scope.ServiceProvider, cleanSetting.LogRetentionDays, cleanSetting.LogBatchSize); |
| 77 | + }, timeout: 3600); // 1 hour lock timeout to prevent other pods from running it |
| 78 | + } |
| 79 | + |
| 80 | + private async Task ExecuteCleanup(IServiceProvider serviceProvider, int retentionDays, int batchSize) |
| 81 | + { |
| 82 | + var db = serviceProvider.GetRequiredService<IBotSharpRepository>(); |
| 83 | + int totalDeleted = 0; |
| 84 | + |
| 85 | + while (true) |
| 86 | + { |
| 87 | + var deletedCount = await db.DeleteOldConversationLogs(retentionDays, batchSize); |
| 88 | + if (deletedCount == 0) break; |
| 89 | + |
| 90 | + totalDeleted += deletedCount; |
| 91 | + _logger.LogInformation($"Cleaned {deletedCount} conversation logs older than {retentionDays} days in this batch."); |
| 92 | + |
| 93 | + // Sleep slightly to yield database resources |
| 94 | + await Task.Delay(1000); |
| 95 | + } |
| 96 | + |
| 97 | + if (totalDeleted > 0) |
| 98 | + { |
| 99 | + _logger.LogInformation($"Successfully cleaned a total of {totalDeleted} conversation logs older than {retentionDays} days."); |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | +} |
0 commit comments