using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; namespace ClassNotify.Server.Services; /// /// 小规模灰度升级管控服务实现 (P2.5 RC1-4 Phase 3) /// 严格限定 1~5 台同一学校设备,物理隔离未放行设备 (Held),单 Canary,人工放行门禁 /// 严禁将聚合汇总计数持久化到批次表,所有统计严格基于 DeviceUpdateRun 动态计算 /// public sealed class DeviceUpdateBatchService : IDeviceUpdateBatchService { private readonly ClassNotifyDbContext _db; private readonly IDeviceUpdateDispatchNotifier _dispatchNotifier; private readonly ILogger _logger; public DeviceUpdateBatchService( ClassNotifyDbContext db, IDeviceUpdateDispatchNotifier dispatchNotifier, ILogger logger) { _db = db; _dispatchNotifier = dispatchNotifier; _logger = logger; } public async Task CreateBatchAsync( CreateUpdateBatchRequest request, string actorUser, string actorRole, string? actorTenantId, string clientIp, CancellationToken ct) { // 1. RBAC: 仅限系统超级管理员 (SuperAdmin) 允许发起灰度批次 (U21) if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Unauthorized attempt to create update batch by user {User} with role {Role}. 403 Forbidden.", actorUser, actorRole); return DeviceUpdateBatchCreationResult.Forbidden("仅系统管理员 (SuperAdmin) 允许发起小规模灰度升级。"); } // 2. 严格批次规模边界 (U22): 限制 1 至 5 台设备 if (request.DeviceIds == null || request.DeviceIds.Count < 1 || request.DeviceIds.Count > 5) { _logger.LogWarning("Invalid batch size {Count}. Expected 1 to 5 devices.", request.DeviceIds?.Count ?? 0); return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "灰度升级批次设备数量必须在 1 至 5 台之间。"); } // 3. 校验设备列表无重复 if (request.DeviceIds.Distinct(StringComparer.OrdinalIgnoreCase).Count() != request.DeviceIds.Count) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "批次设备列表中包含重复的设备标识。"); } // 4. 必须明确指定恰好 1 台 Canary 设备且必须包含在设备列表中 if (string.IsNullOrWhiteSpace(request.CanaryDeviceId) || !request.DeviceIds.Contains(request.CanaryDeviceId, StringComparer.OrdinalIgnoreCase)) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "必须在批次设备列表中明确指定一台首发金丝雀 (Canary) 验证设备。"); } if (string.IsNullOrWhiteSpace(request.TenantId)) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "必须指定批次目标租户学校 (TenantId)。"); } // 5. 校验目标 Release 是否存在且启用 var release = await _db.UpdateReleases.AsNoTracking().FirstOrDefaultAsync(r => r.Id == request.ReleaseId, ct); if (release == null) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.ReleaseNotFound, $"指定升级版本 '{request.ReleaseId}' 不存在。"); } if (!release.IsEnabled) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.ReleaseDisabled, $"指定升级版本 '{request.ReleaseId}' 已停用。"); } // 6. 校验设备真实存在且严格属于同一租户 (U22: 禁止跨租户) var devices = await _db.Devices .Include(d => d.Classroom) .Where(d => request.DeviceIds.Contains(d.Id)) .ToListAsync(ct); if (devices.Count != request.DeviceIds.Count) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "所选设备列表中存在无效或不存在的设备。"); } if (devices.Any(d => !string.Equals(d.TenantId, request.TenantId, StringComparison.OrdinalIgnoreCase))) { return DeviceUpdateBatchCreationResult.BadRequest( UpdateErrorCodes.InvalidBatchScope, "灰度升级批次内所有设备必须严格同属于指定租户学校,严禁跨租户混合升级。"); } // 7. 幂等性校验 (U23): ClientRequestId 防重 if (!string.IsNullOrWhiteSpace(request.ClientRequestId)) { var existingBatch = await _db.DeviceUpdateBatches .Include(b => b.Runs) .FirstOrDefaultAsync(b => b.RequestedByUserId == actorUser && b.ClientRequestId == request.ClientRequestId, ct); if (existingBatch != null) { _logger.LogInformation("Idempotent hit for batch {BatchId} by user {User} (ClientRequestId={RequestId})", existingBatch.Id, actorUser, request.ClientRequestId); return DeviceUpdateBatchCreationResult.Accepted(BuildBatchDto(existingBatch, existingBatch.Runs, devices)); } } // 8. 活跃任务冲突校验: 所选设备中任何一台不得有正在执行中的升级 var hasActive = await _db.DeviceUpdateRuns .AnyAsync(r => request.DeviceIds.Contains(r.DeviceId) && UpdateStatuses.ActiveStatuses.Contains(r.Status), ct); if (hasActive) { return DeviceUpdateBatchCreationResult.Conflict( UpdateErrorCodes.UpdateAlreadyRunning, "所选设备列表中部分设备当前已有正在执行中的升级任务。"); } // 9. 原子事务落库 var now = DateTimeOffset.UtcNow; var batchId = $"batch_upd_{now.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24]; var batch = new DeviceUpdateBatch { Id = batchId, TenantId = request.TenantId, ReleaseId = release.Id, CanaryDeviceId = request.CanaryDeviceId, RequestedByUserId = actorUser, ClientRequestId = request.ClientRequestId, Status = UpdateBatchStatuses.CanaryRunning, TargetDeviceCount = request.DeviceIds.Count, CreatedAtUtc = now, CompletedAtUtc = null, StoppedAtUtc = null }; var runs = new List(); foreach (var devId in request.DeviceIds) { var dev = devices.First(d => string.Equals(d.Id, devId, StringComparison.OrdinalIgnoreCase)); bool isCanary = string.Equals(dev.Id, request.CanaryDeviceId, StringComparison.OrdinalIgnoreCase); var run = new DeviceUpdateRun { Id = $"upd_{now.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24], TenantId = dev.TenantId, DeviceId = dev.Id, ReleaseId = release.Id, CorrelationId = $"batch_corr_{Guid.NewGuid():N}"[..20], RequestedByUserId = actorUser, ClientRequestId = null, FromVersion = dev.ServiceVersion ?? "unknown", TargetVersion = release.Version, Status = UpdateStatuses.PendingDispatch, CreatedAtUtc = now, DeadlineAtUtc = now.AddMinutes(5), BatchId = batchId, IsCanary = isCanary, // 关键门禁 U24: Canary 为 Released,其余 1~4 台物理置为 Held 门禁 DispatchGate = isCanary ? UpdateDispatchGates.Released : UpdateDispatchGates.Held }; runs.Add(run); } var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUser, ActorRole = actorRole, Action = "DEVICE_UPDATE_BATCH_CREATED", TargetType = "DeviceUpdateBatch", TargetId = batchId, IpAddress = clientIp, Details = JsonSerializer.Serialize(new { BatchId = batchId, TenantId = request.TenantId, ReleaseId = release.Id, TargetVersion = release.Version, CanaryDeviceId = request.CanaryDeviceId, DeviceCount = runs.Count, ClientRequestId = request.ClientRequestId }) }; _db.DeviceUpdateBatches.Add(batch); _db.DeviceUpdateRuns.AddRange(runs); _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); // 唤醒后台调度器立即下发 Canary _dispatchNotifier.Notify(); _logger.LogInformation("Update batch {BatchId} created with {Count} devices (Canary={CanaryId}). State: CanaryRunning.", batchId, runs.Count, request.CanaryDeviceId); return DeviceUpdateBatchCreationResult.Accepted(BuildBatchDto(batch, runs, devices)); } public async Task> GetBatchAsync( string batchId, string actorRole, CancellationToken ct) { if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateBatchQueryResult.Forbidden("仅系统管理员允许查询灰度批次详情。"); } var batch = await _db.DeviceUpdateBatches .Include(b => b.Runs) .Include(b => b.Release) .FirstOrDefaultAsync(b => b.Id == batchId, ct); if (batch == null) { return DeviceUpdateBatchQueryResult.NotFound($"升级批次 '{batchId}' 不存在。"); } var deviceIds = batch.Runs.Select(r => r.DeviceId).ToList(); var devices = await _db.Devices .Include(d => d.Classroom) .Where(d => deviceIds.Contains(d.Id)) .ToListAsync(ct); return DeviceUpdateBatchQueryResult.Ok(BuildBatchDto(batch, batch.Runs, devices)); } public async Task ContinueBatchAsync( string batchId, string actorUser, string actorRole, string clientIp, CancellationToken ct) { // 1. RBAC: 仅限 SuperAdmin (U21) if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateBatchActionResult.Forbidden("仅系统管理员允许人工确认放行灰度批次。"); } var batch = await _db.DeviceUpdateBatches .Include(b => b.Runs) .Include(b => b.Release) .FirstOrDefaultAsync(b => b.Id == batchId, ct); if (batch == null) { return DeviceUpdateBatchActionResult.NotFound(UpdateErrorCodes.BatchNotFound, $"升级批次 '{batchId}' 不存在。"); } // 2. 状态机校验 (U26): 仅在 AwaitingContinue 状态下允许放行 if (!string.Equals(batch.Status, UpdateBatchStatuses.AwaitingContinue, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Cannot continue batch {BatchId}: Status is {Status}, expected AwaitingContinue.", batch.Id, batch.Status); return DeviceUpdateBatchActionResult.BadRequest( UpdateErrorCodes.BatchInvalidState, $"升级批次当前状态为 '{batch.Status}',仅在 'AwaitingContinue' 状态下允许人工确认放行。"); } // 3. 金丝雀成功校验 (U26): Canary 必须已处于 Succeeded 状态 var canaryRun = batch.Runs.FirstOrDefault(r => r.IsCanary); if (canaryRun == null || !string.Equals(canaryRun.Status, UpdateStatuses.Succeeded, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Cannot continue batch {BatchId}: Canary run {RunId} status is {Status}, not Succeeded.", batch.Id, canaryRun?.Id, canaryRun?.Status); return DeviceUpdateBatchActionResult.BadRequest( UpdateErrorCodes.CanaryNotSucceeded, "金丝雀验证设备未成功完成升级,严禁放行后续批次设备。"); } // 4. 原子放行门禁 (Held -> Released) var now = DateTimeOffset.UtcNow; batch.Status = UpdateBatchStatuses.RollingOut; var heldRuns = batch.Runs.Where(r => string.Equals(r.DispatchGate, UpdateDispatchGates.Held, StringComparison.OrdinalIgnoreCase)).ToList(); foreach (var r in heldRuns) { r.DispatchGate = UpdateDispatchGates.Released; r.NextDispatchAttemptAtUtc = now; // 立即安排分发 } var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUser, ActorRole = actorRole, Action = "DEVICE_UPDATE_BATCH_CONTINUED", TargetType = "DeviceUpdateBatch", TargetId = batch.Id, IpAddress = clientIp, Details = JsonSerializer.Serialize(new { BatchId = batch.Id, TenantId = batch.TenantId, ReleasedDeviceCount = heldRuns.Count, PreviousStatus = UpdateBatchStatuses.AwaitingContinue, NewStatus = UpdateBatchStatuses.RollingOut }) }; _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); // 唤醒后台分发器 _dispatchNotifier.Notify(); _logger.LogInformation("Batch {BatchId} continued by user {User}. {Count} held runs released. Status -> RollingOut.", batch.Id, actorUser, heldRuns.Count); var deviceIds = batch.Runs.Select(r => r.DeviceId).ToList(); var devices = await _db.Devices .Include(d => d.Classroom) .Where(d => deviceIds.Contains(d.Id)) .ToListAsync(ct); return DeviceUpdateBatchActionResult.Ok(BuildBatchDto(batch, batch.Runs, devices)); } public async Task StopBatchAsync( string batchId, string actorUser, string actorRole, string clientIp, CancellationToken ct) { // 1. RBAC: 仅限 SuperAdmin (U21) if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateBatchActionResult.Forbidden("仅系统管理员允许人工停止灰度批次。"); } var batch = await _db.DeviceUpdateBatches .Include(b => b.Runs) .Include(b => b.Release) .FirstOrDefaultAsync(b => b.Id == batchId, ct); if (batch == null) { return DeviceUpdateBatchActionResult.NotFound(UpdateErrorCodes.BatchNotFound, $"升级批次 '{batchId}' 不存在。"); } var deviceIds = batch.Runs.Select(r => r.DeviceId).ToList(); var devices = await _db.Devices .Include(d => d.Classroom) .Where(d => deviceIds.Contains(d.Id)) .ToListAsync(ct); // 已终态批次幂等返回 if (string.Equals(batch.Status, UpdateBatchStatuses.Stopped, StringComparison.OrdinalIgnoreCase) || string.Equals(batch.Status, UpdateBatchStatuses.Completed, StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateBatchActionResult.Ok(BuildBatchDto(batch, batch.Runs, devices)); } var now = DateTimeOffset.UtcNow; batch.Status = UpdateBatchStatuses.Stopped; batch.StoppedAtUtc = now; // 关键安全门禁 U27: Stop 动作严禁粗暴中断正在执行中的客户端任务 // Held 状态任务保持 Held (永不分发),活跃任务任由其自然终态化 var audit = new AdminAuditEvent { Id = Guid.NewGuid().ToString("N"), OccurredAt = now, ActorUsername = actorUser, ActorRole = actorRole, Action = "DEVICE_UPDATE_BATCH_STOPPED", TargetType = "DeviceUpdateBatch", TargetId = batch.Id, IpAddress = clientIp, Details = JsonSerializer.Serialize(new { BatchId = batch.Id, TenantId = batch.TenantId, StoppedAt = now, RemainingHeldCount = batch.Runs.Count(r => string.Equals(r.DispatchGate, UpdateDispatchGates.Held, StringComparison.OrdinalIgnoreCase)) }) }; _db.AdminAuditEvents.Add(audit); await _db.SaveChangesAsync(ct); _logger.LogInformation("Batch {BatchId} stopped by user {User} at {Now:u}.", batch.Id, actorUser, now); return DeviceUpdateBatchActionResult.Ok(BuildBatchDto(batch, batch.Runs, devices)); } public async Task>> GetReleasesAsync( string actorRole, CancellationToken ct) { if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase)) { return DeviceUpdateBatchQueryResult>.Forbidden("仅系统管理员允许查询发布包版本列表。"); } var list = await _db.UpdateReleases .AsNoTracking() .Where(r => r.IsEnabled) .OrderByDescending(r => r.CreatedAtUtc) .Select(r => new UpdateReleaseSummaryDto { ReleaseId = r.Id, Version = r.Version, Architecture = r.Architecture, PackageSizeBytes = r.PackageSizeBytes, PackageSha256 = r.PackageSha256, CreatedAtUtc = r.CreatedAtUtc, IsEnabled = r.IsEnabled }) .ToListAsync(ct); return DeviceUpdateBatchQueryResult>.Ok(list); } #region Helpers & Invariants private static UpdateBatchSummaryDto CalculateSummary(List runs) { var summary = new UpdateBatchSummaryDto { Target = runs.Count, Held = runs.Count(r => r.DispatchGate == UpdateDispatchGates.Held && r.Status == UpdateStatuses.PendingDispatch), Updating = runs.Count(r => r.DispatchGate == UpdateDispatchGates.Released && UpdateStatuses.ActiveStatuses.Contains(r.Status)), Succeeded = runs.Count(r => r.Status == UpdateStatuses.Succeeded), RolledBack = runs.Count(r => r.Status == UpdateStatuses.RolledBack), Failed = runs.Count(r => r.Status == UpdateStatuses.Failed), RollbackFailed = runs.Count(r => r.Status == UpdateStatuses.RollbackFailed), TimedOut = runs.Count(r => r.Status == UpdateStatuses.TimedOut) }; // 关键门禁 U28: 恒等守恒断言校验 (Target == Held + Updating + Succeeded + RolledBack + Failed + RollbackFailed + TimedOut) int sum = summary.Held + summary.Updating + summary.Succeeded + summary.RolledBack + summary.Failed + summary.RollbackFailed + summary.TimedOut; if (summary.Target != sum) { throw new InvalidOperationException($"Dynamic batch summary invariant violated! Target={summary.Target}, Sum={sum}"); } return summary; } private static UpdateBatchDto BuildBatchDto( DeviceUpdateBatch batch, List runs, List devices) { var deviceMap = devices.ToDictionary(d => d.Id, StringComparer.OrdinalIgnoreCase); var details = runs.Select(r => { deviceMap.TryGetValue(r.DeviceId, out var dev); return new UpdateBatchDeviceDetailDto { DeviceId = r.DeviceId, Hostname = dev?.Hostname ?? "", ClassroomName = dev?.Classroom?.DisplayName ?? "", IsCanary = r.IsCanary, DispatchGate = r.DispatchGate, Status = r.Status, FromVersion = r.FromVersion, TargetVersion = r.TargetVersion, StartedAtUtc = r.DispatchedAtUtc, CompletedAtUtc = r.CompletedAtUtc, ErrorCode = r.ErrorCode, ErrorMessage = r.ErrorMessage }; }).ToList(); return new UpdateBatchDto { BatchId = batch.Id, TenantId = batch.TenantId, ReleaseId = batch.ReleaseId, TargetVersion = batch.Release?.Version ?? (runs.FirstOrDefault()?.TargetVersion ?? ""), Status = batch.Status, CanaryDeviceId = batch.CanaryDeviceId, CreatedAtUtc = batch.CreatedAtUtc, CompletedAtUtc = batch.CompletedAtUtc, StoppedAtUtc = batch.StoppedAtUtc, Summary = CalculateSummary(runs), Devices = details }; } #endregion }