ResetRobotCommandHandler.cs 4.54 KB
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.MessageBus.Commands;
using Rcs.Application.Services.Protocol;
using Rcs.Domain.Extensions;
using Rcs.Domain.Repositories;
using TaskStatus = Rcs.Domain.Entities.TaskStatus;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands;

/// <summary>
/// 复位机器人命令处理器
/// @author zzy
/// </summary>
public class ResetRobotCommandHandler : IConsumer<ResetRobotCommand>
{
    private readonly ILogger<ResetRobotCommandHandler> _logger;
    private readonly IRobotRepository _robotRepository;
    private readonly IRobotTaskRepository _robotTaskRepository;
    private readonly IProtocolServiceFactory _protocolServiceFactory;
    private readonly IRequestClient<ExecuteRobotSubTaskCommand> _executeRobotSubTaskClient;

    public ResetRobotCommandHandler(
        ILogger<ResetRobotCommandHandler> logger,
        IRobotRepository robotRepository,
        IRobotTaskRepository robotTaskRepository,
        IProtocolServiceFactory protocolServiceFactory,
        IRequestClient<ExecuteRobotSubTaskCommand> executeRobotSubTaskClient)
    {
        _logger = logger;
        _robotRepository = robotRepository;
        _robotTaskRepository = robotTaskRepository;
        _protocolServiceFactory = protocolServiceFactory;
        _executeRobotSubTaskClient = executeRobotSubTaskClient;
    }

    public async Task Consume(ConsumeContext<ResetRobotCommand> context)
    {
        var command = context.Message;
        try
        {
            var robot = await _robotRepository.GetByIdAsync(command.RobotId, context.CancellationToken);
            if (robot == null)
            {
                throw new BusinessException($"机器人ID {command.RobotId} 不存在");
            }

            var protocolService = _protocolServiceFactory.GetService(robot);

            // 先对执行中的子任务进行重新执行处理,确保子任务上下文(含SubTaskId)先重建
            var inProgressSubTask = await FindInProgressSubTaskAsync(command.RobotId, context.CancellationToken);
            if (inProgressSubTask != null)
            {
                _logger.LogInformation(
                    "复位前先重执行执行中子任务: RobotId={RobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}, Sequence={Sequence}",
                    command.RobotId,
                    inProgressSubTask.TaskId,
                    inProgressSubTask.SubTaskId,
                    inProgressSubTask.Sequence);

                var subTaskResp = await _executeRobotSubTaskClient.GetResponse<ApiResponse>(
                    new ExecuteRobotSubTaskCommand
                    {
                        SubTaskId = inProgressSubTask.SubTaskId
                    },
                    context.CancellationToken);

                if (!subTaskResp.Message.Success)
                {
                    throw new BusinessException(
                        $"复位前重执行子任务失败,SubTaskId={inProgressSubTask.SubTaskId},原因:{subTaskResp.Message.Message}");
                }
            }

            // 复位机器人
            await protocolService.ResetRobotAsync(robot, context.CancellationToken);

            await context.RespondAsync(ApiResponse.Successful());
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "复位机器人失败: {RobotId}", command.RobotId);
            await context.RespondAsync(ApiResponse.Failed(ex.Message));
        }
    }

    private async Task<Domain.Entities.RobotSubTask?> FindInProgressSubTaskAsync(Guid robotId, CancellationToken cancellationToken)
    {
        var tasks = (await _robotTaskRepository.GetByRobotIdAsync(robotId, cancellationToken))
            .Where(t => t.SubTasks != null && t.SubTasks.Any())
            .ToList();

        var inProgressSubTask = tasks
            .Where(t => t.Status == TaskStatus.InProgress)
            .SelectMany(t => t.SubTasks.Select(st => new { Task = t, SubTask = st }))
            .Where(x => x.SubTask.Status == TaskStatus.InProgress)
            .OrderBy(x => x.SubTask.Sequence)
            .Select(x => x.SubTask)
            .FirstOrDefault();

        if (inProgressSubTask != null)
        {
            return inProgressSubTask;
        }

        // 兜底:若主任务状态尚未同步为InProgress,仍允许取机器人下第一个执行中子任务
        return tasks
            .SelectMany(t => t.SubTasks)
            .Where(st => st.Status == TaskStatus.InProgress)
            .OrderBy(st => st.Sequence)
            .FirstOrDefault();
    }
}