using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
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.Logging;
using Microsoft.Extensions.Options;
using ClassNotify.Server.Infrastructure.Correlation;
namespace ClassNotify.Server.Services;
///
/// 客户端在线升级管控服务实现 (P2.5 RC1-4 Phase 1)
///
public sealed class DeviceUpdateService : IDeviceUpdateService
{
private readonly ClassNotifyDbContext _db;
private readonly IOptions _options;
private readonly IDeviceUpdateDispatchNotifier _dispatchNotifier;
private readonly ICorrelationContext _correlationContext;
private readonly ILogger _logger;
private static readonly ConcurrentDictionary _deviceLocks = new();
public DeviceUpdateService(
ClassNotifyDbContext db,
IOptions options,
IDeviceUpdateDispatchNotifier dispatchNotifier,
ICorrelationContext correlationContext,
ILogger logger)
{
_db = db;
_options = options;
_dispatchNotifier = dispatchNotifier;
_correlationContext = correlationContext;
_logger = logger;
}
public async Task CreateUpdateRunAsync(
string deviceId,
CreateDeviceUpdateRequest request,
string actorUser,
string actorRole,
string? actorTenantId,
string clientIp,
CancellationToken ct)
{
// 1. RBAC: 第一版升级属于高风险物理变更,仅限 SuperAdmin (U3)
if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase))
{
_logger.LogWarning("Unauthorized user {User} with role {Role} attempted to trigger update for device {DeviceId}. 403 Forbidden.",
actorUser, actorRole, deviceId);
return DeviceUpdateCreationResult.Forbidden("仅系统管理员 (SuperAdmin) 允许发起终端软件版本升级。");
}
if (string.IsNullOrWhiteSpace(request.ReleaseId))
{
return DeviceUpdateCreationResult.BadRequest(UpdateErrorCodes.ReleaseNotFound, "必须指定目标更新版本 ReleaseId。");
}
// 2. 校验目标 Release 是否存在且启用
var release = await _db.UpdateReleases.AsNoTracking().FirstOrDefaultAsync(r => r.Id == request.ReleaseId, ct);
if (release == null)
{
_logger.LogWarning("UpdateRelease {ReleaseId} not found.", request.ReleaseId);
return DeviceUpdateCreationResult.BadRequest(UpdateErrorCodes.ReleaseNotFound, $"指定升级版本 '{request.ReleaseId}' 不存在。");
}
if (!release.IsEnabled)
{
_logger.LogWarning("UpdateRelease {ReleaseId} is disabled.", request.ReleaseId);
return DeviceUpdateCreationResult.BadRequest(UpdateErrorCodes.ReleaseDisabled, $"指定升级版本 '{request.ReleaseId}' 已停用。");
}
// 3. 校验设备是否存在
var device = await _db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId, ct);
if (device == null)
{
_logger.LogWarning("Target device {DeviceId} for update not found.", deviceId);
return DeviceUpdateCreationResult.NotFound($"目标设备 '{deviceId}' 不存在。");
}
// 4. 并发控制与防重校验 (U5: 单设备同时仅允许一个活跃更新任务)
var gate = _deviceLocks.GetOrAdd(deviceId, _ => new SemaphoreSlim(1, 1));
await gate.WaitAsync(ct);
try
{
// 4a. 幂等性校验 (ClientRequestId)
if (!string.IsNullOrWhiteSpace(request.ClientRequestId))
{
var existing = await _db.DeviceUpdateRuns
.AsNoTracking()
.FirstOrDefaultAsync(u => u.RequestedByUserId == actorUser && u.ClientRequestId == request.ClientRequestId, ct);
if (existing != null)
{
_logger.LogInformation("Idempotent hit for update run {RunId} by user {User} (ClientRequestId={RequestId})",
existing.Id, actorUser, request.ClientRequestId);
return DeviceUpdateCreationResult.Accepted(MapToDto(existing));
}
}
// 4b. 检查设备当前是否有正在进行的更新任务
var existingActive = await _db.DeviceUpdateRuns
.AsNoTracking()
.FirstOrDefaultAsync(u => u.DeviceId == deviceId && UpdateStatuses.ActiveStatuses.Contains(u.Status), ct);
if (existingActive != null)
{
_logger.LogWarning("Device {DeviceId} already has active update run {RunId} in status {Status}. 409 Conflict.",
deviceId, existingActive.Id, existingActive.Status);
return DeviceUpdateCreationResult.Conflict(
UpdateErrorCodes.UpdateAlreadyRunning,
existingActive.Id,
$"设备 '{deviceId}' 当前已有正在执行中的版本升级任务 ({existingActive.Id},状态: {existingActive.Status})。");
}
// 5. 写入数据库原子事务
var now = DateTimeOffset.UtcNow;
var runId = $"upd_{now.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..24];
var correlationId = !string.IsNullOrWhiteSpace(_correlationContext.CorrelationId)
? _correlationContext.CorrelationId
: $"upd_corr_{Guid.NewGuid():N}"[..20];
var updateRun = new DeviceUpdateRun
{
Id = runId,
TenantId = device.TenantId,
DeviceId = device.Id,
ReleaseId = release.Id,
CorrelationId = correlationId,
RequestedByUserId = actorUser,
ClientRequestId = request.ClientRequestId,
FromVersion = device.ServiceVersion ?? "unknown",
TargetVersion = release.Version,
Status = UpdateStatuses.PendingDispatch,
CreatedAtUtc = now,
DeadlineAtUtc = now.AddMinutes(5), // 5 分钟超时窗口
DispatchedAtUtc = null,
CompletedAtUtc = null,
DispatchAttemptCount = 0,
LastDispatchAttemptAtUtc = null,
NextDispatchAttemptAtUtc = now,
ErrorCode = null,
ErrorMessage = null
};
var audit = new AdminAuditEvent
{
Id = Guid.NewGuid().ToString("N"),
OccurredAt = now,
ActorUsername = actorUser,
ActorRole = actorRole,
Action = "DEVICE_UPDATE_REQUESTED",
TargetType = "DeviceUpdateRun",
TargetId = runId,
Details = JsonSerializer.Serialize(new
{
updateRunId = runId,
deviceId = device.Id,
tenantId = device.TenantId,
releaseId = release.Id,
fromVersion = updateRun.FromVersion,
targetVersion = updateRun.TargetVersion,
correlationId
}),
IpAddress = clientIp
};
_db.DeviceUpdateRuns.Add(updateRun);
_db.AdminAuditEvents.Add(audit);
await _db.SaveChangesAsync(ct);
_logger.LogInformation("Device update requested: RunId={RunId}, DeviceId={DeviceId}, TargetVersion={Version}, Release={ReleaseId}",
runId, device.Id, release.Version, release.Id);
// 6. 唤醒调度 Worker
_dispatchNotifier.Notify();
return DeviceUpdateCreationResult.Accepted(MapToDto(updateRun));
}
finally
{
gate.Release();
}
}
public async Task> GetDeviceUpdateRunAsync(
string updateRunId,
string actorRole,
CancellationToken ct)
{
if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase))
{
return DeviceUpdateQueryResult.Forbidden("仅系统管理员允许查询升级任务详情。");
}
var run = await _db.DeviceUpdateRuns.AsNoTracking().FirstOrDefaultAsync(u => u.Id == updateRunId, ct);
if (run == null)
{
return DeviceUpdateQueryResult.NotFound($"升级任务 '{updateRunId}' 不存在。");
}
return DeviceUpdateQueryResult.Ok(MapToDto(run));
}
public async Task>> GetDeviceUpdateHistoryAsync(
string deviceId,
int take,
string actorRole,
CancellationToken ct)
{
if (!string.Equals(actorRole, "SuperAdmin", StringComparison.OrdinalIgnoreCase))
{
return DeviceUpdateQueryResult>.Forbidden("仅系统管理员允许查询设备升级历史。");
}
var clampedTake = Math.Clamp(take <= 0 ? 5 : take, 1, 20);
var list = await _db.DeviceUpdateRuns
.AsNoTracking()
.Where(u => u.DeviceId == deviceId)
.OrderByDescending(u => u.CreatedAtUtc)
.Take(clampedTake)
.Select(u => MapToDto(u))
.ToListAsync(ct);
return DeviceUpdateQueryResult>.Ok(list);
}
public async Task PreparePackageDownloadAsync(
string releaseId,
string deviceId,
CancellationToken ct)
{
var device = await _db.Devices.AsNoTracking().FirstOrDefaultAsync(d => d.Id == deviceId, ct);
if (device == null)
{
return DeviceUpdateDownloadResult.Forbidden("未经认证或未知的设备标识。");
}
var release = await _db.UpdateReleases.AsNoTracking().FirstOrDefaultAsync(r => r.Id == releaseId, ct);
if (release == null || !release.IsEnabled)
{
return DeviceUpdateDownloadResult.NotFound($"目标升级版本 '{releaseId}' 不存在或已被停用。");
}
// 路径防逃逸核验
var root = _options.Value.GetEffectiveStorageRoot();
string physicalPath;
try
{
physicalPath = UpdatePackagePathResolver.ResolvePackagePath(root, release.PackageRelativePath);
}
catch (InvalidUpdatePackagePathException ex)
{
_logger.LogWarning("CRITICAL: Package path traversal detected for release {ReleaseId}: {Message} (Path='{Path}')",
release.Id, ex.Message, release.PackageRelativePath);
return DeviceUpdateDownloadResult.BadRequest(UpdateErrorCodes.InvalidStoragePath, "Invalid package path detected.");
}
if (!File.Exists(physicalPath))
{
_logger.LogError("Update package file missing from disk: ReleaseId={ReleaseId}, Path={Path}", release.Id, physicalPath);
return DeviceUpdateDownloadResult.ServerError(UpdateErrorCodes.PackageNotReady, "Update package file is missing from storage.");
}
var downloadName = $"classnotify-update-{release.Version}-{release.Architecture}.zip";
return DeviceUpdateDownloadResult.Ok(physicalPath, downloadName, release.PackageSha256, release.PackageSizeBytes);
}
public async Task ReportDeviceUpdateStatusAsync(
string deviceId,
string updateRunId,
DeviceUpdateReportRequest request,
CancellationToken ct)
{
var run = await _db.DeviceUpdateRuns.FirstOrDefaultAsync(u => u.Id == updateRunId && u.DeviceId == deviceId, ct);
if (run == null)
{
_logger.LogWarning("Update run {RunId} for device {DeviceId} not found for status report.", updateRunId, deviceId);
return DeviceUpdateReportResult.NotFound($"Update run '{updateRunId}' not found for device '{deviceId}'.");
}
// 状态流转合法性校验 (严防非法跳转与终态复活)
if (!IsValidTransition(run.Status, request.Status))
{
_logger.LogWarning("Illegal update state transition rejected for run {RunId}: Current={Current}, Requested={Requested}",
run.Id, run.Status, request.Status);
return DeviceUpdateReportResult.Conflict(
UpdateErrorCodes.InvalidUpdateStateTransition,
$"Invalid update state transition from '{run.Status}' to '{request.Status}'. Terminal states cannot be revived.");
}
run.Status = request.Status;
if (!string.IsNullOrWhiteSpace(request.ErrorCode)) run.ErrorCode = request.ErrorCode;
if (!string.IsNullOrWhiteSpace(request.ErrorMessage)) run.ErrorMessage = request.ErrorMessage;
var now = DateTimeOffset.UtcNow;
if (request.Status == UpdateStatuses.Succeeded)
{
run.CompletedAtUtc = now;
// 升级成功:同步更新设备的版本心跳与客户端版本 (U8)
var dev = await _db.Devices.FirstOrDefaultAsync(d => d.Id == deviceId, ct);
if (dev != null)
{
dev.ServiceVersion = run.TargetVersion;
dev.ClientVersion = run.TargetVersion;
_logger.LogInformation("Device {DeviceId} successfully updated from {FromVersion} to {TargetVersion}!",
deviceId, run.FromVersion, run.TargetVersion);
}
}
else if (UpdateStatuses.TerminalStatuses.Contains(request.Status))
{
run.CompletedAtUtc = now;
_logger.LogWarning("Update run {RunId} for device {DeviceId} terminated with status {Status}: Error={Error}, Msg={Msg}",
run.Id, deviceId, request.Status, request.ErrorCode, request.ErrorMessage);
}
// Phase 3: 若任务隶属于灰度批次,即时推进批次生命周期状态 (CanaryRunning -> AwaitingContinue / Stopped; RollingOut -> Completed)
if (!string.IsNullOrWhiteSpace(run.BatchId))
{
var batch = await _db.DeviceUpdateBatches
.Include(b => b.Runs)
.FirstOrDefaultAsync(b => b.Id == run.BatchId, ct);
if (batch != null)
{
if (batch.Status == UpdateBatchStatuses.CanaryRunning && run.IsCanary)
{
if (request.Status == UpdateStatuses.Succeeded)
{
batch.Status = UpdateBatchStatuses.AwaitingContinue;
_logger.LogInformation("Batch {BatchId} Canary device {DeviceId} succeeded. Batch -> AwaitingContinue.", batch.Id, deviceId);
}
else if (UpdateStatuses.TerminalStatuses.Contains(request.Status))
{
batch.Status = UpdateBatchStatuses.Stopped;
batch.StoppedAtUtc = now;
_logger.LogWarning("Batch {BatchId} Canary device {DeviceId} entered terminal status {Status}. Batch -> Stopped.", batch.Id, deviceId, request.Status);
}
}
else if (batch.Status == UpdateBatchStatuses.RollingOut)
{
bool allTerminal = batch.Runs.Count > 0 && batch.Runs.All(r => UpdateStatuses.TerminalStatuses.Contains(r.Status));
if (allTerminal)
{
batch.Status = UpdateBatchStatuses.Completed;
batch.CompletedAtUtc = now;
_logger.LogInformation("Batch {BatchId} all {Count} runs reached terminal states. Batch -> Completed.", batch.Id, batch.Runs.Count);
}
}
}
}
await _db.SaveChangesAsync(ct);
return DeviceUpdateReportResult.Ok();
}
private static bool IsValidTransition(string currentStatus, string targetStatus)
{
if (string.Equals(currentStatus, targetStatus, StringComparison.OrdinalIgnoreCase))
{
return true; // Idempotent same-state report
}
// 终态不可复活 (Succeeded, Failed, RolledBack, RollbackFailed, TimedOut)
if (UpdateStatuses.TerminalStatuses.Contains(currentStatus))
{
return false;
}
return currentStatus switch
{
UpdateStatuses.PendingDispatch => targetStatus is UpdateStatuses.Downloading or UpdateStatuses.Failed or UpdateStatuses.TimedOut,
UpdateStatuses.Downloading => targetStatus is UpdateStatuses.Verified or UpdateStatuses.Failed or UpdateStatuses.TimedOut,
UpdateStatuses.Verified => targetStatus is UpdateStatuses.Installing or UpdateStatuses.Failed or UpdateStatuses.TimedOut,
UpdateStatuses.Installing => targetStatus is UpdateStatuses.HealthChecking or UpdateStatuses.Succeeded or UpdateStatuses.RollingBack or UpdateStatuses.Failed or UpdateStatuses.TimedOut,
UpdateStatuses.HealthChecking => targetStatus is UpdateStatuses.Succeeded or UpdateStatuses.RollingBack or UpdateStatuses.Failed or UpdateStatuses.TimedOut,
UpdateStatuses.RollingBack => targetStatus is UpdateStatuses.RolledBack or UpdateStatuses.RollbackFailed or UpdateStatuses.Failed or UpdateStatuses.TimedOut,
_ => false
};
}
private static DeviceUpdateStatusDto MapToDto(DeviceUpdateRun u) => new()
{
UpdateRunId = u.Id,
DeviceId = u.DeviceId,
TenantId = u.TenantId,
ReleaseId = u.ReleaseId,
Status = u.Status,
FromVersion = u.FromVersion,
TargetVersion = u.TargetVersion,
CreatedAtUtc = u.CreatedAtUtc,
DeadlineAtUtc = u.DeadlineAtUtc,
CompletedAtUtc = u.CompletedAtUtc,
ErrorCode = u.ErrorCode,
ErrorMessage = u.ErrorMessage
};
}