UnifiedTrafficControlService.cs
86.2 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
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Rcs.Application.Services;
using Rcs.Application.Services.PathFind.Models;
using Rcs.Domain.Settings;
using StackExchange.Redis;
namespace Rcs.Infrastructure.PathFinding.Services
{
/// <summary>
/// 统一交通管制服务实现 - 基于 Redis 的分布式地图锁管理
/// Key格式: "rcs:lock:node:{MapCode}:{NodeCode}" 或 "rcs:lock:edge:{MapCode}:{EdgeCode}"
/// 支持双向互斥检测:锁定边时自动检查逆向边是否被其他机器人占用
/// @author zzy
/// @date 2026-01-30
/// </summary>
public class UnifiedTrafficControlService : IUnifiedTrafficControlService
{
private readonly ILogger<UnifiedTrafficControlService> _logger;
private readonly IConnectionMultiplexer _redis;
private readonly AppSettings _settings;
private IDatabase RedisDb => _redis.GetDatabase();
// 逆向边映射 Key: "{MapCode}:{EdgeCode}", Value: "{MapCode}:{ReverseEdgeCode}"
// 用于双向互斥检测(保留内存缓存,因为地图结构相对固定)
private readonly Dictionary<string, string> _reverseEdgeMap = new();
// Redis Hash 字段名常量
private const string LockFieldRobotId = "rid";
private const string LockFieldLockedAt = "lat";
private const string LockFieldExpiresAt = "eat";
private const string LockFieldFromNode = "frm";
private const string LockFieldToNode = "to";
private const string LockFieldHasDirection = "dir";
private const string LockFieldBindings = "bindings";
public UnifiedTrafficControlService(
ILogger<UnifiedTrafficControlService> logger,
IConnectionMultiplexer redis,
IOptions<AppSettings> settings)
{
_logger = logger;
_redis = redis;
_settings = settings.Value;
}
#region Key生成
private string BuildNodeKey(string mapCode, string nodeCode) =>
$"{_settings.Redis.KeyPrefixes.NodeLockPrefix}:{mapCode}:{nodeCode}";
private string BuildEdgeKey(string mapCode, string edgeCode) =>
$"{_settings.Redis.KeyPrefixes.EdgeLockPrefix}:{mapCode}:{edgeCode}";
private string BuildRobotNodesKey(Guid robotId) =>
$"{_settings.Redis.KeyPrefixes.RobotLockResourcesPrefix}:{robotId}:{_settings.Redis.KeyPrefixes.RobotLockNodesSuffix}";
private string BuildRobotEdgesKey(Guid robotId) =>
$"{_settings.Redis.KeyPrefixes.RobotLockResourcesPrefix}:{robotId}:{_settings.Redis.KeyPrefixes.RobotLockEdgesSuffix}";
private string BuildRobotBindingsKey(Guid robotId) =>
$"{_settings.Redis.KeyPrefixes.RobotLockResourcesPrefix}:{robotId}:{_settings.Redis.KeyPrefixes.RobotLockBindingsSuffix}";
private string BuildBindingIndexKey(Guid robotId, string bindingId) =>
$"{BuildRobotBindingsKey(robotId)}:{bindingId}";
#endregion
#region 逆向边管理(双向互斥检测)
/// <summary>
/// 注册逆向边关系(用于双向互斥检测)
/// @author zzy
/// </summary>
public void RegisterReverseEdge(string mapCode, string edgeCode, string? reverseEdgeCode)
{
var key = $"{mapCode}:{edgeCode}";
lock (_reverseEdgeMap)
{
if (!string.IsNullOrEmpty(reverseEdgeCode))
{
var reverseKey = $"{mapCode}:{reverseEdgeCode}";
_reverseEdgeMap[key] = reverseKey;
_reverseEdgeMap[reverseKey] = key;
//_logger.LogDebug("注册逆向边关系: {EdgeKey} <-> {ReverseEdgeKey}", key, reverseKey);
}
else
{
_reverseEdgeMap.Remove(key);
}
}
}
/// <summary>
/// 批量注册逆向边关系
/// @author zzy
/// </summary>
public void RegisterReverseEdges(string mapCode, Dictionary<string, string?> edgeReverseMapping)
{
foreach (var (edgeCode, reverseEdgeCode) in edgeReverseMapping)
{
RegisterReverseEdge(mapCode, edgeCode, reverseEdgeCode);
}
_logger.LogInformation("批量注册逆向边关系完成: MapCode={MapCode}, Count={Count}",
mapCode, edgeReverseMapping.Count);
}
/// <summary>
/// 清除指定地图的逆向边关系缓存
/// @author zzy
/// </summary>
public void ClearReverseEdgeCache(string mapCode)
{
lock (_reverseEdgeMap)
{
var keysToRemove = _reverseEdgeMap.Keys.Where(k => k.StartsWith($"{mapCode}:")).ToList();
foreach (var key in keysToRemove)
{
_reverseEdgeMap.Remove(key);
}
_logger.LogInformation("已清除地图 {MapCode} 的逆向边缓存,共 {Count} 条", mapCode, keysToRemove.Count);
}
}
private string? GetReverseEdgeKey(string mapCode, string edgeCode)
{
var key = $"{mapCode}:{edgeCode}";
lock (_reverseEdgeMap)
{
return _reverseEdgeMap.TryGetValue(key, out var reverseKey) ? reverseKey : null;
}
}
private string? ExtractEdgeCodeFromReverseKey(string mapCode, string reverseKey)
{
var prefix = $"{mapCode}:";
if (reverseKey.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return reverseKey.Substring(prefix.Length);
}
var separatorIndex = reverseKey.LastIndexOf(':');
if (separatorIndex >= 0 && separatorIndex < reverseKey.Length - 1)
{
return reverseKey.Substring(separatorIndex + 1);
}
return reverseKey;
}
private string? ResolveReverseEdgeCode(
string mapCode,
string edgeCode,
string? fromNodeCode = null,
string? toNodeCode = null)
{
var reverseKeyInfo = GetReverseEdgeKey(mapCode, edgeCode);
if (!string.IsNullOrEmpty(reverseKeyInfo))
{
var reverseEdgeCodeFromMap = ExtractEdgeCodeFromReverseKey(mapCode, reverseKeyInfo);
if (!string.IsNullOrEmpty(reverseEdgeCodeFromMap))
{
return reverseEdgeCodeFromMap;
}
}
if (!string.IsNullOrEmpty(fromNodeCode) && !string.IsNullOrEmpty(toNodeCode))
{
return $"{toNodeCode}-{fromNodeCode}";
}
return null;
}
/// <summary>
/// 检查逆向边是否被其他机器人锁定
/// @author zzy
/// </summary>
/// <param name="mapCode">地图编码</param>
/// <param name="edgeCode">边编码</param>
/// <param name="robotId">机器人ID</param>
/// <param name="fromNodeCode">起点节点编码(可选,用于构建逆向边编码)</param>
/// <param name="toNodeCode">终点节点编码(可选,用于构建逆向边编码)</param>
private async Task<(bool hasConflict, Guid? conflictingRobotId)> CheckReverseEdgeConflictAsync(
string mapCode, string edgeCode, Guid robotId,
string? fromNodeCode = null, string? toNodeCode = null)
{
var reverseEdgeCode = ResolveReverseEdgeCode(mapCode, edgeCode, fromNodeCode, toNodeCode);
if (string.IsNullOrEmpty(reverseEdgeCode))
{
return (false, null);
}
var reverseEdgeLockKey = BuildEdgeKey(mapCode, reverseEdgeCode);
var lockInfo = await GetLockInfoAsync(reverseEdgeLockKey);
if (lockInfo != null)
{
var now = DateTime.Now;
if (lockInfo.RobotId != robotId && lockInfo.ExpiresAt > now)
{
// _logger.LogDebug("双向互斥冲突: Edge={EdgeCode}, ReverseEdge={ReverseEdge}, HeldBy={HeldBy}",
// edgeCode, reverseEdgeCode, lockInfo.RobotId);
return (true, lockInfo.RobotId);
}
}
return (false, null);
}
/// <summary>
/// 从合并映射初始化逆向边关系
/// @author zzy
/// </summary>
public Task InitializeFromMergedMappingsAsync(Dictionary<string, MergedMapTopology> mergedTopologies)
{
if (mergedTopologies == null || mergedTopologies.Count == 0)
{
_logger.LogWarning("合并拓扑为空,跳过逆向边初始化");
return Task.CompletedTask;
}
var totalCount = 0;
foreach (var (mapCode, topology) in mergedTopologies)
{
ClearReverseEdgeCache(mapCode);
if (topology.ReverseEdgeMap != null && topology.ReverseEdgeMap.Count > 0)
{
RegisterReverseEdges(mapCode, topology.ReverseEdgeMap);
totalCount += topology.ReverseEdgeMap.Count;
}
}
_logger.LogInformation("从合并映射初始化逆向边关系完成: MapCode数={MapCodeCount}, 逆向边总数={TotalCount}",
mergedTopologies.Count, totalCount);
return Task.CompletedTask;
}
/// <summary>
/// 刷新指定MapCode的逆向边关系
/// @author zzy
/// </summary>
public Task RefreshReverseEdgesAsync(string mapCode, MergedMapTopology mergedTopology)
{
if (string.IsNullOrEmpty(mapCode) || mergedTopology == null)
{
return Task.CompletedTask;
}
ClearReverseEdgeCache(mapCode);
if (mergedTopology.ReverseEdgeMap != null && mergedTopology.ReverseEdgeMap.Count > 0)
{
RegisterReverseEdges(mapCode, mergedTopology.ReverseEdgeMap);
_logger.LogInformation("刷新逆向边关系完成: MapCode={MapCode}, Count={Count}",
mapCode, mergedTopology.ReverseEdgeMap.Count);
}
return Task.CompletedTask;
}
#endregion
#region 基于Redis的锁操作
/// <summary>
/// 设置锁信息到Redis(使用事务保证原子性)
/// </summary>
private async Task<bool> SetLockInfoAsync(string lockKey, LockInfo lockInfo, int ttlSeconds)
{
var hashEntries = new HashEntry[]
{
new(LockFieldRobotId, lockInfo.RobotId.ToString()),
new(LockFieldLockedAt, lockInfo.LockedAt.Ticks),
new(LockFieldExpiresAt, lockInfo.ExpiresAt.Ticks)
};
await RedisDb.HashSetAsync(lockKey, hashEntries);
await RedisDb.KeyExpireAsync(lockKey, TimeSpan.FromSeconds(ttlSeconds));
return true;
}
/// <summary>
/// 尝试锁定节点
/// @author zzy
/// </summary>
public async Task<bool> TryAcquireNodeLockAsync(string mapCode, string nodeCode, Guid robotId, int ttlSeconds = 30)
{
var key = BuildNodeKey(mapCode, nodeCode);
return await TryAcquireLockAsync(key, robotId, ttlSeconds, LockResourceType.Node);
}
/// <summary>
/// 尝试锁定边(包含双向互斥检测)
/// @author zzy
/// </summary>
public async Task<bool> TryAcquireEdgeLockAsync(string mapCode, string edgeCode, Guid robotId, int ttlSeconds = 30)
{
var (hasConflict, conflictingRobotId) = await CheckReverseEdgeConflictAsync(mapCode, edgeCode, robotId);
if (hasConflict)
{
// _logger.LogDebug("边锁定失败(双向互斥): EdgeCode={EdgeCode}, MapCode={MapCode}, ConflictingRobot={ConflictingRobot}",
// edgeCode, mapCode, conflictingRobotId);
return false;
}
var key = BuildEdgeKey(mapCode, edgeCode);
return await TryAcquireLockAsync(key, robotId, ttlSeconds, LockResourceType.Edge);
}
/// <summary>
/// 尝试锁定边(带方向信息,用于区分同向/逆向冲突)
/// @author zzy
/// </summary>
public async Task<bool> TryAcquireEdgeLockWithDirectionAsync(
string mapCode, string edgeCode, Guid robotId,
string fromNodeCode, string toNodeCode, int ttlSeconds = 30)
{
var (hasConflict, conflictingRobotId) = await CheckReverseEdgeConflictAsync(mapCode, edgeCode, robotId, fromNodeCode, toNodeCode);
if (hasConflict)
{
// _logger.LogDebug("边锁定失败(双向互斥): EdgeCode={EdgeCode}, MapCode={MapCode}, ConflictingRobot={ConflictingRobot}",
// edgeCode, mapCode, conflictingRobotId);
return false;
}
var key = BuildEdgeKey(mapCode, edgeCode);
return await TryAcquireEdgeLockWithDirectionAsync(key, robotId, fromNodeCode, toNodeCode, ttlSeconds);
}
/// <summary>
/// 带方向信息的边锁获取
/// @author zzy
/// </summary>
private async Task<bool> TryAcquireEdgeLockWithDirectionAsync(
string key, Guid robotId,
string fromNodeCode, string toNodeCode, int ttlSeconds)
{
var now = DateTime.Now;
var expiresAt = now.AddSeconds(ttlSeconds);
// 使用 Lua 脚本保证原子性,包含方向信息
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local lockedAt = ARGV[2]
local expiresAt = ARGV[3]
local ttl = ARGV[4]
local fromNode = ARGV[5]
local toNode = ARGV[6]
local current = redis.call('HGET', key, 'rid')
if current == false then
-- 锁不存在,创建新锁
redis.call('HMSET', key, 'rid', robotId, 'lat', lockedAt, 'eat', expiresAt, 'frm', fromNode, 'to', toNode, 'dir', '1')
redis.call('EXPIRE', key, ttl)
return 1
elseif current == robotId then
-- 同一机器人,续期并更新方向
redis.call('HMSET', key, 'eat', expiresAt, 'frm', fromNode, 'to', toNode, 'dir', '1')
redis.call('EXPIRE', key, ttl)
return 1
else
-- 检查是否过期
local currentExpires = redis.call('HGET', key, 'eat')
if currentExpires == false or tonumber(currentExpires) < tonumber(lockedAt) then
redis.call('HMSET', key, 'rid', robotId, 'lat', lockedAt, 'eat', expiresAt, 'frm', fromNode, 'to', toNode, 'dir', '1')
redis.call('EXPIRE', key, ttl)
return 1
else
return 0
end
end
";
var result = (int)await RedisDb.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { key },
new RedisValue[]
{
robotId.ToString(),
now.Ticks.ToString(),
expiresAt.Ticks.ToString(),
ttlSeconds.ToString(),
fromNodeCode ?? "",
toNodeCode ?? ""
});
var success = result == 1;
if (success)
{
// 记录机器人锁定的资源
var setKey = BuildRobotEdgesKey(robotId);
await RedisDb.SetAddAsync(setKey, key);
await RedisDb.KeyExpireAsync(setKey, TimeSpan.FromSeconds(ttlSeconds * 10));
// _logger.LogDebug("边锁定成功(带方向): Key={Key}, RobotId={RobotId}, Direction={From}->{To}",
// key, robotId, fromNodeCode, toNodeCode);
}
else
{
var holder = await GetLockHolderAsync(key);
// _logger.LogDebug("边锁定失败: Key={Key}, RobotId={RobotId}, HeldBy={HeldBy}",
// key, robotId, holder);
}
return success;
}
/// <summary>
/// 通用锁获取逻辑(Redis实现)
/// </summary>
private async Task<bool> TryAcquireLockAsync(string key, Guid robotId, int ttlSeconds, LockResourceType resourceType)
{
var now = DateTime.Now;
var expiresAt = now.AddSeconds(ttlSeconds);
// 使用 Lua 脚本保证原子性
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local lockedAt = ARGV[2]
local expiresAt = ARGV[3]
local ttl = ARGV[4]
local current = redis.call('HGET', key, 'rid')
if current == false then
-- 锁不存在,创建新锁
redis.call('HMSET', key, 'rid', robotId, 'lat', lockedAt, 'eat', expiresAt)
redis.call('EXPIRE', key, ttl)
return 1
elseif current == robotId then
-- 同一机器人,续期
redis.call('HMSET', key, 'eat', expiresAt)
redis.call('EXPIRE', key, ttl)
return 1
else
-- 检查是否过期
local currentExpires = redis.call('HGET', key, 'eat')
if currentExpires == false or tonumber(currentExpires) < tonumber(lockedAt) then
redis.call('HMSET', key, 'rid', robotId, 'lat', lockedAt, 'eat', expiresAt)
redis.call('EXPIRE', key, ttl)
return 1
else
return 0
end
end
";
var result = (int)await RedisDb.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { key },
new RedisValue[]
{
robotId.ToString(),
now.Ticks.ToString(),
expiresAt.Ticks.ToString(),
ttlSeconds.ToString()
});
var success = result == 1;
if (success)
{
// 记录机器人锁定的资源
var setKey = resourceType == LockResourceType.Node
? BuildRobotNodesKey(robotId)
: BuildRobotEdgesKey(robotId);
await RedisDb.SetAddAsync(setKey, key);
await RedisDb.KeyExpireAsync(setKey, TimeSpan.FromSeconds(ttlSeconds * 10)); // 资源索引TTL更长
// _logger.LogDebug("锁定成功: Key={Key}, RobotId={RobotId}", key, robotId);
}
else
{
var holder = await GetLockHolderAsync(key);
// _logger.LogDebug("锁定失败: Key={Key}, RobotId={RobotId}, HeldBy={HeldBy}",
// key, robotId, holder);
}
return success;
}
private async Task<BindingAcquireResult> TryAcquireBindingNodeLockAsync(
string mapCode,
string nodeCode,
Guid robotId,
string bindingId,
int ttlSeconds)
{
var key = BuildNodeKey(mapCode, nodeCode);
var acquireResult = await TryAcquireBindingLockAsync(
key,
robotId,
bindingId,
ttlSeconds,
LockResourceType.Node);
if (!acquireResult.Success && !acquireResult.InvalidLegacyFormat)
{
acquireResult.ConflictingRobotId = await GetNodeLockHolderAsync(mapCode, nodeCode);
acquireResult.FailureReason ??= $"节点锁定失败: {nodeCode}";
}
return acquireResult;
}
private async Task<BindingAcquireResult> TryAcquireBindingEdgeLockAsync(
string mapCode,
VdaLockCoveredEdge coveredEdge,
Guid robotId,
string bindingId,
int ttlSeconds)
{
var reverseConflict = await CheckReverseEdgeConflictAsync(
mapCode,
coveredEdge.EdgeCode,
robotId,
coveredEdge.FromNodeCode,
coveredEdge.ToNodeCode);
if (reverseConflict.hasConflict)
{
return new BindingAcquireResult
{
Success = false,
HasReverseConflict = true,
FailureReason = $"边锁定失败(双向互斥): {coveredEdge.EdgeCode}",
ConflictingRobotId = reverseConflict.conflictingRobotId
};
}
var key = BuildEdgeKey(mapCode, coveredEdge.EdgeCode);
var acquireResult = await TryAcquireBindingLockAsync(
key,
robotId,
bindingId,
ttlSeconds,
LockResourceType.Edge,
coveredEdge.FromNodeCode,
coveredEdge.ToNodeCode);
if (!acquireResult.Success && !acquireResult.InvalidLegacyFormat)
{
acquireResult.ConflictingRobotId = await GetEdgeLockHolderAsync(mapCode, coveredEdge.EdgeCode);
acquireResult.FailureReason ??= $"边锁定失败: {coveredEdge.EdgeCode}";
}
return acquireResult;
}
private async Task<BindingAcquireResult> TryAcquireBindingLockAsync(
string key,
Guid robotId,
string bindingId,
int ttlSeconds,
LockResourceType resourceType,
string? fromNodeCode = null,
string? toNodeCode = null)
{
var now = DateTime.Now;
var expiresAt = now.AddSeconds(ttlSeconds);
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local lockedAt = ARGV[2]
local expiresAt = ARGV[3]
local ttl = ARGV[4]
local bindingId = ARGV[5]
local fromNode = ARGV[6]
local toNode = ARGV[7]
local hasDirection = ARGV[8]
local current = redis.call('HGET', key, 'rid')
local function buildBindings()
return cjson.encode({ bindingId })
end
if current == false then
redis.call('HMSET', key, 'rid', robotId, 'lat', lockedAt, 'eat', expiresAt, 'bindings', buildBindings(), 'frm', fromNode, 'to', toNode, 'dir', hasDirection)
redis.call('EXPIRE', key, ttl)
return 1
end
local currentBindingsRaw = redis.call('HGET', key, 'bindings')
if currentBindingsRaw == false then
return -2
end
local currentExpires = redis.call('HGET', key, 'eat')
if current ~= robotId then
if currentExpires == false or tonumber(currentExpires) < tonumber(lockedAt) then
redis.call('HMSET', key, 'rid', robotId, 'lat', lockedAt, 'eat', expiresAt, 'bindings', buildBindings(), 'frm', fromNode, 'to', toNode, 'dir', hasDirection)
redis.call('EXPIRE', key, ttl)
return 1
end
return 0
end
local bindings = cjson.decode(currentBindingsRaw)
local exists = false
for _, existing in ipairs(bindings) do
if existing == bindingId then
exists = true
break
end
end
if not exists then
table.insert(bindings, bindingId)
end
redis.call('HMSET', key, 'eat', expiresAt, 'bindings', cjson.encode(bindings), 'frm', fromNode, 'to', toNode, 'dir', hasDirection)
redis.call('EXPIRE', key, ttl)
if exists then
return 2
end
return 1
";
var scriptResult = (int)await RedisDb.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { key },
new RedisValue[]
{
robotId.ToString(),
now.Ticks.ToString(),
expiresAt.Ticks.ToString(),
ttlSeconds.ToString(),
bindingId,
fromNodeCode ?? string.Empty,
toNodeCode ?? string.Empty,
resourceType == LockResourceType.Edge ? "1" : "0"
});
if (scriptResult == -2)
{
return new BindingAcquireResult
{
Success = false,
InvalidLegacyFormat = true,
FailureReason = $"发现旧格式锁数据,无法按严格 binding 模式继续: {key}"
};
}
if (scriptResult is 1 or 2)
{
var resourceSetKey = resourceType == LockResourceType.Node
? BuildRobotNodesKey(robotId)
: BuildRobotEdgesKey(robotId);
await RedisDb.SetAddAsync(resourceSetKey, key);
await RedisDb.KeyExpireAsync(resourceSetKey, TimeSpan.FromSeconds(ttlSeconds * 10));
return new BindingAcquireResult { Success = true };
}
return new BindingAcquireResult { Success = false };
}
private async Task SaveBindingIndexAsync(
string mapCode,
Guid robotId,
string bindingId,
IEnumerable<string> nodeCodes,
IEnumerable<VdaLockCoveredEdge> coveredEdges,
int ttlSeconds)
{
var bindingIndexKey = BuildBindingIndexKey(robotId, bindingId);
var robotBindingsKey = BuildRobotBindingsKey(robotId);
var resourceKeys = nodeCodes
.Where(code => !string.IsNullOrWhiteSpace(code))
.Select(code => BuildNodeKey(mapCode, code))
.Concat(coveredEdges
.Where(edge => !string.IsNullOrWhiteSpace(edge.EdgeCode))
.Select(edge => BuildEdgeKey(mapCode, edge.EdgeCode)))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Select(key => (RedisValue)key)
.ToArray();
if (resourceKeys.Length > 0)
{
await RedisDb.SetAddAsync(bindingIndexKey, resourceKeys);
}
await RedisDb.KeyExpireAsync(bindingIndexKey, TimeSpan.FromSeconds(ttlSeconds));
await RedisDb.SetAddAsync(robotBindingsKey, bindingIndexKey);
await RedisDb.KeyExpireAsync(robotBindingsKey, TimeSpan.FromSeconds(ttlSeconds * 10));
}
private async Task<List<string>> GetBindingResourceKeysStrictAsync(
Guid robotId,
string bindingId,
bool allowAlreadyReleased)
{
var bindingIndexKey = BuildBindingIndexKey(robotId, bindingId);
var resourceKeys = (await RedisDb.SetMembersAsync(bindingIndexKey))
.Select(member => member.ToString())
.Where(key => !string.IsNullOrWhiteSpace(key))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
if (resourceKeys.Count > 0)
{
return resourceKeys;
}
if (allowAlreadyReleased)
{
if (await HasActiveBindingResourceAsync(robotId, bindingId))
{
throw new InvalidOperationException(
$"严格 binding 反向索引缺失,但资源锁仍携带该 BindingId,无法继续释放: {bindingIndexKey}");
}
return new List<string>();
}
throw new InvalidOperationException(
$"严格 binding 反向索引缺失或为空,无法继续: {bindingIndexKey}");
}
private async Task<bool> HasActiveBindingResourceAsync(Guid robotId, string bindingId)
{
var (nodeKeys, edgeKeys) = await GetRobotLockedResourcesAsync(robotId);
foreach (var resourceKey in nodeKeys
.Concat(edgeKeys)
.Where(key => !string.IsNullOrWhiteSpace(key))
.Distinct(StringComparer.OrdinalIgnoreCase))
{
var lockInfo = await GetLockInfoAsync(resourceKey);
if (lockInfo?.BindingIds.Contains(bindingId, StringComparer.OrdinalIgnoreCase) == true)
{
return true;
}
}
return false;
}
private async Task ValidateBindingResourcesAsync(
Guid robotId,
string bindingId,
IReadOnlyCollection<string> resourceKeys)
{
var now = DateTime.Now;
foreach (var resourceKey in resourceKeys)
{
var lockInfo = await GetLockInfoAsync(resourceKey);
if (lockInfo == null)
{
throw new InvalidOperationException(
$"严格 binding 资源锁缺失,无法继续: BindingId={bindingId}, ResourceKey={resourceKey}");
}
if (lockInfo.RobotId != robotId)
{
throw new InvalidOperationException(
$"严格 binding 资源锁持有者不匹配,无法继续: BindingId={bindingId}, ResourceKey={resourceKey}, ExpectedRobotId={robotId}, ActualRobotId={lockInfo.RobotId}");
}
if (lockInfo.ExpiresAt <= now)
{
throw new InvalidOperationException(
$"严格 binding 资源锁已过期,无法继续: BindingId={bindingId}, ResourceKey={resourceKey}");
}
if (lockInfo.BindingIds.Count == 0)
{
throw new InvalidOperationException(
$"发现旧格式或损坏的锁数据,无法按严格 binding 模式继续: BindingId={bindingId}, ResourceKey={resourceKey}");
}
if (!lockInfo.BindingIds.Contains(bindingId, StringComparer.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
$"严格 binding 资源锁未绑定指定 BindingId,无法继续: BindingId={bindingId}, ResourceKey={resourceKey}");
}
}
}
private async Task RenewBindingResourcesAsync(
Guid robotId,
string bindingId,
IReadOnlyCollection<string> resourceKeys,
int ttlSeconds)
{
if (resourceKeys.Count == 0)
{
return;
}
var expiresAt = DateTime.Now.AddSeconds(ttlSeconds);
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local newExpiresAt = ARGV[2]
local ttl = ARGV[3]
local bindingId = ARGV[4]
local current = redis.call('HGET', key, 'rid')
if current == false then
return -2
end
if current ~= robotId then
return 0
end
local rawBindings = redis.call('HGET', key, 'bindings')
if rawBindings == false then
return -1
end
local bindings = cjson.decode(rawBindings)
local exists = false
for _, existing in ipairs(bindings) do
if existing == bindingId then
exists = true
break
end
end
if not exists then
return -3
end
redis.call('HSET', key, 'eat', newExpiresAt)
redis.call('EXPIRE', key, ttl)
return 1
";
foreach (var resourceKey in resourceKeys)
{
var renewResult = (int)await RedisDb.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { resourceKey },
new RedisValue[]
{
robotId.ToString(),
expiresAt.Ticks.ToString(),
ttlSeconds.ToString(),
bindingId
});
if (renewResult != 1)
{
throw new InvalidOperationException(
$"严格 binding 资源锁续期失败,无法继续: BindingId={bindingId}, ResourceKey={resourceKey}, Result={renewResult}");
}
}
}
private async Task ReleaseBindingResourcesDirectAsync(
string mapCode,
Guid robotId,
string bindingId,
IEnumerable<string> nodeCodes,
IEnumerable<string> edgeCodes)
{
foreach (var nodeCode in nodeCodes
.Where(code => !string.IsNullOrWhiteSpace(code))
.Distinct(StringComparer.OrdinalIgnoreCase))
{
var key = BuildNodeKey(mapCode, nodeCode);
var releaseResult = await ReleaseBindingFromResourceKeyAsync(key, robotId, bindingId);
if (releaseResult == BindingReleaseResult.ResourceDeleted)
{
await RedisDb.SetRemoveAsync(BuildRobotNodesKey(robotId), key);
}
}
foreach (var edgeCode in edgeCodes
.Where(code => !string.IsNullOrWhiteSpace(code))
.Distinct(StringComparer.OrdinalIgnoreCase))
{
var key = BuildEdgeKey(mapCode, edgeCode);
var releaseResult = await ReleaseBindingFromResourceKeyAsync(key, robotId, bindingId);
if (releaseResult == BindingReleaseResult.ResourceDeleted)
{
await RedisDb.SetRemoveAsync(BuildRobotEdgesKey(robotId), key);
}
}
}
private async Task<BindingReleaseResult> ReleaseBindingFromResourceKeyAsync(
string key,
Guid robotId,
string bindingId)
{
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local bindingId = ARGV[2]
local current = redis.call('HGET', key, 'rid')
if current == false then
return 0
end
if current ~= robotId then
return 0
end
local rawBindings = redis.call('HGET', key, 'bindings')
if rawBindings == false then
return -1
end
local bindings = cjson.decode(rawBindings)
local updated = {}
local removed = false
for _, existing in ipairs(bindings) do
if existing == bindingId then
removed = true
else
table.insert(updated, existing)
end
end
if not removed then
return 0
end
if #updated == 0 then
redis.call('DEL', key)
return 2
end
redis.call('HSET', key, 'bindings', cjson.encode(updated))
return 1
";
var scriptResult = (int)await RedisDb.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { key },
new RedisValue[] { robotId.ToString(), bindingId });
return scriptResult switch
{
2 => BindingReleaseResult.ResourceDeleted,
1 => BindingReleaseResult.BindingRemoved,
-1 => BindingReleaseResult.InvalidLegacyFormat,
_ => BindingReleaseResult.NoChange
};
}
private BindingLockRequestResult NormalizeBindingLockResult(BindingLockRequestResult result)
{
result.LockedBindingIds = result.LockedBindingIds
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
result.LockedNodeCodes = result.LockedNodeCodes
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
result.LockedEdgeCodes = result.LockedEdgeCodes
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
result.ConflictingRobotIds = result.ConflictingRobotIds
.Distinct()
.ToList();
return result;
}
/// <summary>
/// 释放节点锁
/// @author zzy
/// </summary>
public async Task<bool> ReleaseNodeLockAsync(string mapCode, string nodeCode, Guid robotId)
{
var key = BuildNodeKey(mapCode, nodeCode);
return await ReleaseLockAsync(key, robotId, LockResourceType.Node);
}
/// <summary>
/// 释放边锁
/// @author zzy
/// </summary>
public async Task<bool> ReleaseEdgeLockAsync(string mapCode, string edgeCode, Guid robotId)
{
var key = BuildEdgeKey(mapCode, edgeCode);
return await ReleaseLockAsync(key, robotId, LockResourceType.Edge);
}
/// <summary>
/// 通用锁释放逻辑(Redis实现)
/// </summary>
private async Task<bool> ReleaseLockAsync(string key, Guid robotId, LockResourceType resourceType)
{
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local current = redis.call('HGET', key, 'rid')
if current == robotId then
redis.call('DEL', key)
return 1
else
return 0
end
";
var result = (int)await RedisDb.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { key },
new RedisValue[] { robotId.ToString() });
if (result == 1)
{
// 从机器人资源集合中移除
var setKey = resourceType == LockResourceType.Node
? BuildRobotNodesKey(robotId)
: BuildRobotEdgesKey(robotId);
await RedisDb.SetRemoveAsync(setKey, key);
// _logger.LogDebug("释放锁成功: Key={Key}, RobotId={RobotId}", key, robotId);
return true;
}
return false;
}
/// <summary>
/// 批量锁定路径
/// @author zzy
/// </summary>
public async Task<LockRequestResult> TryAcquirePathLocksAsync(
string mapCode,
IEnumerable<string> nodeCodes,
IEnumerable<string> edgeCodes,
Guid robotId,
int ttlSeconds = 30)
{
var result = new LockRequestResult { Success = true };
var nodeList = nodeCodes.ToList();
var edgeList = edgeCodes.ToList();
var lockedNodeKeys = new List<string>();
var lockedEdgeKeys = new List<string>();
try
{
// 尝试锁定所有节点
foreach (var nodeCode in nodeList)
{
var key = BuildNodeKey(mapCode, nodeCode);
var locked = await TryAcquireNodeLockAsync(mapCode, nodeCode, robotId, ttlSeconds);
if (locked)
{
lockedNodeKeys.Add(key);
result.LockedNodeCodes.Add(nodeCode);
}
else
{
result.Success = false;
result.ConflictingNodeCodes.Add(nodeCode);
var holder = await GetNodeLockHolderAsync(mapCode, nodeCode);
if (holder.HasValue && !result.ConflictingRobotIds.Contains(holder.Value))
{
result.ConflictingRobotIds.Add(holder.Value);
}
result.FailureReason = $"节点锁定失败: {mapCode}:{nodeCode}";
break;
}
}
// 如果节点锁定成功,继续锁定边
if (result.Success)
{
foreach (var edgeCode in edgeList)
{
var key = BuildEdgeKey(mapCode, edgeCode);
var locked = await TryAcquireEdgeLockAsync(mapCode, edgeCode, robotId, ttlSeconds);
if (locked)
{
lockedEdgeKeys.Add(key);
result.LockedEdgeCodes.Add(edgeCode);
}
else
{
result.Success = false;
result.ConflictingEdgeCodes.Add(edgeCode);
var holder = await GetEdgeLockHolderAsync(mapCode, edgeCode);
if (holder.HasValue && !result.ConflictingRobotIds.Contains(holder.Value))
{
result.ConflictingRobotIds.Add(holder.Value);
result.FailureReason = $"边锁定失败(直接占用): {mapCode}:{edgeCode}";
}
else
{
var (hasReverseConflict, reverseHolder) = await CheckReverseEdgeConflictAsync(mapCode, edgeCode, robotId);
if (hasReverseConflict && reverseHolder.HasValue && !result.ConflictingRobotIds.Contains(reverseHolder.Value))
{
result.ConflictingRobotIds.Add(reverseHolder.Value);
}
result.FailureReason = $"边锁定失败(双向互斥): {mapCode}:{edgeCode}";
}
break;
}
}
}
// 如果失败,回滚所有已锁定的资源
if (!result.Success)
{
foreach (var nodeCode in result.LockedNodeCodes.ToList())
{
await ReleaseNodeLockAsync(mapCode, nodeCode, robotId);
}
foreach (var edgeCode in result.LockedEdgeCodes.ToList())
{
await ReleaseEdgeLockAsync(mapCode, edgeCode, robotId);
}
result.LockedNodeCodes.Clear();
result.LockedEdgeCodes.Clear();
_logger.LogWarning("批量锁定失败并回滚: RobotId={RobotId}, MapCode={MapCode}, Reason={Reason}",
robotId, mapCode, result.FailureReason);
}
else
{
// _logger.LogDebug("批量锁定成功: RobotId={RobotId}, MapCode={MapCode}, Nodes={NodeCount}, Edges={EdgeCount}",
// robotId, mapCode, result.LockedNodeCodes.Count, result.LockedEdgeCodes.Count);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "批量锁定异常: RobotId={RobotId}, MapCode={MapCode}", robotId, mapCode);
foreach (var nodeCode in result.LockedNodeCodes)
{
await ReleaseNodeLockAsync(mapCode, nodeCode, robotId);
}
foreach (var edgeCode in result.LockedEdgeCodes)
{
await ReleaseEdgeLockAsync(mapCode, edgeCode, robotId);
}
result.Success = false;
result.FailureReason = $"锁定异常: {ex.Message}";
result.LockedNodeCodes.Clear();
result.LockedEdgeCodes.Clear();
}
return result;
}
/// <summary>
/// 批量释放路径锁
/// @author zzy
/// </summary>
public async Task<int> ReleasePathLocksAsync(
string mapCode,
IEnumerable<string> nodeCodes,
IEnumerable<string> edgeCodes,
Guid robotId)
{
var releasedCount = 0;
foreach (var nodeCode in nodeCodes)
{
if (await ReleaseNodeLockAsync(mapCode, nodeCode, robotId))
{
releasedCount++;
}
}
foreach (var edgeCode in edgeCodes)
{
if (await ReleaseEdgeLockAsync(mapCode, edgeCode, robotId))
{
releasedCount++;
}
}
// _logger.LogDebug("批量释放锁: RobotId={RobotId}, MapCode={MapCode}, ReleasedCount={Count}",
// robotId, mapCode, releasedCount);
return releasedCount;
}
#endregion
#region 锁状态查询
/// <summary>
/// 检查节点是否被锁定
/// @author zzy
/// </summary>
public async Task<LockStatusInfo> GetNodeLockStatusAsync(string mapCode, string nodeCode)
{
var key = BuildNodeKey(mapCode, nodeCode);
return await GetLockStatusAsync(key, nodeCode, LockResourceType.Node);
}
/// <summary>
/// 检查边是否被锁定
/// @author zzy
/// </summary>
public async Task<LockStatusInfo> GetEdgeLockStatusAsync(string mapCode, string edgeCode)
{
var key = BuildEdgeKey(mapCode, edgeCode);
return await GetLockStatusAsync(key, edgeCode, LockResourceType.Edge);
}
/// <summary>
/// 通用锁状态查询(Redis实现)
/// </summary>
private async Task<LockStatusInfo> GetLockStatusAsync(string key, string code, LockResourceType resourceType)
{
var status = new LockStatusInfo
{
ResourceKey = key,
ResourceCode = code,
ResourceType = resourceType,
IsLocked = false
};
var lockInfo = await GetLockInfoAsync(key);
if (lockInfo != null)
{
var now = DateTime.Now;
if (lockInfo.ExpiresAt > now)
{
status.IsLocked = true;
status.LockedByRobotId = lockInfo.RobotId;
status.LockedAt = lockInfo.LockedAt;
status.ExpiresAt = lockInfo.ExpiresAt;
}
else
{
// 清理过期锁
await RedisDb.KeyDeleteAsync(key);
}
}
return status;
}
/// <summary>
/// 获取节点锁持有者
/// @author zzy
/// </summary>
public async Task<Guid?> GetNodeLockHolderAsync(string mapCode, string nodeCode)
{
var key = BuildNodeKey(mapCode, nodeCode);
return await GetLockHolderAsync(key);
}
/// <summary>
/// 获取边锁持有者
/// @author zzy
/// </summary>
public async Task<Guid?> GetEdgeLockHolderAsync(string mapCode, string edgeCode)
{
var key = BuildEdgeKey(mapCode, edgeCode);
return await GetLockHolderAsync(key);
}
/// <summary>
/// 通用获取锁持有者
/// </summary>
private async Task<Guid?> GetLockHolderAsync(string key)
{
var lockInfo = await GetLockInfoAsync(key);
if (lockInfo != null && lockInfo.ExpiresAt > DateTime.Now)
{
return lockInfo.RobotId;
}
return null;
}
/// <summary>
/// 获取机器人当前锁定的所有资源
/// @author zzy
/// </summary>
public async Task<(List<string> NodeKeys, List<string> EdgeKeys)> GetRobotLockedResourcesAsync(Guid robotId)
{
var nodesKey = BuildRobotNodesKey(robotId);
var edgesKey = BuildRobotEdgesKey(robotId);
var nodeKeys = await RedisDb.SetMembersAsync(nodesKey);
var edgeKeys = await RedisDb.SetMembersAsync(edgesKey);
return (
nodeKeys.Select(k => k.ToString()).ToList(),
edgeKeys.Select(k => k.ToString()).ToList()
);
}
#endregion
#region 全局锁管理
/// <summary>
/// 释放机器人的所有锁
/// @author zzy
/// </summary>
public async Task<int> ReleaseAllRobotLocksAsync(Guid robotId)
{
var releasedCount = 0;
var (nodeKeys, edgeKeys) = await GetRobotLockedResourcesAsync(robotId);
var bindingsSetKey = BuildRobotBindingsKey(robotId);
var nodesSetKey = BuildRobotNodesKey(robotId);
var edgesSetKey = BuildRobotEdgesKey(robotId);
foreach (var key in nodeKeys)
{
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local current = redis.call('HGET', key, 'rid')
if current == robotId then
redis.call('DEL', key)
return 1
end
return 0
";
var result = (int)await RedisDb.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { key },
new RedisValue[] { robotId.ToString() });
if (result == 1)
{
releasedCount++;
await RedisDb.SetRemoveAsync(nodesSetKey, key);
}
}
foreach (var key in edgeKeys)
{
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local current = redis.call('HGET', key, 'rid')
if current == robotId then
redis.call('DEL', key)
return 1
end
return 0
";
var result = (int)await RedisDb.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { key },
new RedisValue[] { robotId.ToString() });
if (result == 1)
{
releasedCount++;
await RedisDb.SetRemoveAsync(edgesSetKey, key);
}
}
// 清理空的资源索引,保留仍持有(例如当前节点锁)的索引数据
if (await RedisDb.SetLengthAsync(nodesSetKey) == 0)
{
await RedisDb.KeyDeleteAsync(nodesSetKey);
}
if (await RedisDb.SetLengthAsync(edgesSetKey) == 0)
{
await RedisDb.KeyDeleteAsync(edgesSetKey);
}
var bindingKeys = await RedisDb.SetMembersAsync(bindingsSetKey);
if (bindingKeys.Length > 0)
{
foreach (var bindingKey in bindingKeys)
{
await RedisDb.KeyDeleteAsync(bindingKey.ToString());
}
}
await RedisDb.KeyDeleteAsync(bindingsSetKey);
_logger.LogInformation(
"释放机器人锁完成: RobotId={RobotId}, ReleasedCount={Count}",
robotId,
releasedCount);
return releasedCount;
}
/// <summary>
/// 续期机器人的所有锁
/// @author zzy
/// </summary>
public async Task<int> RenewAllRobotLocksAsync(Guid robotId, int ttlSeconds = 30)
{
var renewedCount = 0;
var newExpiresAt = DateTime.Now.AddSeconds(ttlSeconds);
var (nodeKeys, edgeKeys) = await GetRobotLockedResourcesAsync(robotId);
var bindingsSetKey = BuildRobotBindingsKey(robotId);
foreach (var key in nodeKeys)
{
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local newExpiresAt = ARGV[2]
local ttl = ARGV[3]
local current = redis.call('HGET', key, 'rid')
if current == robotId then
redis.call('HSET', key, 'eat', newExpiresAt)
redis.call('EXPIRE', key, ttl)
return 1
end
return 0
";
var result = (int)await RedisDb.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { key },
new RedisValue[]
{
robotId.ToString(),
newExpiresAt.Ticks.ToString(),
ttlSeconds.ToString()
});
if (result == 1)
{
renewedCount++;
}
}
foreach (var key in edgeKeys)
{
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local newExpiresAt = ARGV[2]
local ttl = ARGV[3]
local current = redis.call('HGET', key, 'rid')
if current == robotId then
redis.call('HSET', key, 'eat', newExpiresAt)
redis.call('EXPIRE', key, ttl)
return 1
end
return 0
";
var result = (int)await RedisDb.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { key },
new RedisValue[]
{
robotId.ToString(),
newExpiresAt.Ticks.ToString(),
ttlSeconds.ToString()
});
if (result == 1)
{
renewedCount++;
}
}
// 续期资源索引的TTL
var nodesSetKey = BuildRobotNodesKey(robotId);
var edgesSetKey = BuildRobotEdgesKey(robotId);
await RedisDb.KeyExpireAsync(nodesSetKey, TimeSpan.FromSeconds(ttlSeconds * 10));
await RedisDb.KeyExpireAsync(edgesSetKey, TimeSpan.FromSeconds(ttlSeconds * 10));
await RedisDb.KeyExpireAsync(bindingsSetKey, TimeSpan.FromSeconds(ttlSeconds * 10));
var bindingKeys = await RedisDb.SetMembersAsync(bindingsSetKey);
foreach (var bindingKey in bindingKeys)
{
await RedisDb.KeyExpireAsync(bindingKey.ToString(), TimeSpan.FromSeconds(ttlSeconds));
}
// _logger.LogDebug("续期机器人锁: RobotId={RobotId}, RenewedCount={Count}", robotId, renewedCount);
return renewedCount;
}
/// <summary>
/// 获取指定MapCode下所有锁定状态
/// @author zzy
/// </summary>
public async Task<List<LockStatusInfo>> GetAllLockStatusAsync(string mapCode)
{
var result = new List<LockStatusInfo>();
var now = DateTime.Now;
var nodePrefix = $"{_settings.Redis.KeyPrefixes.NodeLockPrefix}:{mapCode}:";
var edgePrefix = $"{_settings.Redis.KeyPrefixes.EdgeLockPrefix}:{mapCode}:";
// 使用 SCAN 遍历节点锁
var nodeCursor = 0;
do
{
var scanResult = await RedisDb.ScriptEvaluateAsync(
"return redis.call('SCAN', ARGV[1], 'MATCH', ARGV[2], 'COUNT', 100)",
null,
new RedisValue[] { nodeCursor.ToString(), $"{nodePrefix}*" });
var array = (RedisResult[])scanResult;
nodeCursor = int.Parse(array[0].ToString());
var keys = (RedisResult[])array[1];
foreach (var key in keys)
{
var lockInfo = await GetLockInfoAsync(key.ToString());
if (lockInfo != null && lockInfo.ExpiresAt > now)
{
var code = key.ToString()!.Substring(nodePrefix.Length);
result.Add(new LockStatusInfo
{
ResourceKey = key.ToString()!,
ResourceCode = code,
ResourceType = LockResourceType.Node,
IsLocked = true,
LockedByRobotId = lockInfo.RobotId,
LockedAt = lockInfo.LockedAt,
ExpiresAt = lockInfo.ExpiresAt
});
}
}
} while (nodeCursor != 0);
// 使用 SCAN 遍历边锁
var edgeCursor = 0;
do
{
var scanResult = await RedisDb.ScriptEvaluateAsync(
"return redis.call('SCAN', ARGV[1], 'MATCH', ARGV[2], 'COUNT', 100)",
null,
new RedisValue[] { edgeCursor.ToString(), $"{edgePrefix}*" });
var array = (RedisResult[])scanResult;
edgeCursor = int.Parse(array[0].ToString());
var keys = (RedisResult[])array[1];
foreach (var key in keys)
{
var lockInfo = await GetLockInfoAsync(key.ToString());
if (lockInfo != null && lockInfo.ExpiresAt > now)
{
var code = key.ToString()!.Substring(edgePrefix.Length);
result.Add(new LockStatusInfo
{
ResourceKey = key.ToString()!,
ResourceCode = code,
ResourceType = LockResourceType.Edge,
IsLocked = true,
LockedByRobotId = lockInfo.RobotId,
LockedAt = lockInfo.LockedAt,
ExpiresAt = lockInfo.ExpiresAt
});
}
}
} while (edgeCursor != 0);
return result;
}
#endregion
#region 冲突检测
/// <summary>
/// 检测路径是否与其他机器人冲突
/// @author zzy
/// </summary>
public async Task<PathConflictResult> CheckPathConflictAsync(
string mapCode,
IEnumerable<string> nodeCodes,
IEnumerable<string> edgeCodes,
Guid robotId,
Dictionary<string, (string FromNodeCode, string ToNodeCode)>? edgeDirectionMap = null)
{
var result = new PathConflictResult { HasConflict = false };
var now = DateTime.Now;
var nodeList = nodeCodes.ToList();
var edgeList = edgeCodes.ToList();
// 检查节点冲突
for (int i = 0; i < nodeList.Count; i++)
{
var nodeCode = nodeList[i];
var key = BuildNodeKey(mapCode, nodeCode);
var lockInfo = await GetLockInfoAsync(key);
if (lockInfo != null && lockInfo.RobotId != robotId && lockInfo.ExpiresAt > now)
{
result.HasConflict = true;
result.FirstConflictIndex ??= i;
result.Conflicts.Add(new PathConflictDetail
{
ResourceKey = key,
NodeCode = nodeCode,
ConflictType = ConflictType.NodeOccupied,
ConflictingRobotId = lockInfo.RobotId,
PathIndex = i
});
}
}
// 检查边冲突(同向冲突 + 逆向冲突)
for (int i = 0; i < edgeList.Count; i++)
{
var edgeCode = edgeList[i];
// 1. 检查当前 edgeCode 是否被锁定(同向冲突 - 跟随情况)
var key = BuildEdgeKey(mapCode, edgeCode);
var lockInfo = await GetLockInfoAsync(key);
if (lockInfo != null && lockInfo.RobotId != robotId && lockInfo.ExpiresAt > now)
{
// edgeCode 带方向,被锁定即表示同向行驶,记录但不视为真正冲突
result.SameDirectionConflicts.Add(new PathConflictDetail
{
ResourceKey = key,
EdgeCode = edgeCode,
ConflictType = ConflictType.EdgeOccupied,
ConflictingRobotId = lockInfo.RobotId,
PathIndex = i
});
continue; // 同向边已占用,跳过逆向边检查(同向已锁定,逆向不可能是同一条物理边)
}
// 2. 检查逆向边是否被锁定(逆向冲突 - 对向行驶)
// 根据 edgeDirectionMap 中的起点终点对调构建逆向边 Key
string? fromNodeCode = null;
string? toNodeCode = null;
if (edgeDirectionMap != null && edgeDirectionMap.TryGetValue(edgeCode, out var direction))
{
fromNodeCode = direction.FromNodeCode;
toNodeCode = direction.ToNodeCode;
}
var reverseEdgeCode = ResolveReverseEdgeCode(mapCode, edgeCode, fromNodeCode, toNodeCode);
if (!string.IsNullOrEmpty(reverseEdgeCode))
{
var reverseEdgeLockKey = BuildEdgeKey(mapCode, reverseEdgeCode);
var reverseLockInfo = await GetLockInfoAsync(reverseEdgeLockKey);
if (reverseLockInfo != null && reverseLockInfo.RobotId != robotId && reverseLockInfo.ExpiresAt > now)
{
// 逆向边被占用,这是对向冲突
result.HasConflict = true;
result.FirstConflictIndex ??= i;
result.Conflicts.Add(new PathConflictDetail
{
ResourceKey = reverseEdgeLockKey,
EdgeCode = edgeCode,
ConflictType = ConflictType.HeadOnConflict,
ConflictingRobotId = reverseLockInfo.RobotId,
PathIndex = i
});
// _logger.LogDebug("路径冲突检测发现逆向占用: Edge={EdgeCode}, ReverseEdge={ReverseEdge}, ConflictingRobot={ConflictingRobot}",
// edgeCode, reverseEdgeCode, reverseLockInfo.RobotId);
}
}
}
return result;
}
/// <summary>
/// 尝试锁定下一段路径,并判断是否存在逆向占用
/// 用于车辆快到当前段终点时,判断并发送下一段路径指令的场景
/// 排除同方向边冲突(同方向行驶视为跟随,不冲突)
/// @author zzy
/// </summary>
public async Task<NextSegmentLockResult> TryAcquireNextSegmentLockAsync(
string mapCode,
IEnumerable<PathSegmentWithCode> segments,
Guid robotId,
int ttlSeconds = 30)
{
var result = new NextSegmentLockResult { Success = false };
var segmentList = segments.ToList();
var nodeCodes = segmentList
.Select(s => s.FromNodeCode)
.Union(segmentList.Select(s => s.ToNodeCode))
.Distinct()
.Where(code => !string.IsNullOrEmpty(code))
.ToList();
var edgeCodes = segmentList
.Select(s => s.EdgeCode)
.Distinct()
.Where(code => !string.IsNullOrEmpty(code))
.ToList();
// 构建边方向映射(用于排除同方向冲突)
var edgeDirectionMap = segmentList
.Where(s => !string.IsNullOrEmpty(s.EdgeCode))
.GroupBy(s => s.EdgeCode, StringComparer.OrdinalIgnoreCase)
.ToDictionary(
g => g.Key,
g =>
{
var preferred = g.FirstOrDefault(s => !string.IsNullOrEmpty(s.FromNodeCode) && !string.IsNullOrEmpty(s.ToNodeCode))
?? g.First();
return (preferred.FromNodeCode, preferred.ToNodeCode);
},
StringComparer.OrdinalIgnoreCase);
// 首先检查路径冲突(传入方向映射以排除同方向冲突)
var conflictResult = await CheckPathConflictAsync(mapCode, nodeCodes, edgeCodes, robotId, edgeDirectionMap);
// 检查是否存在逆向冲突(HeadOnConflict)
var hasReverseConflict = conflictResult.Conflicts.Any(c => c.ConflictType == ConflictType.HeadOnConflict);
if (hasReverseConflict)
{
result.HasReverseConflict = true;
result.FailureReason = "存在逆向占用冲突";
// _logger.LogDebug("下一段路径存在逆向占用: RobotId={RobotId}, MapCode={MapCode}",
// robotId, mapCode);
return result;
}
# region 后续添加空间碰撞冲突和交叉边冲突再排除同向冲突判定,实现跟随
// 如果有其他冲突(节点被占用或非同向的边冲突),返回失败
// if (conflictResult.Conflicts.Any(c => c.ConflictType == ConflictType.NodeOccupied ||
// c.ConflictType == ConflictType.EdgeOccupied))
// {
// result.HasReverseConflict = false;
// var nodeConflicts = conflictResult.Conflicts.Where(c => c.ConflictType == ConflictType.NodeOccupied).ToList();
// var edgeConflicts = conflictResult.Conflicts.Where(c => c.ConflictType == ConflictType.EdgeOccupied).ToList();
//
// if (nodeConflicts.Any())
// {
// result.FailureReason = $"节点被占用: {string.Join(",", nodeConflicts.Select(c => c.NodeCode))}";
// }
// else if (edgeConflicts.Any())
// {
// result.FailureReason = $"边被占用(非同向): {string.Join(",", edgeConflicts.Select(c => c.EdgeCode))}";
// }
// else
// {
// result.FailureReason = "路径被其他机器人占用";
// }
//
// _logger.LogDebug("下一段路径被占用: RobotId={RobotId}, MapCode={MapCode}, Reason={Reason}",
// robotId, mapCode, result.FailureReason);
// return result;
// }
# endregion
if (conflictResult.Conflicts.Any() || conflictResult.SameDirectionConflicts.Any())
{
if (hasReverseConflict)
{
result.HasReverseConflict = true;
result.FailureReason = "存在普通冲突";
return result;
}
}
// 尝试锁定节点
var lockedNodeCodes = new List<string>();
foreach (var nodeCode in nodeCodes)
{
var locked = await TryAcquireNodeLockAsync(mapCode, nodeCode, robotId, ttlSeconds);
if (locked)
{
lockedNodeCodes.Add(nodeCode);
}
else
{
// 锁定失败,回滚已锁定的节点
foreach (var lockedNode in lockedNodeCodes)
{
await ReleaseNodeLockAsync(mapCode, lockedNode, robotId);
}
result.FailureReason = $"节点锁定失败: {nodeCode}";
_logger.LogDebug("下一段路径节点锁定失败: RobotId={RobotId}, MapCode={MapCode}, Node={Node}",
robotId, mapCode, nodeCode);
return result;
}
}
// 尝试锁定边(使用带方向信息的锁)
var lockedEdgeCodes = new List<string>();
foreach (var segment in segmentList.Where(s => !string.IsNullOrEmpty(s.EdgeCode)))
{
var locked = await TryAcquireEdgeLockWithDirectionAsync(
mapCode, segment.EdgeCode, robotId,
segment.FromNodeCode, segment.ToNodeCode, ttlSeconds);
if (locked)
{
lockedEdgeCodes.Add(segment.EdgeCode);
}
else
{
// 锁定失败,回滚所有已锁定的资源
foreach (var lockedNode in lockedNodeCodes)
{
await ReleaseNodeLockAsync(mapCode, lockedNode, robotId);
}
foreach (var lockedEdge in lockedEdgeCodes)
{
await ReleaseEdgeLockAsync(mapCode, lockedEdge, robotId);
}
result.FailureReason = $"边锁定失败: {segment.EdgeCode}";
_logger.LogDebug("下一段路径边锁定失败: RobotId={RobotId}, MapCode={MapCode}, Edge={Edge}",
robotId, mapCode, segment.EdgeCode);
return result;
}
}
result.Success = true;
result.LockedNodeCodes = lockedNodeCodes;
result.LockedEdgeCodes = lockedEdgeCodes;
_logger.LogDebug("下一段路径锁定成功: RobotId={RobotId}, MapCode={MapCode}, Nodes={NodeCount}, Edges={EdgeCount}",
robotId, mapCode, lockedNodeCodes.Count, lockedEdgeCodes.Count);
return result;
}
public async Task<BindingLockRequestResult> TryAcquireBindingsAsync(
string mapCode,
Guid robotId,
IEnumerable<BindingLockRequest> bindings,
int ttlSeconds = 30)
{
var result = new BindingLockRequestResult { Success = true };
var newlyLockedBindingIds = new List<string>();
var bindingList = bindings
.Where(binding => !string.IsNullOrWhiteSpace(binding.BindingId))
.ToList();
foreach (var binding in bindingList)
{
var bindingIndexKey = BuildBindingIndexKey(robotId, binding.BindingId);
if (await RedisDb.KeyExistsAsync(bindingIndexKey))
{
var existingResourceKeys = await GetBindingResourceKeysStrictAsync(
robotId,
binding.BindingId,
allowAlreadyReleased: false);
await ValidateBindingResourcesAsync(robotId, binding.BindingId, existingResourceKeys);
await RenewBindingResourcesAsync(robotId, binding.BindingId, existingResourceKeys, ttlSeconds);
result.LockedBindingIds.Add(binding.BindingId);
result.LockedNodeCodes.AddRange(binding.CoveredNodeCodes
.Where(code => !string.IsNullOrWhiteSpace(code))
.Distinct(StringComparer.OrdinalIgnoreCase));
result.LockedEdgeCodes.AddRange(binding.CoveredEdges
.Where(edge => !string.IsNullOrWhiteSpace(edge.EdgeCode))
.Select(edge => edge.EdgeCode)
.Distinct(StringComparer.OrdinalIgnoreCase));
await RedisDb.KeyExpireAsync(bindingIndexKey, TimeSpan.FromSeconds(ttlSeconds));
await RedisDb.KeyExpireAsync(BuildRobotBindingsKey(robotId), TimeSpan.FromSeconds(ttlSeconds * 10));
continue;
}
var acquiredNodeCodes = new List<string>();
var acquiredEdges = new List<VdaLockCoveredEdge>();
foreach (var nodeCode in binding.CoveredNodeCodes
.Where(code => !string.IsNullOrWhiteSpace(code))
.Distinct(StringComparer.OrdinalIgnoreCase))
{
var nodeAcquire = await TryAcquireBindingNodeLockAsync(mapCode, nodeCode, robotId, binding.BindingId, ttlSeconds);
if (!nodeAcquire.Success)
{
result.Success = false;
result.HasReverseConflict = nodeAcquire.HasReverseConflict;
result.FailureReason = nodeAcquire.FailureReason;
if (nodeAcquire.ConflictingRobotId.HasValue)
{
result.ConflictingRobotIds.Add(nodeAcquire.ConflictingRobotId.Value);
}
await ReleaseBindingResourcesDirectAsync(
mapCode,
robotId,
binding.BindingId,
acquiredNodeCodes,
acquiredEdges.Select(edge => edge.EdgeCode));
await RollbackBindingsAsync(mapCode, robotId, newlyLockedBindingIds);
result.LockedBindingIds.Clear();
result.LockedNodeCodes.Clear();
result.LockedEdgeCodes.Clear();
return NormalizeBindingLockResult(result);
}
acquiredNodeCodes.Add(nodeCode);
result.LockedNodeCodes.Add(nodeCode);
}
foreach (var coveredEdge in binding.CoveredEdges
.Where(edge => !string.IsNullOrWhiteSpace(edge.EdgeCode))
.GroupBy(edge => edge.EdgeCode, StringComparer.OrdinalIgnoreCase)
.Select(group => group.First()))
{
var edgeAcquire = await TryAcquireBindingEdgeLockAsync(
mapCode,
coveredEdge,
robotId,
binding.BindingId,
ttlSeconds);
if (!edgeAcquire.Success)
{
result.Success = false;
result.HasReverseConflict = edgeAcquire.HasReverseConflict;
result.FailureReason = edgeAcquire.FailureReason;
if (edgeAcquire.ConflictingRobotId.HasValue)
{
result.ConflictingRobotIds.Add(edgeAcquire.ConflictingRobotId.Value);
}
await ReleaseBindingResourcesDirectAsync(
mapCode,
robotId,
binding.BindingId,
acquiredNodeCodes,
acquiredEdges.Select(edge => edge.EdgeCode));
await RollbackBindingsAsync(mapCode, robotId, newlyLockedBindingIds);
result.LockedBindingIds.Clear();
result.LockedNodeCodes.Clear();
result.LockedEdgeCodes.Clear();
return NormalizeBindingLockResult(result);
}
acquiredEdges.Add(coveredEdge);
result.LockedEdgeCodes.Add(coveredEdge.EdgeCode);
}
await SaveBindingIndexAsync(mapCode, robotId, binding.BindingId, acquiredNodeCodes, acquiredEdges, ttlSeconds);
newlyLockedBindingIds.Add(binding.BindingId);
result.LockedBindingIds.Add(binding.BindingId);
}
return NormalizeBindingLockResult(result);
}
public async Task<int> ReleaseBindingsAsync(
string mapCode,
Guid robotId,
IEnumerable<string> bindingIds)
{
var releasedCount = 0;
var nodeSetKey = BuildRobotNodesKey(robotId);
var edgeSetKey = BuildRobotEdgesKey(robotId);
var bindingsSetKey = BuildRobotBindingsKey(robotId);
var bindingIdList = bindingIds
.Where(id => !string.IsNullOrWhiteSpace(id))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
var bindingResources = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
foreach (var bindingId in bindingIdList)
{
var resourceKeys = await GetBindingResourceKeysStrictAsync(
robotId,
bindingId,
allowAlreadyReleased: true);
if (resourceKeys.Count > 0)
{
await ValidateBindingResourcesAsync(robotId, bindingId, resourceKeys);
}
bindingResources[bindingId] = resourceKeys;
}
foreach (var bindingId in bindingIdList)
{
var bindingIndexKey = BuildBindingIndexKey(robotId, bindingId);
var resourceKeys = bindingResources[bindingId];
foreach (var resourceKey in resourceKeys)
{
var releaseResult = await ReleaseBindingFromResourceKeyAsync(resourceKey, robotId, bindingId);
if (releaseResult == BindingReleaseResult.ResourceDeleted)
{
releasedCount++;
if (resourceKey.StartsWith($"{_settings.Redis.KeyPrefixes.NodeLockPrefix}:", StringComparison.OrdinalIgnoreCase))
{
await RedisDb.SetRemoveAsync(nodeSetKey, resourceKey);
}
else if (resourceKey.StartsWith($"{_settings.Redis.KeyPrefixes.EdgeLockPrefix}:", StringComparison.OrdinalIgnoreCase))
{
await RedisDb.SetRemoveAsync(edgeSetKey, resourceKey);
}
}
else if (releaseResult == BindingReleaseResult.InvalidLegacyFormat)
{
throw new InvalidOperationException($"发现旧格式锁数据,无法按严格 binding 释放: {resourceKey}");
}
}
await RedisDb.KeyDeleteAsync(bindingIndexKey);
await RedisDb.SetRemoveAsync(bindingsSetKey, bindingIndexKey);
}
if (await RedisDb.SetLengthAsync(bindingsSetKey) == 0)
{
await RedisDb.KeyDeleteAsync(bindingsSetKey);
}
return releasedCount;
}
public Task<int> RollbackBindingsAsync(
string mapCode,
Guid robotId,
IEnumerable<string> bindingIds)
{
return ReleaseBindingsAsync(mapCode, robotId, bindingIds);
}
#endregion
#region 内部模型
private class LockInfo
{
public Guid RobotId { get; set; }
public DateTime LockedAt { get; set; }
public DateTime ExpiresAt { get; set; }
public List<string> BindingIds { get; set; } = new();
/// <summary>
/// 行驶方向起点节点Code(用于方向判断)
/// </summary>
public string? FromNodeCode { get; set; }
/// <summary>
/// 行驶方向终点节点Code(用于方向判断)
/// </summary>
public string? ToNodeCode { get; set; }
/// <summary>
/// 是否有方向信息
/// </summary>
public bool HasDirection => !string.IsNullOrEmpty(FromNodeCode) && !string.IsNullOrEmpty(ToNodeCode);
}
private sealed class BindingAcquireResult
{
public bool Success { get; set; }
public bool HasReverseConflict { get; set; }
public bool InvalidLegacyFormat { get; set; }
public string? FailureReason { get; set; }
public Guid? ConflictingRobotId { get; set; }
}
private enum BindingReleaseResult
{
NoChange = 0,
BindingRemoved = 1,
ResourceDeleted = 2,
InvalidLegacyFormat = 3
}
#endregion
#region 路口冲突检测辅助方法
/// <summary>
/// 检查节点是否被其他机器人占用
/// @author zzy
/// @date 2026-03-10
/// </summary>
public async Task<bool> IsNodeOccupiedByOtherAsync(string mapCode, string nodeCode, Guid myRobotId)
{
var key = BuildNodeKey(mapCode, nodeCode);
var lockInfo = await GetLockInfoAsync(key);
if (lockInfo == null)
return false;
// 检查是否被其他机器人占用
return lockInfo.RobotId != myRobotId;
}
/// <summary>
/// 检查边是否存在逆向冲突
/// @author zzy
/// @date 2026-03-10
/// </summary>
public async Task<bool> HasReverseConflictAsync(
string mapCode,
string edgeCode,
string fromNodeCode,
string toNodeCode,
Guid myRobotId)
{
var reverseEdgeCode = ResolveReverseEdgeCode(mapCode, edgeCode, fromNodeCode, toNodeCode);
if (string.IsNullOrEmpty(reverseEdgeCode))
{
return false;
}
// 检查逆向边是否被占用
var reverseEdgeLockKey = BuildEdgeKey(mapCode, reverseEdgeCode);
var lockInfo = await GetLockInfoAsync(reverseEdgeLockKey);
if (lockInfo == null)
return false;
// 检查是否被其他机器人占用,且方向相反
if (lockInfo.RobotId == myRobotId)
return false;
// 检查方向是否相反
if (lockInfo.HasDirection)
{
var isReverse = lockInfo.FromNodeCode == toNodeCode && lockInfo.ToNodeCode == fromNodeCode;
return isReverse;
}
return true;
}
/// <summary>
/// 获取锁信息
/// @author zzy
/// @date 2026-03-10
/// </summary>
private async Task<LockInfo?> GetLockInfoAsync(string key)
{
var entries = await RedisDb.HashGetAllAsync(key);
if (entries.Length == 0)
return null;
var dict = entries.ToDictionary(
e => e.Name.ToString(),
e => e.Value.ToString());
if (!dict.TryGetValue(LockFieldRobotId, out var robotIdStr) ||
!Guid.TryParse(robotIdStr, out var robotId))
{
return null;
}
var lockInfo = new LockInfo { RobotId = robotId };
if (dict.TryGetValue(LockFieldLockedAt, out var lockedAtStr) &&
long.TryParse(lockedAtStr, out var lockedAtTicks))
{
lockInfo.LockedAt = new DateTime(lockedAtTicks, DateTimeKind.Local);
}
if (dict.TryGetValue(LockFieldExpiresAt, out var expiresAtStr) &&
long.TryParse(expiresAtStr, out var expiresAtTicks))
{
lockInfo.ExpiresAt = new DateTime(expiresAtTicks, DateTimeKind.Local);
}
if (dict.TryGetValue(LockFieldFromNode, out var fromNode))
{
lockInfo.FromNodeCode = fromNode;
}
if (dict.TryGetValue(LockFieldToNode, out var toNode))
{
lockInfo.ToNodeCode = toNode;
}
if (dict.TryGetValue(LockFieldBindings, out var bindingsRaw) &&
!string.IsNullOrWhiteSpace(bindingsRaw))
{
try
{
lockInfo.BindingIds = JsonSerializer.Deserialize<List<string>>(bindingsRaw) ?? new List<string>();
}
catch (JsonException)
{
lockInfo.BindingIds = new List<string>();
}
}
return lockInfo;
}
/// <summary>
/// 获取占用指定节点的机器人ID列表
/// @author zzy
/// @date 2026-03-10
/// </summary>
public async Task<List<Guid>> GetRobotsOccupyingNodeAsync(string mapCode, string nodeCode)
{
var key = BuildNodeKey(mapCode, nodeCode);
var lockInfo = await GetLockInfoAsync(key);
if (lockInfo == null)
return new List<Guid>();
return new List<Guid> { lockInfo.RobotId };
}
/// <summary>
/// 获取占用指定边的机器人ID列表
/// @author zzy
/// @date 2026-03-10
/// </summary>
public async Task<List<Guid>> GetRobotsOccupyingEdgeAsync(string mapCode, string edgeCode)
{
var key = BuildEdgeKey(mapCode, edgeCode);
var lockInfo = await GetLockInfoAsync(key);
if (lockInfo == null)
return new List<Guid>();
return new List<Guid> { lockInfo.RobotId };
}
#endregion
}
}