TaskExecutionBackgroundService.cs
43.7 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Rcs.Application.Services;
using Rcs.Application.Services.PathFind;
using Rcs.Application.Services.PathFind.Models;
using Rcs.Application.Services.Protocol;
using Rcs.Application.Shared;
using Rcs.Domain.Entities;
using Rcs.Domain.Enums;
using Rcs.Domain.Models.VDA5050;
using Rcs.Domain.Repositories;
using Rcs.Domain.Settings;
using Rcs.Infrastructure.DB.MsSql;
using Rcs.Infrastructure.PathFinding.Services;
using StackExchange.Redis;
using System.Text.Json;
using Newtonsoft.Json;
using TaskStatus = Rcs.Domain.Entities.TaskStatus;
namespace Rcs.Infrastructure.Services
{
/// <summary>
/// 后台任务执行服务 - 将已分配的任务下发给空闲机器人执行
/// @author zzy
/// </summary>
public class TaskExecutionBackgroundService : BackgroundService, ITaskExecutionService
{
private readonly ILogger<TaskExecutionBackgroundService> _logger;
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IRobotCacheService _robotCacheService;
private readonly IAgvPathService _agvPathService;
private readonly ITaskLeaseService _taskLeaseService;
private readonly IConnectionMultiplexer _redis;
private readonly AppSettings _settings;
private readonly TimeSpan _executionInterval = TimeSpan.FromSeconds(2);
private const int MaxAssignedTasksPerCycle = 10;
private static readonly TimeSpan StarvationCounterTtl = TimeSpan.FromHours(24);
private static readonly TimeSpan ExecutionStartedLatchTtl = TimeSpan.FromMinutes(10);
private const string TaskExecutionDeferKeySuffix = "task-exec-defer";
private const string TaskExecutionStartedLatchKeySuffix = "task-exec-started";
public TaskExecutionBackgroundService(
ILogger<TaskExecutionBackgroundService> logger,
IServiceScopeFactory serviceScopeFactory,
IRobotCacheService robotCacheService,
IAgvPathService agvPathService,
ITaskLeaseService taskLeaseService,
IConnectionMultiplexer redis,
IOptions<AppSettings> settings)
{
_logger = logger;
_serviceScopeFactory = serviceScopeFactory;
_robotCacheService = robotCacheService;
_agvPathService = agvPathService;
_taskLeaseService = taskLeaseService;
_redis = redis;
_settings = settings.Value;
}
/// <summary>
/// 后台服务执行入口
/// @author zzy
/// </summary>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("[任务执行] 后台任务执行服务已启动");
while (!stoppingToken.IsCancellationRequested)
{
try
{
await ExecuteTasksAsync(stoppingToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "[任务执行] 执行过程发生异常");
}
await Task.Delay(_executionInterval, stoppingToken);
}
_logger.LogInformation("[任务执行] 后台任务执行服务已停止");
}
/// <summary>
/// 执行一次任务执行检查
/// @author zzy
/// </summary>
public async Task<TaskExecutionResult> ExecuteTasksAsync(CancellationToken cancellationToken = default)
{
using var scope = _serviceScopeFactory.CreateScope();
var taskRepo = scope.ServiceProvider.GetRequiredService<IRobotTaskRepository>();
var robotRepo = scope.ServiceProvider.GetRequiredService<IRobotRepository>();
// 1. 获取已分配和执行中的任务(执行中的任务可能有待执行的子任务)
var assignedTasks = await taskRepo.GetByStatusAsync(TaskStatus.Assigned, cancellationToken);
var inProgressTasks = await taskRepo.GetByStatusAsync(TaskStatus.InProgress, cancellationToken);
var activeTasks = assignedTasks
.Concat(inProgressTasks)
.Where(t => t.RobotId.HasValue)
.ToList();
if (!activeTasks.Any())
{
return new TaskExecutionResult { Success = true, ExecutedCount = 0, Message = "无待执行任务" };
}
var tasksToExecute = await BuildExecutionQueueAsync(activeTasks, robotRepo, taskRepo, cancellationToken);
_logger.LogInformation("执行队列{queue}",JsonConvert.SerializeObject(tasksToExecute.Select(t => t.ShelfCode)));
if (!tasksToExecute.Any())
{
return new TaskExecutionResult { Success = true, ExecutedCount = 0, Message = "无待执行任务" };
}
int executedCount = 0;
foreach (var task in tasksToExecute)
{
if (!task.RobotId.HasValue) continue;
// 2. 获取机器人信息
var robot = await robotRepo.GetByIdFullDataAsync(task.RobotId.Value, cancellationToken);
if (robot == null)
{
_logger.LogWarning("[任务执行] 任务 {TaskCode} 对应的机器人不存在", task.TaskCode);
continue;
}
if (!robot.IsRobotAvailable())
{
_logger.LogDebug("[任务执行] 机器人 {RobotCode} 当前不可用", robot.RobotCode);
continue;
}
// 4. 检查机器人是否有执行中的任务
var hasInProgressTask = await HasInProgressTaskAsync(robot.RobotId, task.TaskId, taskRepo, cancellationToken);
if (hasInProgressTask)
{
_logger.LogDebug("[任务执行] 机器人 {RobotCode} 存在执行中任务", robot.RobotCode);
continue;
}
var leaseAcquireResult = await _taskLeaseService.TryAcquireAsync(
task.TaskId,
robot.RobotId,
"execute",
cancellationToken);
if (!leaseAcquireResult.Success || leaseAcquireResult.Lease == null)
{
_logger.LogDebug(
"[任务执行] 跳过任务(租约冲突): TaskCode={TaskCode}, RobotCode={RobotCode}",
task.TaskCode,
robot.RobotCode);
continue;
}
// 5. 根据协议类型执行任务
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
dbContext.ChangeTracker.Clear();
await using var lease = leaseAcquireResult.Lease;
var success = await ExecuteTaskByProtocolAsync(task, robot, taskRepo, scope, cancellationToken);
if (success)
{
await SetExecutionStartedLatchAsync(task.TaskId, cancellationToken);
executedCount++;
}
else
{
await ClearExecutionStartedLatchAsync(task.TaskId, cancellationToken);
}
}
return new TaskExecutionResult
{
Success = true,
ExecutedCount = executedCount,
Message = $"本次执行完成,已下发 {executedCount} 个任务"
};
}
/// <summary>
/// 构建执行队列:按机器人分组后,为每台机器人挑选一个最优候选任务。
/// 候选任务按任务优先级降序(数值越大越优先)排序,
/// 同优先级按路径代价升序、创建时间毫秒值升序排序(更早创建优先)。
/// </summary>
/// <param name="activeTasks">当前活动任务集合(Assigned + InProgress)</param>
/// <param name="robotRepo">机器人仓储</param>
/// <param name="taskRepo">任务仓储</param>
/// <param name="cancellationToken">取消令牌</param>
/// <returns>本轮待执行任务列表</returns>
private async Task<List<RobotTask>> BuildExecutionQueueAsync(
IEnumerable<RobotTask> activeTasks,
IRobotRepository robotRepo,
IRobotTaskRepository taskRepo,
CancellationToken cancellationToken)
{
var selectedCandidates = new List<TaskCandidate>();
var mapGraphCache = new Dictionary<Guid, PathGraph?>();
// 按机器人分组,每个机器人每轮最多选择一个“下一下发任务”
var taskGroups = activeTasks
.Where(t => t.RobotId.HasValue)
.GroupBy(t => t.RobotId!.Value);
foreach (var taskGroup in taskGroups)
{
var robot = await robotRepo.GetByIdFullDataAsync(taskGroup.Key, cancellationToken);
if (robot == null)
{
continue;
}
// 判断机器人是否仍在执行:只看“执行中子任务”,不依赖主任务状态
var hasInProgressSubTask = taskGroup.Any(t =>
t.SubTasks.Any(st => st.Status == TaskStatus.InProgress));
if (hasInProgressSubTask)
{
continue;
}
var candidateTasks = new List<TaskCandidate>();
foreach (var task in taskGroup)
{
var taskWithDetails = await taskRepo.GetByIdWithDetailsAsync(task.TaskId, cancellationToken);
if (taskWithDetails == null)
{
continue;
}
if (!taskWithDetails.SubTasks.Any() && taskWithDetails.Status == TaskStatus.InProgress)
{
continue;
}
var nextSubTask = taskWithDetails.GetNextExecutableSubTask();
if (taskWithDetails.SubTasks.Any() && nextSubTask == null)
{
continue;
}
var pathEvaluation = await CalculatePathCostToTaskAsync(
robot,
taskWithDetails,
nextSubTask,
mapGraphCache,
cancellationToken);
if (pathEvaluation.PathCost == double.MaxValue)
{
continue;
}
candidateTasks.Add(new TaskCandidate(
taskWithDetails,
nextSubTask,
pathEvaluation.PathCost,
pathEvaluation.Segments,
CalculateCompletionRatio(taskWithDetails)));
}
if (!candidateTasks.Any())
{
continue;
}
TaskCandidate? selectedTask;
if (_settings.TaskExecution.EnableCompositeSelection)
{
selectedTask = await SelectTaskWithCompositeRulesAsync(robot.RobotId, candidateTasks, cancellationToken);
}
else
{
// 先按任务优先级降序,再按路径代价升序、创建时间毫秒值升序与 TaskId 做稳定排序
selectedTask = candidateTasks
.OrderBy(c => c, TaskCandidateComparer.Instance)
.FirstOrDefault();
}
if (selectedTask != null)
{
// CalculatePathAsync 会更新机器人规划路径,需确保最终状态与选中任务一致。
if (candidateTasks.Count > 1)
{
await CalculatePathCostToTaskAsync(
robot,
selectedTask.Task,
selectedTask.NextSubTask,
mapGraphCache,
cancellationToken);
}
if (_settings.TaskExecution.EnableCompositeSelection)
{
await UpdateStarvationGuardStateAsync(robot.RobotId, candidateTasks, selectedTask.Task.TaskId, cancellationToken);
}
selectedCandidates.Add(selectedTask);
}
}
return selectedCandidates
.OrderBy(c => c, TaskCandidateComparer.Instance)
.Select(c => c.Task)
.Take(MaxAssignedTasksPerCycle)
.ToList();
}
/// <summary>
/// 计算机器人到候选任务目标点的可行路径总代价。
/// 若路径规划发生异常,则回退为当前位置到对应子任务终点的欧几里得保底代价;
/// 若关键数据缺失,返回 <see cref="double.MaxValue"/>。
/// </summary>
/// <param name="robot">机器人实体</param>
/// <param name="task">候选任务</param>
/// <param name="nextSubTask">候选任务的下一子任务</param>
/// <param name="mapGraphCache">地图图缓存,避免重复加载</param>
/// <param name="cancellationToken">取消令牌</param>
/// <returns>可行路径总代价与路径段集合</returns>
private async Task<PathCostEvaluation> CalculatePathCostToTaskAsync(
Robot robot,
RobotTask task,
RobotSubTask? nextSubTask,
IDictionary<Guid, PathGraph?> mapGraphCache,
CancellationToken cancellationToken)
{
var targetNodeId = nextSubTask?.EndNodeId
?? task.BeginLocation?.MapNode?.NodeId
?? task.EndLocation?.MapNode?.NodeId;
if (!targetNodeId.HasValue || targetNodeId.Value == Guid.Empty)
{
return PathCostEvaluation.Invalid;
}
var mapId = nextSubTask?.EndNode?.MapId
?? task.BeginLocation?.MapNode
?.MapId
?? task.EndLocation?.MapNode
?.MapId
?? robot.CurrentMapCodeId;
if (!mapId.HasValue)
{
return PathCostEvaluation.Invalid;
}
if (!mapGraphCache.TryGetValue(mapId.Value, out var graph))
{
graph = await _agvPathService.GetOrBuildGraphAsync(mapId.Value);
mapGraphCache[mapId.Value] = graph;
}
if (graph == null || !graph.Nodes.TryGetValue(targetNodeId.Value, out var targetPathNode))
{
return PathCostEvaluation.Invalid;
}
var startNodeId = ResolveStartNodeId(robot, graph);
if (!startNodeId.HasValue)
{
return PathCostEvaluation.Invalid;
}
var request = new PathRequest
{
RobotId = robot.RobotId,
MapId = mapId.Value,
StartNodeId = startNodeId.Value,
EndNodeId = targetNodeId.Value,
CurrentTheta = robot.CurrentTheta ?? 0d,
IsLoaded = !string.IsNullOrWhiteSpace(task.ContainerID),
Priority = task.Priority,
BatteryLevel = robot.BatteryLevel ?? 100,
MovementType = robot.MovementType,
ForkRadOffsets = robot.ForkRadOffset,
RequiredEndRad = targetPathNode.Theta
};
try
{
var pathResult = await _agvPathService.CalculatePathAsync(request, cancellationToken);
if (!pathResult.Success)
{
throw new Exception($"[任务执行] 候选任务不可达,跳过: RobotCode={robot.RobotCode}, TaskCode={task.TaskCode}, Reason={pathResult.ErrorMessage}");
}
if (double.IsNaN(pathResult.TotalCost) || double.IsInfinity(pathResult.TotalCost))
{
throw new Exception($"[任务执行] 候选任务路径代价无效,跳过: RobotCode={robot.RobotCode}, TaskCode={task.TaskCode}, TotalCost={pathResult.TotalCost}");
}
return new PathCostEvaluation(pathResult.TotalCost, pathResult.Segments);
}
catch (Exception ex)
{
var fallbackCost = CalculateFallbackDistanceToSubTaskEndCost(robot, task, nextSubTask, graph);
if (fallbackCost != double.MaxValue)
{
_logger.LogWarning(
ex,
"[任务执行] 计算候选任务路径代价异常,走兜底(当前位置->子任务终点/主任务起点欧几里得): RobotCode={RobotCode}, TaskCode={TaskCode}, FallbackCost={FallbackCost:F3}",
robot.RobotCode,
task.TaskCode,
fallbackCost);
return new PathCostEvaluation(fallbackCost, Array.Empty<PathSegment>());
}
_logger.LogWarning(
ex,
"[任务执行] 计算候选任务路径代价异常,且无法计算兜底距离,跳过: RobotCode={RobotCode}, TaskCode={TaskCode}",
robot.RobotCode,
task.TaskCode);
return PathCostEvaluation.Invalid;
}
}
/// <summary>
/// 路径规划异常时的保底代价:
/// 有子任务时,机器人当前位置到子任务终点的欧几里得距离;
/// 无子任务时,机器人当前位置到主任务起点的欧几里得距离。
/// </summary>
private static double CalculateFallbackDistanceToSubTaskEndCost(
Robot robot,
RobotTask task,
RobotSubTask? nextSubTask,
PathGraph? graph)
{
var sourceX = robot.CurrentX ?? robot.MapNode?.X;
var sourceY = robot.CurrentY ?? robot.MapNode?.Y;
if (!sourceX.HasValue || !sourceY.HasValue)
{
return double.MaxValue;
}
double? targetX;
double? targetY;
if (nextSubTask != null)
{
targetX = nextSubTask.EndNode?.X;
targetY = nextSubTask.EndNode?.Y;
if ((!targetX.HasValue || !targetY.HasValue)
&& graph != null
&& graph.Nodes.TryGetValue(nextSubTask.EndNodeId, out var endNode))
{
targetX = endNode.X;
targetY = endNode.Y;
}
}
else
{
var beginNodeId = task.BeginLocation?.MapNode?.NodeId;
targetX = task.BeginLocation?.MapNode?.X;
targetY = task.BeginLocation?.MapNode?.Y;
if ((!targetX.HasValue || !targetY.HasValue)
&& beginNodeId.HasValue
&& graph != null
&& graph.Nodes.TryGetValue(beginNodeId.Value, out var beginNode))
{
targetX = beginNode.X;
targetY = beginNode.Y;
}
}
if (!targetX.HasValue || !targetY.HasValue)
{
return double.MaxValue;
}
return CalculateEuclideanDistance(
sourceX.Value,
sourceY.Value,
targetX.Value,
targetY.Value);
}
private static double CalculateEuclideanDistance(double x1, double y1, double x2, double y2)
{
var dx = x1 - x2;
var dy = y1 - y2;
return Math.Sqrt((dx * dx) + (dy * dy));
}
/// <summary>
/// 解析机器人在图中的起始节点:
/// 优先使用当前节点ID;若缺失则按当前位置坐标匹配最近节点。
/// </summary>
private static Guid? ResolveStartNodeId(Robot robot, PathGraph graph)
{
if (robot.CurrentNodeId.HasValue && graph.Nodes.ContainsKey(robot.CurrentNodeId.Value))
{
return robot.CurrentNodeId.Value;
}
var sourceX = robot.CurrentX ?? robot.MapNode?.X;
var sourceY = robot.CurrentY ?? robot.MapNode?.Y;
if (!sourceX.HasValue || !sourceY.HasValue || graph.Nodes.Count == 0)
{
return null;
}
Guid? nearestNodeId = null;
var nearestDistanceSquared = double.MaxValue;
foreach (var node in graph.Nodes.Values)
{
if (!node.Active)
{
continue;
}
var dx = sourceX.Value - node.X;
var dy = sourceY.Value - node.Y;
var distanceSquared = dx * dx + dy * dy;
if (distanceSquared < nearestDistanceSquared)
{
nearestDistanceSquared = distanceSquared;
nearestNodeId = node.NodeId;
}
}
return nearestNodeId;
}
private async Task<TaskCandidate?> SelectTaskWithCompositeRulesAsync(
Guid robotId,
IReadOnlyCollection<TaskCandidate> candidateTasks,
CancellationToken cancellationToken)
{
var starvationForced = await TrySelectTaskByStarvationGuardAsync(robotId, candidateTasks, cancellationToken);
if (starvationForced != null)
{
return starvationForced;
}
var primary = candidateTasks
.OrderBy(c => c, CompositePrimaryComparer.Instance)
.FirstOrDefault();
if (primary == null)
{
return null;
}
var decisionInputs = candidateTasks
.Select(c => new ExecutionCandidateInput(
c.Task.TaskId,
c.Task.Priority,
c.CompletionRatio,
c.PathCost,
c.CreatedAtMilliseconds,
c.Task.TaskId == primary.Task.TaskId
? 0d
: CalculateNonOverlapDistance(c.PathSegments, primary.PathSegments)))
.ToList();
var decision = SelectExecutionCandidate(
decisionInputs,
_settings.TaskExecution.EqualPriorityNonOverlapThreshold,
_settings.TaskExecution.LowerPriorityNonOverlapThreshold);
if (decision is null)
{
return primary;
}
var selected = candidateTasks.FirstOrDefault(c => c.Task.TaskId == decision.Value.SelectedTaskId) ?? primary;
_logger.LogInformation(
"[任务执行] 综合排序选中: RobotId={RobotId}, T1={T1TaskId}, Selected={SelectedTaskId}, Bucket={Bucket}",
robotId,
decision.Value.PrimaryTaskId,
decision.Value.SelectedTaskId,
decision.Value.Bucket);
return selected;
}
private async Task<TaskCandidate?> TrySelectTaskByStarvationGuardAsync(
Guid robotId,
IReadOnlyCollection<TaskCandidate> candidateTasks,
CancellationToken cancellationToken)
{
if (!_settings.TaskExecution.EnableStarvationGuard)
{
return null;
}
var maxDefers = Math.Max(1, _settings.TaskExecution.StarvationGuardMaxDefers);
var db = _redis.GetDatabase();
var forced = new List<TaskCandidate>();
foreach (var candidate in candidateTasks)
{
cancellationToken.ThrowIfCancellationRequested();
if (!ShouldTrackForStarvationGuard(candidate))
{
continue;
}
var key = BuildDeferCounterKey(robotId, candidate.Task.TaskId);
var deferCountValue = await db.StringGetAsync(key);
if (!deferCountValue.HasValue || !long.TryParse(deferCountValue.ToString(), out var deferCount))
{
continue;
}
if (deferCount >= maxDefers)
{
forced.Add(candidate);
}
}
if (!forced.Any())
{
return null;
}
var selected = forced
.OrderBy(c => c, CompositePrimaryComparer.Instance)
.First();
_logger.LogInformation(
"[任务执行] 饥饿保护触发强制执行: RobotId={RobotId}, TaskId={TaskId}, MaxDefers={MaxDefers}",
robotId,
selected.Task.TaskId,
maxDefers);
return selected;
}
private async Task UpdateStarvationGuardStateAsync(
Guid robotId,
IReadOnlyCollection<TaskCandidate> candidateTasks,
Guid selectedTaskId,
CancellationToken cancellationToken)
{
if (!_settings.TaskExecution.EnableStarvationGuard)
{
return;
}
try
{
var db = _redis.GetDatabase();
foreach (var candidate in candidateTasks)
{
cancellationToken.ThrowIfCancellationRequested();
var key = BuildDeferCounterKey(robotId, candidate.Task.TaskId);
if (!ShouldTrackForStarvationGuard(candidate))
{
await db.KeyDeleteAsync(key);
continue;
}
if (candidate.Task.TaskId == selectedTaskId)
{
await db.KeyDeleteAsync(key);
continue;
}
await db.StringIncrementAsync(key);
await db.KeyExpireAsync(key, StarvationCounterTtl);
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "[任务执行] 饥饿保护计数更新失败: RobotId={RobotId}", robotId);
}
}
private string BuildDeferCounterKey(Guid robotId, Guid taskId)
{
return $"{_settings.Redis.KeyPrefixes.Robot}:{TaskExecutionDeferKeySuffix}:{robotId}:{taskId}";
}
private static bool ShouldTrackForStarvationGuard(TaskCandidate candidate)
{
return candidate.NextSubTask != null
&& candidate.Task.SubTasks.Count > 0
&& candidate.CompletionRatio > 0d
&& candidate.CompletionRatio < 1d;
}
private static double CalculateCompletionRatio(RobotTask task)
{
var totalSubTasks = task.SubTasks.Count;
if (totalSubTasks == 0)
{
return 0d;
}
// Skip 语义在实体层通过 Completed 状态落库,因此这里按 Completed 统计即可覆盖 Completed+Skipped。
var completedSubTasks = task.SubTasks.Count(st => st.Status == TaskStatus.Completed);
return (double)completedSubTasks / totalSubTasks;
}
private static double CalculateNonOverlapDistance(
IReadOnlyList<PathSegment> candidateSegments,
IReadOnlyList<PathSegment> primarySegments)
{
if (candidateSegments.Count == 0 || primarySegments.Count == 0)
{
return double.MaxValue;
}
var primaryEdgeIds = primarySegments
.Where(s => s.EdgeId != Guid.Empty)
.Select(s => s.EdgeId)
.ToHashSet();
if (primaryEdgeIds.Count == 0)
{
return double.MaxValue;
}
var candidateRealSegments = candidateSegments
.Where(s => s.EdgeId != Guid.Empty)
.ToList();
if (candidateRealSegments.Count == 0)
{
return double.MaxValue;
}
return candidateRealSegments
.Where(s => !primaryEdgeIds.Contains(s.EdgeId))
.Sum(s => s.Length);
}
internal static ExecutionCandidateDecision? SelectExecutionCandidate(
IReadOnlyCollection<ExecutionCandidateInput> candidateInputs,
double equalPriorityThreshold,
double lowerPriorityThreshold)
{
if (candidateInputs.Count == 0)
{
return null;
}
var primary = candidateInputs
.OrderBy(c => c, CompositePrimaryInputComparer.Instance)
.First();
var equalPrioritySelected = candidateInputs
.Where(c => c.TaskId != primary.TaskId
&& c.Priority == primary.Priority
&& c.NonOverlapDistance <= equalPriorityThreshold)
.OrderBy(c => c.NonOverlapDistance)
.ThenBy(c => c.CreatedAtMilliseconds)
.ThenBy(c => c.TaskId)
.Select(c => (ExecutionCandidateInput?)c)
.FirstOrDefault();
if (equalPrioritySelected.HasValue)
{
return new ExecutionCandidateDecision(
equalPrioritySelected.Value.TaskId,
primary.TaskId,
CandidateSelectionBucket.EqualPriorityReplacement);
}
var lowerPrioritySelected = candidateInputs
.Where(c => c.TaskId != primary.TaskId
&& c.Priority < primary.Priority
&& c.NonOverlapDistance <= lowerPriorityThreshold)
.OrderBy(c => c.NonOverlapDistance)
.ThenBy(c => c.CreatedAtMilliseconds)
.ThenBy(c => c.TaskId)
.Select(c => (ExecutionCandidateInput?)c)
.FirstOrDefault();
if (lowerPrioritySelected.HasValue)
{
return new ExecutionCandidateDecision(
lowerPrioritySelected.Value.TaskId,
primary.TaskId,
CandidateSelectionBucket.LowerPriorityReplacement);
}
return new ExecutionCandidateDecision(
primary.TaskId,
primary.TaskId,
CandidateSelectionBucket.Primary);
}
/// <summary>
/// 候选任务评分上下文。
/// 封装单个候选任务的排序比较信息。
/// </summary>
private sealed class TaskCandidate
{
public TaskCandidate(
RobotTask task,
RobotSubTask? nextSubTask,
double pathCost,
IReadOnlyList<PathSegment> pathSegments,
double completionRatio)
{
Task = task;
NextSubTask = nextSubTask;
PathCost = pathCost;
PathSegments = pathSegments;
CompletionRatio = completionRatio;
CreatedAtMilliseconds = task.CreatedAt.Ticks / TimeSpan.TicksPerMillisecond;
}
public RobotTask Task { get; }
public RobotSubTask? NextSubTask { get; }
public double PathCost { get; }
public IReadOnlyList<PathSegment> PathSegments { get; }
public double CompletionRatio { get; }
public long CreatedAtMilliseconds { get; }
}
/// <summary>
/// 历史默认排序:先按任务优先级降序,再按路径代价升序、创建时间毫秒值升序与 TaskId 做稳定排序。
/// </summary>
private sealed class TaskCandidateComparer : IComparer<TaskCandidate>
{
public static readonly TaskCandidateComparer Instance = new();
public int Compare(TaskCandidate? x, TaskCandidate? y)
{
if (ReferenceEquals(x, y)) return 0;
if (x is null) return 1;
if (y is null) return -1;
var priorityCompare = y.Task.Priority.CompareTo(x.Task.Priority);
if (priorityCompare != 0)
{
return priorityCompare;
}
var pathCostCompare = x.PathCost.CompareTo(y.PathCost);
if (pathCostCompare != 0)
{
return pathCostCompare;
}
var createdAtCompare = x.CreatedAtMilliseconds.CompareTo(y.CreatedAtMilliseconds);
if (createdAtCompare != 0)
{
return createdAtCompare;
}
return x.Task.TaskId.CompareTo(y.Task.TaskId);
}
}
private sealed class CompositePrimaryComparer : IComparer<TaskCandidate>
{
public static readonly CompositePrimaryComparer Instance = new();
public int Compare(TaskCandidate? x, TaskCandidate? y)
{
if (ReferenceEquals(x, y)) return 0;
if (x is null) return 1;
if (y is null) return -1;
var priorityCompare = y.Task.Priority.CompareTo(x.Task.Priority);
if (priorityCompare != 0)
{
return priorityCompare;
}
var completionCompare = y.CompletionRatio.CompareTo(x.CompletionRatio);
if (completionCompare != 0)
{
return completionCompare;
}
var pathCostCompare = x.PathCost.CompareTo(y.PathCost);
if (pathCostCompare != 0)
{
return pathCostCompare;
}
var createdAtCompare = x.CreatedAtMilliseconds.CompareTo(y.CreatedAtMilliseconds);
if (createdAtCompare != 0)
{
return createdAtCompare;
}
return x.Task.TaskId.CompareTo(y.Task.TaskId);
}
}
private sealed class CompositePrimaryInputComparer : IComparer<ExecutionCandidateInput>
{
public static readonly CompositePrimaryInputComparer Instance = new();
public int Compare(ExecutionCandidateInput x, ExecutionCandidateInput y)
{
var priorityCompare = y.Priority.CompareTo(x.Priority);
if (priorityCompare != 0)
{
return priorityCompare;
}
var completionCompare = y.CompletionRatio.CompareTo(x.CompletionRatio);
if (completionCompare != 0)
{
return completionCompare;
}
var pathCostCompare = x.PathCost.CompareTo(y.PathCost);
if (pathCostCompare != 0)
{
return pathCostCompare;
}
var createdAtCompare = x.CreatedAtMilliseconds.CompareTo(y.CreatedAtMilliseconds);
if (createdAtCompare != 0)
{
return createdAtCompare;
}
return x.TaskId.CompareTo(y.TaskId);
}
}
private sealed record PathCostEvaluation(double PathCost, IReadOnlyList<PathSegment> Segments)
{
public static PathCostEvaluation Invalid { get; } =
new(double.MaxValue, Array.Empty<PathSegment>());
}
internal readonly record struct ExecutionCandidateInput(
Guid TaskId,
int Priority,
double CompletionRatio,
double PathCost,
long CreatedAtMilliseconds,
double NonOverlapDistance);
internal readonly record struct ExecutionCandidateDecision(
Guid SelectedTaskId,
Guid PrimaryTaskId,
CandidateSelectionBucket Bucket);
internal enum CandidateSelectionBucket
{
Primary = 0,
EqualPriorityReplacement = 1,
LowerPriorityReplacement = 2
}
/// <summary>
/// 检查机器人是否有执行中的任务
/// @author zzy
/// </summary>
private async Task<bool> HasInProgressTaskAsync(
Guid robotId,
Guid taskId,
IRobotTaskRepository taskRepo,
CancellationToken cancellationToken)
{
var robotTasks = await taskRepo.GetByRobotIdAsync(robotId, cancellationToken);
return robotTasks.Any(t =>
t.TaskId != taskId &&
t.SubTasks.Any(st => st.Status == TaskStatus.InProgress));
}
/// <summary>
/// 根据协议类型执行任务
/// @author zzy
/// 重构为使用协议工厂模式
/// </summary>
private async Task<bool> ExecuteTaskByProtocolAsync(
RobotTask task,
Robot robot,
IRobotTaskRepository taskRepo,
IServiceScope scope,
CancellationToken cancellationToken)
{
try
{
// 使用同一scope的taskRepo获取带详情的任务,避免跨scope实体跟踪冲突
var taskWithDetails = await taskRepo.GetByIdWithDetailsAsync(task.TaskId, cancellationToken);
if (taskWithDetails == null)
{
_logger.LogWarning("[任务执行] 任务 {TaskCode} 详情获取失败", task.TaskCode);
return false;
}
if (taskWithDetails.RobotId != robot.RobotId)
{
_logger.LogWarning(
"[任务执行] 任务机器人已变更,放弃下发: TaskCode={TaskCode}, ExpectedRobot={ExpectedRobot}, ActualRobot={ActualRobot}",
taskWithDetails.TaskCode,
robot.RobotId,
taskWithDetails.RobotId);
return false;
}
if (taskWithDetails.Status != TaskStatus.Assigned && taskWithDetails.Status != TaskStatus.InProgress)
{
_logger.LogWarning(
"[任务执行] 任务状态已变更,放弃下发: TaskCode={TaskCode}, Status={Status}",
taskWithDetails.TaskCode,
taskWithDetails.Status);
return false;
}
if (taskWithDetails.SubTasks.Count <= 0 && robot.ProtocolType == ProtocolType.VDA)
{
_logger.LogWarning("[任务执行] 任务 {TaskCode} 不存在子任务,执行失败", task.TaskCode);
return false;
}
// 获取协议服务工厂
var protocolServiceFactory = scope.ServiceProvider.GetRequiredService<IProtocolServiceFactory>();
var protocolService = protocolServiceFactory.GetService(robot);
// 执行任务
var res = await protocolService.PrepareSendOrderAsync(robot, taskWithDetails, cancellationToken);
if (res.Success)
{
taskWithDetails.StartExecution();
await taskRepo.UpdateAsync(taskWithDetails, cancellationToken);
await taskRepo.SaveChangesAsync(cancellationToken);
if (IsDeferredProtocolSuccess(res.Message))
{
_logger.LogInformation(
"[任务执行] 任务 {TaskCode} 已进入调度等待,尚未实际下发给机器人 {RobotCode},协议类型: {ProtocolType}, Message={Message}",
taskWithDetails.TaskCode,
robot.RobotCode,
robot.ProtocolType,
res.Message);
}
else
{
_logger.LogInformation(
"[任务执行] 任务 {TaskCode} 已下发给机器人 {RobotCode},协议类型: {ProtocolType}",
taskWithDetails.TaskCode,
robot.RobotCode,
robot.ProtocolType);
}
return true;
}
else
{
throw new Exception(res.Message);
}
}
catch (Exception ex)
{
try
{
var taskForErrorUpdate = await taskRepo.GetByIdAsync(task.TaskId, cancellationToken);
if (taskForErrorUpdate != null)
{
taskForErrorUpdate.ErrorInfo = ex.Message.ToString();
taskForErrorUpdate.UpdatedAt = DateTime.Now;
await taskRepo.UpdateAsync(taskForErrorUpdate, cancellationToken);
await taskRepo.SaveChangesAsync(cancellationToken);
}
}
catch (Exception updateEx)
{
_logger.LogError(updateEx, "[任务执行] 任务 {TaskCode} 错误信息更新失败", task.TaskCode);
}
_logger.LogError(ex, "[任务执行] 任务 {TaskCode} 执行失败", task.TaskCode);
return false;
}
}
private static bool IsDeferredProtocolSuccess(string? message)
{
if (string.IsNullOrWhiteSpace(message))
{
return false;
}
return message.Contains("等待", StringComparison.OrdinalIgnoreCase) ||
message.Contains("冲突", StringComparison.OrdinalIgnoreCase) ||
message.Contains("并发更新", StringComparison.OrdinalIgnoreCase) ||
message.Contains("未到", StringComparison.OrdinalIgnoreCase) ||
message.Contains("失败", StringComparison.OrdinalIgnoreCase);
}
private async Task SetExecutionStartedLatchAsync(Guid taskId, CancellationToken cancellationToken)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
var key = BuildExecutionStartedLatchKey(taskId);
await _redis.GetDatabase().StringSetAsync(
key,
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
ExecutionStartedLatchTtl);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.LogDebug(ex, "[任务执行] 设置执行开始门闩失败: TaskId={TaskId}", taskId);
}
}
private async Task ClearExecutionStartedLatchAsync(Guid taskId, CancellationToken cancellationToken)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
await _redis.GetDatabase().KeyDeleteAsync(BuildExecutionStartedLatchKey(taskId));
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.LogDebug(ex, "[任务执行] 删除执行开始门闩失败: TaskId={TaskId}", taskId);
}
}
private string BuildExecutionStartedLatchKey(Guid taskId)
{
return $"{_settings.Redis.KeyPrefixes.TaskLeasePrefix}:{TaskExecutionStartedLatchKeySuffix}:{taskId}";
}
}
}