CancelRobotTaskCommandHandler.cs 1.89 KB
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.MessageBus.Commands;
using Rcs.Domain.Extensions;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands;

/// <summary>
/// 取消机器人任务命令处理器
/// 职责:协调领域操作,实际取消指令下发由领域事件处理器完成
/// @author zzy
/// </summary>
public class CancelRobotTaskCommandHandler : IConsumer<CancelRobotTaskCommand>
{
    private readonly ILogger<CancelRobotTaskCommandHandler> _logger;
    private readonly IRobotRepository _robotRepository;

    public CancelRobotTaskCommandHandler(
        ILogger<CancelRobotTaskCommandHandler> logger,
        IRobotRepository robotRepository)
    {
        _logger = logger;
        _robotRepository = robotRepository;
    }

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

            // 调用 Robot 领域方法取消任务,触发 RobotTaskCancelledDomainEvent
            // 事件处理器负责:1.向机器人下发取消指令 2.更新任务状态
            robot.CancelTask(null);

            // 保存变更,领域事件会在 SaveChangesAsync 中同步分发
            // await _robotRepository.SaveChangesAsync(context.CancellationToken);

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