FatigueTestBackgroundService.cs 14.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
using System.Collections.Concurrent;
using MassTransit.Mediator;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.MessageBus.Commands;
using Rcs.Application.Services;
using Rcs.Domain.Entities;
using Rcs.Domain.Repositories;
using Rcs.Shared.Utils;
using TaskStatus = Rcs.Domain.Entities.TaskStatus;

namespace Rcs.Infrastructure.Services;

/// <summary>
/// Fatigue test background service. One worker per running fatigue config.
/// </summary>
public class FatigueTestBackgroundService : BackgroundService
{
    private readonly ILogger<FatigueTestBackgroundService> _logger;
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly TimeSpan _checkInterval = TimeSpan.FromSeconds(5);
    private readonly ConcurrentDictionary<string, WorkerState> _workers = new(StringComparer.OrdinalIgnoreCase);

    public FatigueTestBackgroundService(
        ILogger<FatigueTestBackgroundService> logger,
        IServiceScopeFactory scopeFactory)
    {
        _logger = logger;
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("[FatigueTest] Fatigue test background service started");

        try
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                await SyncWorkersAsync(stoppingToken);
                await Task.Delay(_checkInterval, stoppingToken);
            }
        }
        catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
        {
            // ignored
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "[FatigueTest] Supervisor loop crashed");
        }
        finally
        {
            await StopAllWorkersAsync();
            _logger.LogInformation("[FatigueTest] Fatigue test background service stopped");
        }
    }

    private async Task SyncWorkersAsync(CancellationToken cancellationToken)
    {
        await CleanupCompletedWorkersAsync();

        using var scope = _scopeFactory.CreateScope();
        var configService = scope.ServiceProvider.GetRequiredService<IFatigueTestConfigService>();
        var configs = await configService.GetConfigsAsync(cancellationToken);

        var runningConfigIds = configs
            .Where(c => c.IsRunning && !string.IsNullOrWhiteSpace(c.ConfigId))
            .Select(c => c.ConfigId)
            .ToHashSet(StringComparer.OrdinalIgnoreCase);

        var existingWorkerIds = _workers.Keys.ToList();
        foreach (var workerId in existingWorkerIds)
        {
            if (!runningConfigIds.Contains(workerId))
            {
                await StopWorkerAsync(workerId);
            }
        }

        foreach (var configId in runningConfigIds)
        {
            if (_workers.ContainsKey(configId))
            {
                continue;
            }

            var workerCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            var workerTask = RunWorkerAsync(configId, workerCts.Token);
            var workerState = new WorkerState(workerCts, workerTask);

            if (!_workers.TryAdd(configId, workerState))
            {
                workerCts.Cancel();
                workerCts.Dispose();
                continue;
            }

            _logger.LogInformation("[FatigueTest] Worker started for config {ConfigId}", configId);
        }
    }

    private async Task CleanupCompletedWorkersAsync()
    {
        foreach (var kvp in _workers.ToArray())
        {
            if (!kvp.Value.Task.IsCompleted)
            {
                continue;
            }

            if (!_workers.TryRemove(kvp.Key, out var removed))
            {
                continue;
            }

            try
            {
                await removed.Task;
            }
            catch (OperationCanceledException)
            {
                // ignored
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "[FatigueTest] Worker {ConfigId} failed", kvp.Key);
            }
            finally
            {
                removed.Cts.Dispose();
            }
        }
    }

    private async Task StopWorkerAsync(string configId)
    {
        if (!_workers.TryRemove(configId, out var worker))
        {
            return;
        }

        worker.Cts.Cancel();
        try
        {
            await worker.Task;
        }
        catch (OperationCanceledException)
        {
            // ignored
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "[FatigueTest] Worker {ConfigId} stopped with error", configId);
        }
        finally
        {
            worker.Cts.Dispose();
        }

        _logger.LogInformation("[FatigueTest] Worker stopped for config {ConfigId}", configId);
    }

    private async Task StopAllWorkersAsync()
    {
        var allWorkerIds = _workers.Keys.ToList();
        foreach (var configId in allWorkerIds)
        {
            await StopWorkerAsync(configId);
        }
    }

    private async Task RunWorkerAsync(string configId, CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            try
            {
                using var scope = _scopeFactory.CreateScope();
                var configService = scope.ServiceProvider.GetRequiredService<IFatigueTestConfigService>();
                var config = await configService.GetConfigByIdAsync(configId, cancellationToken);

                if (config?.IsRunning != true)
                {
                    _logger.LogInformation("[FatigueTest] Worker exits for config {ConfigId} because config is stopped or deleted", configId);
                    return;
                }

                await ProcessSingleConfigOnceAsync(config, scope.ServiceProvider, cancellationToken);
            }
            catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
            {
                return;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "[FatigueTest] Error while processing config {ConfigId}", configId);
            }

            await Task.Delay(_checkInterval, cancellationToken);
        }
    }

    private async Task ProcessSingleConfigOnceAsync(
        FatigueTestConfig config,
        IServiceProvider serviceProvider,
        CancellationToken cancellationToken)
    {
        if (!ValidateConfig(config))
        {
            return;
        }

        var robotRepository = serviceProvider.GetRequiredService<IRobotRepository>();
        var robotTaskRepository = serviceProvider.GetRequiredService<IRobotTaskRepository>();
        var storageLocationRepository = serviceProvider.GetRequiredService<IStorageLocationRepository>();
        var mediator = serviceProvider.GetRequiredService<IMediator>();

        var availableRobotAssignments = await GetAvailableRobotsAsync(
            config.RobotIds,
            robotRepository,
            robotTaskRepository,
            cancellationToken);

        if (!availableRobotAssignments.Any())
        {
            _logger.LogDebug("[FatigueTest] Config {ConfigId}: no available robot", config.ConfigId);
            return;
        }

        var locationIds = config.LocationIds
            .Where(id => Guid.TryParse(id, out _))
            .Select(Guid.Parse)
            .ToList();

        if (locationIds.Count < 2)
        {
            _logger.LogWarning("[FatigueTest] Config {ConfigId}: locations are less than 2", config.ConfigId);
            return;
        }

        var allLocations = new List<StorageLocation>();
        foreach (var locationId in locationIds)
        {
            var location = await storageLocationRepository.GetByIdAsync(locationId, cancellationToken);
            if (location != null && location.IsActive)
            {
                allLocations.Add(location);
            }
        }

        var occupiedLocations = allLocations
            .Where(l => l.Status == StorageLocationStatus.Occupied)
            .ToList();
        var emptyLocations = allLocations
            .Where(l => l.Status == StorageLocationStatus.Empty)
            .ToList();

        if (!occupiedLocations.Any() || !emptyLocations.Any())
        {
            _logger.LogDebug(
                "[FatigueTest] Config {ConfigId}: insufficient occupied or empty locations, occupied={OccupiedCount}, empty={EmptyCount}",
                config.ConfigId,
                occupiedLocations.Count,
                emptyLocations.Count);
            return;
        }

        var random = Random.Shared;
        var (robot, cacheLocation) = availableRobotAssignments[random.Next(availableRobotAssignments.Count)];
        var beginLocation = occupiedLocations[random.Next(occupiedLocations.Count)];
        var endLocation = emptyLocations[random.Next(emptyLocations.Count)];

        if (beginLocation.LocationId == endLocation.LocationId)
        {
            _logger.LogDebug("[FatigueTest] Config {ConfigId}: begin and end locations are the same", config.ConfigId);
            return;
        }

        var hasActiveTask = await CheckLocationHasActiveTaskAsync(
            beginLocation.LocationId,
            endLocation.LocationId,
            robotTaskRepository,
            cancellationToken);

        if (hasActiveTask)
        {
            _logger.LogDebug("[FatigueTest] Config {ConfigId}: begin or end location already has active task", config.ConfigId);
            return;
        }

        await CreateTransportTaskAsync(
            robot,
            cacheLocation,
            beginLocation,
            endLocation,
            mediator,
            robotRepository,
            cancellationToken);

        _logger.LogInformation(
            "[FatigueTest] Config {ConfigId}: task created, robot={RobotCode}, begin={BeginLocation}, end={EndLocation}",
            config.ConfigId,
            robot.RobotCode,
            beginLocation.LocationCode,
            endLocation.LocationCode);

        await Task.Delay(config.TaskIntervalMs, cancellationToken);
    }

    private bool ValidateConfig(FatigueTestConfig config)
    {
        if (!config.RobotIds.Any())
        {
            _logger.LogWarning("[FatigueTest] Config {ConfigId} invalid: RobotIds is empty", config.ConfigId);
            return false;
        }

        if (!config.LocationIds.Any())
        {
            _logger.LogWarning("[FatigueTest] Config {ConfigId} invalid: LocationIds is empty", config.ConfigId);
            return false;
        }

        return true;
    }

    private async Task<List<(Robot Robot, RobotCacheLocation CacheLocation)>> GetAvailableRobotsAsync(
        List<string> robotIds,
        IRobotRepository robotRepository,
        IRobotTaskRepository robotTaskRepository,
        CancellationToken cancellationToken)
    {
        var availableRobots = new List<(Robot Robot, RobotCacheLocation CacheLocation)>();

        foreach (var robotIdStr in robotIds)
        {
            if (!Guid.TryParse(robotIdStr, out var robotId))
            {
                continue;
            }

            var robot = await robotRepository.GetByIdFullDataAsync(robotId, cancellationToken);
            if (robot?.Active != true)
            {
                continue;
            }

            var inProgressTasks = await robotTaskRepository.GetnProgressByRobotIdAsync(robotId, cancellationToken);
            if (inProgressTasks.Any())
            {
                _logger.LogDebug("[FatigueTest] Robot {RobotCode} has in-progress task, skipped", robot.RobotCode);
                continue;
            }

            var availableCacheLocation = robot.CacheLocations
                .FirstOrDefault(location => string.IsNullOrWhiteSpace(location.ContainerId));
            if (availableCacheLocation == null)
            {
                _logger.LogDebug("[FatigueTest] Robot {RobotCode} has no empty cache location, skipped", robot.RobotCode);
                continue;
            }

            availableRobots.Add((robot, availableCacheLocation));
        }

        return availableRobots;
    }

    private async Task<bool> CheckLocationHasActiveTaskAsync(
        Guid beginLocationId,
        Guid endLocationId,
        IRobotTaskRepository robotTaskRepository,
        CancellationToken cancellationToken)
    {
        var allTasks = await robotTaskRepository.GetAllAsync(cancellationToken);
        var activeTasks = allTasks.Where(t => t.Status != TaskStatus.Cancelled && t.Status != TaskStatus.Completed).ToList();

        foreach (var task in activeTasks)
        {
            if (task.BeginLocationId.HasValue &&
                (task.BeginLocationId.Value == beginLocationId || task.BeginLocationId.Value == endLocationId))
            {
                return true;
            }

            if (task.EndLocationId.HasValue &&
                (task.EndLocationId.Value == beginLocationId || task.EndLocationId.Value == endLocationId))
            {
                return true;
            }
        }

        return false;
    }

    private async Task CreateTransportTaskAsync(
        Robot robot,
        RobotCacheLocation cacheLocation,
        StorageLocation beginLocation,
        StorageLocation endLocation,
        IMediator mediator,
        IRobotRepository robotRepository,
        CancellationToken cancellationToken)
    {
        var command = new CreateOrUpdateRobotTaskCommand
        {
            TaskCode = $"FATIGUE_{DateTime.Now:yyMMddHHmmss}_{Guid.NewGuid().ToString("N")[..6].ToUpper()}",
            TaskName = $"FatigueTask_{DateTime.Now:HHmmss}",
            RobotId = robot.RobotId.ToString(),
            ShelfCode = cacheLocation.LocationCode,
            BeginLocationId = beginLocation.LocationId.ToString(),
            EndLocationId = endLocation.LocationId.ToString(),
            ContainerID = GenerateHash.GenerateHashLength8(),
            Priority = 50,
            Status = (int)TaskStatus.Pending
        };

        var client = mediator.CreateRequestClient<CreateOrUpdateRobotTaskCommand>();
        var response = await client.GetResponse<ApiResponse>(command, cancellationToken);

        if (!response.Message.Success)
        {
            throw new InvalidOperationException($"Create task failed: {response.Message.Message}");
        }

        var targetCacheLocation = robot.CacheLocations
            .FirstOrDefault(c => c.LocationCode == command.ShelfCode)
            ?? cacheLocation;

        targetCacheLocation.ContainerId = command.ContainerID;
        targetCacheLocation.UpdatedAt = DateTime.Now;

        await robotRepository.UpdateAsync(robot, cancellationToken);
        await robotRepository.SaveChangesAsync(cancellationToken);
    }

    private sealed class WorkerState
    {
        public WorkerState(CancellationTokenSource cts, Task task)
        {
            Cts = cts;
            Task = task;
        }

        public CancellationTokenSource Cts { get; }

        public Task Task { get; }
    }
}