using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace ClassNotify.Server.Services; /// /// 诊断包生命周期清理统计报告 /// public class SupportBundleCleanupReport { public int ExpiredCleanedCount { get; set; } public int CleanupFailedCount { get; set; } public int OrphanDeletedCount { get; set; } public int OrphanSkippedCount { get; set; } } /// /// 诊断包 24 小时生命周期清理后台工作者 (P2.5 RC1-3 Phase 3) /// 严格执行: /// 1. 物理文件删除 -> 验证文件缺失 -> 数据库原子流转 Expired,清空 StoragePath /// 2. 物理删除失败保留 Available,下载 410 阻断,下一周期重试 /// 3. 保守清理无引用系统命名 Orphan ZIP (>24h) /// public class SupportBundleCleanupWorker : BackgroundService { private readonly IServiceProvider _serviceProvider; private readonly IOptions _options; private readonly ILogger _logger; public SupportBundleCleanupWorker( IServiceProvider serviceProvider, IOptions options, ILogger logger) { _serviceProvider = serviceProvider; _options = options; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("SupportBundleCleanupWorker started (5-minute periodic scan)."); while (!stoppingToken.IsCancellationRequested) { try { await CleanupAsync(stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Unexpected error in SupportBundleCleanupWorker cycle."); } // 5 minutes interval await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); } _logger.LogInformation("SupportBundleCleanupWorker stopped."); } /// /// 执行单次生命周期清理周期 (供 BackgroundService 及单元测试直接调用) /// public async Task CleanupAsync(CancellationToken ct = default) { var report = new SupportBundleCleanupReport(); using var scope = _serviceProvider.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var root = _options.Value.GetEffectiveStorageRoot(); var rootFull = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var rootWithSep = rootFull + Path.DirectorySeparatorChar; var now = DateTimeOffset.UtcNow; // 1. 扫描 Status == Available && ExpiresAtUtc <= now && StoragePath != null var expiredBundles = await db.DeviceSupportBundles .Where(b => b.Status == SupportBundleStatuses.Available && b.ExpiresAtUtc != null && b.ExpiresAtUtc <= now && b.StoragePath != null) .OrderBy(b => b.ExpiresAtUtc) .Take(100) .ToListAsync(ct); foreach (var bundle in expiredBundles) { try { string candidatePath; try { candidatePath = SupportBundlePathResolver.ResolveBundlePath(rootFull, bundle.StoragePath); } catch (InvalidStoragePathException ex) { _logger.LogWarning("Cleanup worker detected invalid StoragePath for bundle {BundleId}: {Message} (StoragePath='{Path}'). Skipping physical delete.", bundle.Id, ex.Message, bundle.StoragePath); continue; } // 严格删除顺序: // Resolve safe path -> Delete physical file -> 确认文件不存在 -> DB Available -> Expired -> StoragePath = null bool fileExisted = File.Exists(candidatePath); if (fileExisted) { try { File.Delete(candidatePath); } catch (Exception ex) { _logger.LogError(ex, "Failed to delete physical support bundle file {FilePath} for {BundleId}. Retrying next cycle.", candidatePath, bundle.Id); report.CleanupFailedCount++; // 重要:物理文件删除失败,DB 不得转 Expired,保留 Available 和 StoragePath! continue; } if (File.Exists(candidatePath)) { _logger.LogWarning("File.Delete did not delete file {FilePath} for {BundleId}. Retrying next cycle.", candidatePath, bundle.Id); report.CleanupFailedCount++; continue; } } else { _logger.LogWarning("SupportBundleFileAlreadyMissing: bundle {BundleId} was marked Available but file {FilePath} was already missing.", bundle.Id, candidatePath); } // 物理文件确认已不存在,原子条件更新数据库:Available -> Expired if (db.Database.IsRelational()) { await db.DeviceSupportBundles .Where(b => b.Id == bundle.Id && b.Status == SupportBundleStatuses.Available) .ExecuteUpdateAsync(setters => setters .SetProperty(x => x.Status, SupportBundleStatuses.Expired) .SetProperty(x => x.StoragePath, (string?)null) .SetProperty(x => x.UpdatedAtUtc, DateTimeOffset.UtcNow), ct); } else { var b = await db.DeviceSupportBundles.FirstOrDefaultAsync(x => x.Id == bundle.Id && x.Status == SupportBundleStatuses.Available, ct); if (b != null) { b.Status = SupportBundleStatuses.Expired; b.StoragePath = null; b.UpdatedAtUtc = DateTimeOffset.UtcNow; await db.SaveChangesAsync(ct); } } report.ExpiredCleanedCount++; _logger.LogInformation("Successfully expired support bundle {BundleId} and cleaned up physical storage.", bundle.Id); } catch (Exception ex) { _logger.LogError(ex, "Error expiring support bundle {BundleId}", bundle.Id); report.CleanupFailedCount++; } } // 2. Conservative Orphan File Cleanup if (Directory.Exists(rootFull)) { try { await CleanupOrphansAsync(rootFull, db, report, ct); } catch (Exception ex) { _logger.LogError(ex, "Error scanning for orphan support bundle files in {Root}", rootFull); } } return report; } private async Task CleanupOrphansAsync(string rootFull, ClassNotifyDbContext db, SupportBundleCleanupReport report, CancellationToken ct) { var cutoff = DateTime.UtcNow.AddHours(-24); var files = Directory.GetFiles(rootFull, "*.*", SearchOption.AllDirectories); foreach (var filePath in files) { var relative = Path.GetRelativePath(rootFull, filePath).Replace('\\', '/'); // 规则:tmp/ 目录绝对不碰 if (relative.StartsWith("tmp/", StringComparison.OrdinalIgnoreCase) || relative.StartsWith("tmp\\", StringComparison.OrdinalIgnoreCase)) { report.OrphanSkippedCount++; continue; } var fileName = Path.GetFileName(filePath); // 规则:必须是系统命名格式 *.zip (以 sb_ 开头,以 .zip 结尾) if (!fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) || !fileName.StartsWith("sb_", StringComparison.OrdinalIgnoreCase)) { // 未知文件不自动删除,仅告警 report.OrphanSkippedCount++; continue; } // 规则:文件创建/写入时间必须 > 24h var lastWrite = File.GetLastWriteTimeUtc(filePath); var creation = File.GetCreationTimeUtc(filePath); var fileAgeUtc = lastWrite < creation ? lastWrite : creation; if (fileAgeUtc >= cutoff) { // 年龄不足 24h,跳过 report.OrphanSkippedCount++; continue; } // 规则:当前数据库没有任何 StoragePath 引用 bool hasDbRef = await db.DeviceSupportBundles.AnyAsync(b => b.StoragePath != null && (b.StoragePath == relative || b.StoragePath == filePath || b.StoragePath.EndsWith("/" + fileName) || b.StoragePath.EndsWith("\\" + fileName)), ct); if (hasDbRef) { report.OrphanSkippedCount++; continue; } // 孤儿确认,执行安全删除 try { File.Delete(filePath); report.OrphanDeletedCount++; _logger.LogInformation("Deleted orphan support bundle zip: {FilePath} (Age={AgeHours:F1}h, 0 DB refs)", filePath, (DateTime.UtcNow - fileAgeUtc).TotalHours); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to delete orphan file: {FilePath}", filePath); } } } }