using ClassNotify.Server.Data; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; namespace ClassNotify.Server.Services; /// /// 批次自检超时与完成度收敛对齐器 (P2.5 RC1-2) /// 负责扫描超期 Run 并将其置为 TimedOut(迟到报告拒绝覆盖) /// 当批次下所有 Run 均到达终态 (Completed/Unreachable/TimedOut) 时,将 Batch.Status 收敛为 Completed /// public sealed class SelfCheckBatchReconciler : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; public SelfCheckBatchReconciler( IServiceScopeFactory scopeFactory, ILogger logger) { _scopeFactory = scopeFactory; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("SelfCheckBatchReconciler started."); while (!stoppingToken.IsCancellationRequested) { try { await ReconcileAsync(stoppingToken); await Task.Delay(2000, stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Unexpected error in SelfCheckBatchReconciler loop"); await Task.Delay(2000, stoppingToken); } } _logger.LogInformation("SelfCheckBatchReconciler stopped."); } private async Task ReconcileAsync(CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; // 1. Reconcile timed-out runs var timedOutRuns = await db.DeviceSelfChecks .Where(r => (r.RunState == SelfCheckRunStates.PendingDispatch || r.RunState == SelfCheckRunStates.Dispatched) && r.DeadlineAtUtc < now) .ToListAsync(ct); if (timedOutRuns.Count > 0) { foreach (var run in timedOutRuns) { run.RunState = SelfCheckRunStates.TimedOut; run.Status = "Timeout"; run.CompletedAtUtc = now; _logger.LogWarning("SelfCheck {RunId} timed out at {Deadline:u}. BatchId={BatchId}, DeviceId={DeviceId}", run.Id, run.DeadlineAtUtc, run.BatchId, run.DeviceId); } await db.SaveChangesAsync(ct); } // 2. Reconcile running batches to Completed when all runs reach terminal states var runningBatches = await db.DeviceSelfCheckBatches .Where(b => b.Status == "Running") .ToListAsync(ct); bool batchesUpdated = false; foreach (var batch in runningBatches) { var activeCount = await db.DeviceSelfChecks .CountAsync(r => r.BatchId == batch.Id && (r.RunState == SelfCheckRunStates.PendingDispatch || r.RunState == SelfCheckRunStates.Dispatched), ct); if (activeCount == 0) { batch.Status = "Completed"; batch.CompletedAtUtc = now; batch.UpdatedAtUtc = now; batchesUpdated = true; _logger.LogInformation("SelfCheck batch {BatchId} reached terminal state (Completed). Target={Target}", batch.Id, batch.TargetDeviceCount); } } if (batchesUpdated) { await db.SaveChangesAsync(ct); } } }