| | | 1 | | using System.Data.Common; |
| | | 2 | | using Elsa.AI.Persistence.EFCore.Helpers; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection; |
| | | 5 | | using Microsoft.Extensions.Hosting; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | |
| | | 8 | | namespace Elsa.AI.Persistence.EFCore.Services; |
| | | 9 | | |
| | 0 | 10 | | public class EFCoreAIConversationCleanupService( |
| | 0 | 11 | | IServiceScopeFactory scopeFactory, |
| | 0 | 12 | | ILogger<EFCoreAIConversationCleanupService> logger) : BackgroundService |
| | | 13 | | { |
| | 0 | 14 | | private static readonly TimeSpan CleanupInterval = TimeSpan.FromHours(1); |
| | | 15 | | |
| | | 16 | | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| | | 17 | | { |
| | 0 | 18 | | while (!stoppingToken.IsCancellationRequested) |
| | | 19 | | { |
| | | 20 | | try |
| | | 21 | | { |
| | 0 | 22 | | await using var scope = scopeFactory.CreateAsyncScope(); |
| | 0 | 23 | | var dbContext = scope.ServiceProvider.GetRequiredService<AIDbContext>(); |
| | 0 | 24 | | await EFCoreAIConversationCleanup.DeleteExpiredAsync(dbContext, DateTimeOffset.UtcNow, stoppingToken); |
| | 0 | 25 | | } |
| | 0 | 26 | | catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) |
| | | 27 | | { |
| | 0 | 28 | | return; |
| | | 29 | | } |
| | 0 | 30 | | catch (InvalidOperationException e) |
| | | 31 | | { |
| | 0 | 32 | | LogCleanupFailure(e); |
| | 0 | 33 | | } |
| | 0 | 34 | | catch (DbUpdateException e) |
| | | 35 | | { |
| | 0 | 36 | | LogCleanupFailure(e); |
| | 0 | 37 | | } |
| | 0 | 38 | | catch (DbException e) |
| | | 39 | | { |
| | 0 | 40 | | LogCleanupFailure(e); |
| | 0 | 41 | | } |
| | 0 | 42 | | catch (Exception e) when (ExceptionFilters.IsNonFatal(e)) |
| | | 43 | | { |
| | 0 | 44 | | LogCleanupFailure(e); |
| | 0 | 45 | | } |
| | | 46 | | |
| | | 47 | | try |
| | | 48 | | { |
| | 0 | 49 | | await Task.Delay(CleanupInterval, stoppingToken); |
| | 0 | 50 | | } |
| | 0 | 51 | | catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) |
| | | 52 | | { |
| | 0 | 53 | | return; |
| | | 54 | | } |
| | | 55 | | } |
| | 0 | 56 | | } |
| | | 57 | | |
| | | 58 | | private void LogCleanupFailure(Exception e) |
| | | 59 | | { |
| | 0 | 60 | | logger.LogWarning(e, "Failed to clean up expired AI conversations."); |
| | 0 | 61 | | } |
| | | 62 | | } |