[CHANGE] Fixed cache service && Download channel images from cache

This commit is contained in:
max
2025-09-18 00:30:35 +02:00
parent 8a64d6fc64
commit ab532ac6dc
2 changed files with 52 additions and 17 deletions

View File

@@ -10,7 +10,7 @@ using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Manager.App.Services.System;
public class CacheService(ILogger<CacheService> logger, IHostEnvironment environment) : ExtendedBackgroundService(nameof(CacheService), "Manages caching.", logger, TimeSpan.FromDays(1))
public class CacheService(ILogger<CacheService> logger, IHostEnvironment environment) : ExtendedBackgroundService(nameof(CacheService), "Manages caching.", logger, TimeSpan.FromHours(5))
{
private DirectoryInfo? _cacheDirectory;
private PooledDbContextFactory<CacheDbContext>? _dbContextFactory;
@@ -131,9 +131,14 @@ public class CacheService(ILogger<CacheService> logger, IHostEnvironment environ
throw new InvalidOperationException("No DbContext factory configured.");
}
if (_cacheDirectory == null)
{
throw new InvalidOperationException("No cache directory configured.");
}
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
var toRemove = dbContext.Cache.Where(c => c.CachedAtUtc >= DateTime.UtcNow.AddDays(-1));
var toRemove = dbContext.Cache.Where(c => c.CachedAtUtc < DateTime.UtcNow.AddDays(-1));
if (!toRemove.Any())
{
LogEvent("No items found to purge from cache.");
@@ -142,9 +147,37 @@ public class CacheService(ILogger<CacheService> logger, IHostEnvironment environ
var totalToRemove = toRemove.Count();
LogEvent($"Found {totalToRemove} cache items that are older than 1 day(s)");
dbContext.RemoveRange(toRemove);
var deleted = await dbContext.SaveChangesAsync(cancellationToken);
LogEvent($"Removed {deleted}/{totalToRemove} items");
var deleted = new List<CacheEntity>();
foreach (var entity in toRemove)
{
var pathToFile = Path.Combine(_cacheDirectory.FullName, DataSubDir, $"{entity.Id}.cache");
if (!File.Exists(pathToFile))
{
deleted.Add(entity);
continue;
}
try
{
File.Delete(pathToFile);
}
catch (Exception e)
{
logger.LogError(e, "Failed to delete cache entity with id: {EntityId}. Skipping cache entity...", entity.Id);
continue;
}
deleted.Add(entity);
}
dbContext.RemoveRange(deleted);
var dbDeleted = await dbContext.SaveChangesAsync(cancellationToken);
if (dbDeleted < deleted.Count)
{
LogEvent("Could not delete all files from cache.", LogSeverity.Warning);
}
LogEvent($"Removed {dbDeleted}/{totalToRemove} items");
}
}