using ClassNotify.Server.Data; using ClassNotify.Server.Hubs; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; /// /// 设备技术诊断包后台分发调度器 (P2.5 RC1-3 Support Bundle Phase 1) /// 严格基于数据库 PendingDispatch 状态作为可靠持久化队列,支持服务器重启后完全自动恢复 /// 离线真实等待重试,直至 Deadline 触发 TimedOut,绝不虚构状态 /// public sealed class SupportBundleDispatchWorker : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly ISupportBundleDispatchNotifier _notifier; private readonly ILogger _logger; public SupportBundleDispatchWorker( IServiceScopeFactory scopeFactory, ISupportBundleDispatchNotifier notifier, ILogger logger) { _scopeFactory = scopeFactory; _notifier = notifier; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("SupportBundleDispatchWorker started."); while (!stoppingToken.IsCancellationRequested) { try { var processed = await ProcessPendingBundlesAsync(stoppingToken); if (!processed) { // 等待通知唤醒或定时兜底检测 (1s) await Task.WhenAny(_notifier.WaitAsync(stoppingToken), Task.Delay(1000, stoppingToken)); } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Unexpected error in SupportBundleDispatchWorker loop"); await Task.Delay(1000, stoppingToken); } } _logger.LogInformation("SupportBundleDispatchWorker stopped."); } private async Task ProcessPendingBundlesAsync(CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var presenceService = scope.ServiceProvider.GetRequiredService(); var hubContext = scope.ServiceProvider.GetRequiredService>(); var now = DateTimeOffset.UtcNow; // 1. 扫描超时任务 (PendingDispatch 或 Collecting 且超过 DeadlineAtUtc) var timedOutBundles = await db.DeviceSupportBundles .Where(sb => (sb.Status == SupportBundleStatuses.PendingDispatch || sb.Status == SupportBundleStatuses.Collecting) && sb.DeadlineAtUtc <= now) .Take(50) .ToListAsync(ct); if (timedOutBundles.Count > 0) { foreach (var b in timedOutBundles) { b.Status = SupportBundleStatuses.TimedOut; b.ErrorCode ??= "DeadlineExceeded"; b.UpdatedAtUtc = now; _logger.LogInformation("SupportBundle {Id} for device {DeviceId} timed out at {Now:u} (deadline was {Deadline:u})", b.Id, b.DeviceId, now, b.DeadlineAtUtc); } await db.SaveChangesAsync(ct); } // 2. 扫描待分发任务 (Status == PendingDispatch && NextDispatchAttemptAtUtc <= now && DeadlineAtUtc > now) var pendingBundles = await db.DeviceSupportBundles .Where(sb => sb.Status == SupportBundleStatuses.PendingDispatch && (sb.NextDispatchAttemptAtUtc == null || sb.NextDispatchAttemptAtUtc <= now) && sb.DeadlineAtUtc > now) .OrderBy(sb => sb.CreatedAtUtc) .Take(50) .ToListAsync(ct); if (pendingBundles.Count == 0) { return timedOutBundles.Count > 0; } foreach (var bundle in pendingBundles) { var device = await db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == bundle.DeviceId, ct); bool isOnline = device != null && presenceService.IsOnline(device.Id, device.LastHeartbeatAt); if (isOnline) { // 设备在线:通过 tenant-qualified SignalR 渠道下发 GenerateSupportBundleCommand var command = new GenerateSupportBundleCommand { FormatVersion = 1, SupportBundleId = bundle.Id, CorrelationId = bundle.CorrelationId, RequestedAtUtc = bundle.CreatedAtUtc, DeadlineAtUtc = bundle.DeadlineAtUtc, MaxSizeBytes = 5 * 1024 * 1024 }; var tenantChannel = $"t:{bundle.TenantId}:d:{bundle.DeviceId}"; await hubContext.Clients.Group(tenantChannel).GenerateSupportBundle(command); bundle.Status = SupportBundleStatuses.Collecting; bundle.DispatchedAtUtc = now; bundle.DispatchAttemptCount += 1; bundle.LastDispatchAttemptAtUtc = now; bundle.UpdatedAtUtc = now; _logger.LogInformation("Successfully dispatched GenerateSupportBundleCommand to {Channel} for bundle {BundleId}. State -> Collecting.", tenantChannel, bundle.Id); } else { // 设备离线:保持 PendingDispatch,按规整阶梯安排下一次重试 (2s, 5s, 10s, 15s) bundle.DispatchAttemptCount += 1; bundle.LastDispatchAttemptAtUtc = now; int backoffSeconds = bundle.DispatchAttemptCount switch { 1 => 2, 2 => 5, 3 => 10, _ => 15 }; bundle.NextDispatchAttemptAtUtc = now.AddSeconds(backoffSeconds); bundle.UpdatedAtUtc = now; _logger.LogInformation("Device {DeviceId} for bundle {BundleId} is offline. Retry scheduled in {Seconds}s (Attempt={Attempt})", bundle.DeviceId, bundle.Id, backoffSeconds, bundle.DispatchAttemptCount); } } await db.SaveChangesAsync(ct); return true; } }