UnifiedTrafficControlService.cs 52.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
using System;
using System.Collections.Generic;
using System.Linq;
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";

        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}";

        #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;
            }
        }

        /// <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)
        {
            string? reverseEdgeCode = null;

            // 优先使用传入的方向信息构建逆向边编码
            if (!string.IsNullOrEmpty(fromNodeCode) && !string.IsNullOrEmpty(toNodeCode))
            {
                reverseEdgeCode = $"{toNodeCode}-{fromNodeCode}";
            }
            else
            {
                // 回退到使用 _reverseEdgeMap
                var reverseKeyInfo = GetReverseEdgeKey(mapCode, edgeCode);
                if (!string.IsNullOrEmpty(reverseKeyInfo))
                {
                    var parts = reverseKeyInfo.Split(':');
                    if (parts.Length == 2)
                    {
                        reverseEdgeCode = parts[1];
                    }
                }
            }

            if (string.IsNullOrEmpty(reverseEdgeCode))
            {
                return (false, null);
            }

            var reverseEdgeLockKey = BuildEdgeKey(mapCode, reverseEdgeCode);
            var lockInfo = await GetLockInfoAsync(reverseEdgeLockKey);

            if (lockInfo != null)
            {
                var now = DateTime.UtcNow;
                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<LockInfo?> GetLockInfoAsync(string lockKey)
        {
            var hashEntries = await RedisDb.HashGetAllAsync(lockKey);
            if (hashEntries.Length == 0) return null;

            var dict = hashEntries.ToDictionary(
                e => e.Name.ToString(),
                e => e.Value.ToString());

            if (!dict.TryGetValue(LockFieldRobotId, out var robotIdStr) ||
                !Guid.TryParse(robotIdStr, out var robotId))
            {
                return null;
            }

            return new LockInfo
            {
                RobotId = robotId,
                LockedAt = dict.TryGetValue(LockFieldLockedAt, out var lat) &&
                           long.TryParse(lat, out var latTicks)
                    ? new DateTime(latTicks, DateTimeKind.Utc)
                    : DateTime.MinValue,
                ExpiresAt = dict.TryGetValue(LockFieldExpiresAt, out var eat) &&
                            long.TryParse(eat, out var eatTicks)
                    ? new DateTime(eatTicks, DateTimeKind.Utc)
                    : DateTime.MinValue,
                FromNodeCode = dict.TryGetValue(LockFieldFromNode, out var frm) ? frm : null,
                ToNodeCode = dict.TryGetValue(LockFieldToNode, out var to) ? to : null
            };
        }

        /// <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.UtcNow;
            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.UtcNow;
            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;
        }

        /// <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.UtcNow;
                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.UtcNow)
            {
                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);

            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++;
                }
            }

            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++;
                }
            }

            // 清理机器人的资源索引
            var nodesSetKey = BuildRobotNodesKey(robotId);
            var edgesSetKey = BuildRobotEdgesKey(robotId);
            await RedisDb.KeyDeleteAsync(nodesSetKey);
            await RedisDb.KeyDeleteAsync(edgesSetKey);

            _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.UtcNow.AddSeconds(ttlSeconds);

            var (nodeKeys, edgeKeys) = await GetRobotLockedResourcesAsync(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));

            // _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.UtcNow;

            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.UtcNow;

            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
                if (edgeDirectionMap != null &&
                    edgeDirectionMap.TryGetValue(edgeCode, out var direction))
                {
                    // 构建逆向边编码:将起点终点对调
                    var reverseEdgeCode = $"{direction.ToNodeCode}-{direction.FromNodeCode}";
                    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))
                .ToDictionary(
                    s => s.EdgeCode,
                    s => (s.FromNodeCode, s.ToNodeCode));

            // 首先检查路径冲突(传入方向映射以排除同方向冲突)
            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;
        }

        #endregion

        #region 内部模型

        private class LockInfo
        {
            public Guid RobotId { get; set; }
            public DateTime LockedAt { get; set; }
            public DateTime ExpiresAt { get; set; }

            /// <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);
        }

        #endregion
    }
}