using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Server.Hubs; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace ClassNotify.Server.Services; /// /// 后台受控远程命令超时与生命周期流转服务 /// 严格兑现封板要求: /// 1. Pending 超时 -> 自动标记 Expired 并推 TeacherHub /// 2. Dispatched 超过 TTL 或持续无心跳响应 -> 自动标记 TimedOut 并推 TeacherHub /// 3. 定期持久化状态至 PostgreSQL 实体 /// public class DeviceCommandTimeoutWorker : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly IHubContext _teacherHub; private readonly ILogger _logger; private readonly TimeSpan _checkInterval; public DeviceCommandTimeoutWorker( IServiceScopeFactory scopeFactory, IHubContext teacherHub, ILogger logger, TimeSpan? checkInterval = null) { _scopeFactory = scopeFactory; _teacherHub = teacherHub; _logger = logger; _checkInterval = checkInterval ?? TimeSpan.FromSeconds(10); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("DeviceCommandTimeoutWorker started (CheckInterval: {Interval}s)", _checkInterval.TotalSeconds); while (!stoppingToken.IsCancellationRequested) { try { await ProcessTimeoutsAsync(stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger.LogError(ex, "Error processing device command timeouts and expirations"); } try { await Task.Delay(_checkInterval, stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } } _logger.LogInformation("DeviceCommandTimeoutWorker stopped."); } public async Task ProcessTimeoutsAsync(CancellationToken cancellationToken = default) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var now = DateTimeOffset.UtcNow; // Fetch all active non-terminal commands var activeCommands = await db.DeviceCommands .Where(c => c.Status == DeviceCommandStatuses.Pending || c.Status == DeviceCommandStatuses.Dispatched) .ToListAsync(cancellationToken); if (activeCommands.Count == 0) return 0; var transitioned = new List(); foreach (var cmd in activeCommands) { if (Domain.Entities.DeviceCommandNormalizer.NormalizeExpiredOrTimedOut(cmd, now)) { transitioned.Add(cmd); _logger.LogWarning("Command {CommandId} (Device {DeviceId}, Tenant {TenantId}) transitioned to terminal status '{Status}': {Reason}", cmd.Id, cmd.DeviceId, cmd.TenantId, cmd.Status, cmd.ResultMessage); } } if (transitioned.Count == 0) return 0; // 1. SAVE TO DATABASE FIRST - Fail-safe against broadcasting ghost states await db.SaveChangesAsync(cancellationToken); // 2. BROADCAST TO TEACHERHUB ONLY AFTER DB PERSISTENCE SUCCEEDS foreach (var cmd in transitioned) { var resultDto = new DeviceCommandResultDto { CommandId = cmd.Id, DeviceId = cmd.DeviceId, Status = cmd.Status, ResultCode = cmd.ResultCode ?? (cmd.Status == DeviceCommandStatuses.Expired ? -2 : -4), ResultMessage = cmd.ResultMessage, ExecutionDurationMs = cmd.DurationMs ?? 0, Timestamp = now }; try { await _teacherHub.Clients.Group($"t:{cmd.TenantId}:teachers").OnDeviceCommandStatusChanged(resultDto); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to broadcast command status change for {CommandId} to TeacherHub", cmd.Id); } } return transitioned.Count; } }