ResetProtectedLockContextService.cs
15.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
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Rcs.Application.Services.PathFind;
using Rcs.Application.Services.PathFind.Models;
using Rcs.Domain.Settings;
using StackExchange.Redis;
namespace Rcs.Infrastructure.Services;
/// <summary>
/// Stores reset-preserved binding locks so they can be released after the robot leaves the reset anchor.
/// </summary>
public sealed class ResetProtectedLockContextService
{
private const string ResetProtectedSuffix = "reset-protected";
private readonly ILogger<ResetProtectedLockContextService> _logger;
private readonly IConnectionMultiplexer _redis;
private readonly IAgvPathService _agvPathService;
private readonly AppSettings _settings;
public ResetProtectedLockContextService(
ILogger<ResetProtectedLockContextService> logger,
IConnectionMultiplexer redis,
IAgvPathService agvPathService,
IOptions<AppSettings> settings)
{
_logger = logger;
_redis = redis;
_agvPathService = agvPathService;
_settings = settings.Value;
}
public string BuildContextKey(Guid robotId) =>
$"{_settings.Redis.KeyPrefixes.RobotLockResourcesPrefix}:{robotId}:{ResetProtectedSuffix}";
public async Task CaptureAsync(Guid robotId, string mapCode, string anchorNodeCode)
{
if (robotId == Guid.Empty ||
string.IsNullOrWhiteSpace(mapCode) ||
string.IsNullOrWhiteSpace(anchorNodeCode))
{
return;
}
var db = _redis.GetDatabase();
var bindingsSetKey = BuildRobotBindingsKey(robotId);
var anchorNodeKey = BuildNodeKey(mapCode, anchorNodeCode);
var bindingIndexKeys = (await db.SetMembersAsync(bindingsSetKey))
.Select(value => value.ToString())
.Where(value => !string.IsNullOrWhiteSpace(value))
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(value => value, StringComparer.OrdinalIgnoreCase)
.ToList();
var snapshots = new List<ResetProtectedBindingSnapshot>();
foreach (var bindingIndexKey in bindingIndexKeys)
{
if (!await db.SetContainsAsync(bindingIndexKey, anchorNodeKey))
{
continue;
}
var bindingId = TryExtractBindingId(robotId, bindingIndexKey);
if (string.IsNullOrWhiteSpace(bindingId))
{
continue;
}
var resourceKeys = (await db.SetMembersAsync(bindingIndexKey))
.Select(value => value.ToString())
.Where(value => !string.IsNullOrWhiteSpace(value))
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(value => value, StringComparer.OrdinalIgnoreCase)
.ToList();
if (resourceKeys.Count == 0)
{
continue;
}
snapshots.Add(new ResetProtectedBindingSnapshot
{
BindingId = bindingId,
ResourceKeys = resourceKeys
});
}
var contextKey = BuildContextKey(robotId);
var anchorNodeOwner = await db.HashGetAsync(anchorNodeKey, "rid");
if (snapshots.Count == 0 && anchorNodeOwner.ToString() != robotId.ToString())
{
await db.KeyDeleteAsync(contextKey);
_logger.LogInformation(
"[复位保护锁] 未捕获到需要按LastNode释放的binding: RobotId={RobotId}, MapCode={MapCode}, AnchorNode={AnchorNode}",
robotId,
mapCode,
anchorNodeCode);
return;
}
var context = new ResetProtectedLockContext
{
RobotId = robotId,
MapCode = mapCode,
AnchorNodeCode = anchorNodeCode,
CreatedAtUtc = DateTime.UtcNow,
Bindings = snapshots
};
await db.StringSetAsync(contextKey, JsonSerializer.Serialize(context));
_logger.LogInformation(
"[复位保护锁] 已捕获复位保护binding上下文: RobotId={RobotId}, MapCode={MapCode}, AnchorNode={AnchorNode}, BindingCount={BindingCount}",
robotId,
mapCode,
anchorNodeCode,
snapshots.Count);
}
public async Task DeleteAsync(Guid robotId)
{
if (robotId == Guid.Empty)
{
return;
}
await _redis.GetDatabase().KeyDeleteAsync(BuildContextKey(robotId));
}
public async Task<ResetProtectedReleaseResult> TryReleaseAfterLastNodeAsync(Guid robotId, string? lastNodeId)
{
var result = new ResetProtectedReleaseResult();
if (robotId == Guid.Empty || string.IsNullOrWhiteSpace(lastNodeId))
{
return result;
}
var db = _redis.GetDatabase();
var contextKey = BuildContextKey(robotId);
var contextValue = await db.StringGetAsync(contextKey);
if (contextValue.IsNullOrEmpty)
{
return result;
}
ResetProtectedLockContext? context;
try
{
context = JsonSerializer.Deserialize<ResetProtectedLockContext>(contextValue.ToString());
}
catch (Exception ex) when (ex is JsonException or NotSupportedException)
{
_logger.LogWarning(ex, "[复位保护锁] 上下文反序列化失败,删除上下文: RobotId={RobotId}, Key={Key}", robotId, contextKey);
await db.KeyDeleteAsync(contextKey);
return result;
}
if (context == null ||
context.RobotId != robotId ||
string.IsNullOrWhiteSpace(context.MapCode) ||
string.IsNullOrWhiteSpace(context.AnchorNodeCode))
{
await db.KeyDeleteAsync(contextKey);
return result;
}
result.HasContext = true;
if (IsNodeCodeMatchWithVirtualSuffix(lastNodeId, context.AnchorNodeCode))
{
result.StillAtAnchor = true;
return result;
}
var activeBindingIds = await GetActivePathCacheBindingIdsAsync(robotId);
var bindingIdsToRelease = new List<string>();
foreach (var snapshot in context.Bindings)
{
if (string.IsNullOrWhiteSpace(snapshot.BindingId))
{
result.AlreadyGoneOrInvalidCount++;
continue;
}
if (activeBindingIds.Contains(snapshot.BindingId))
{
result.ActiveOwnedCount++;
continue;
}
var currentResourceKeys = (await db.SetMembersAsync(BuildBindingIndexKey(robotId, snapshot.BindingId)))
.Select(value => value.ToString())
.Where(value => !string.IsNullOrWhiteSpace(value))
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(value => value, StringComparer.OrdinalIgnoreCase)
.ToList();
if (currentResourceKeys.Count == 0)
{
result.AlreadyGoneOrInvalidCount++;
continue;
}
if (!currentResourceKeys.SequenceEqual(
snapshot.ResourceKeys
.Where(value => !string.IsNullOrWhiteSpace(value))
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(value => value, StringComparer.OrdinalIgnoreCase),
StringComparer.OrdinalIgnoreCase))
{
result.SnapshotMismatchCount++;
continue;
}
bindingIdsToRelease.Add(snapshot.BindingId);
}
if (bindingIdsToRelease.Count > 0)
{
result.ReleasedResourceCount = await _agvPathService.ReleaseBindingsAsync(
context.MapCode,
robotId,
bindingIdsToRelease);
result.ReleasedBindingCount = bindingIdsToRelease.Count;
}
result.ReleasedAnchorNodeCount = await ReleaseStandaloneAnchorNodeIfUnboundAsync(context);
await db.KeyDeleteAsync(contextKey);
result.ContextDeleted = true;
_logger.LogInformation(
"[复位保护锁] 已按LastNode离开释放复位保护binding: RobotId={RobotId}, LastNode={LastNode}, AnchorNode={AnchorNode}, ReleasedBindings={ReleasedBindings}, ReleasedResources={ReleasedResources}, ReleasedAnchorNodes={ReleasedAnchorNodes}, ActiveOwned={ActiveOwned}, SnapshotMismatch={SnapshotMismatch}, Gone={Gone}",
robotId,
lastNodeId,
context.AnchorNodeCode,
result.ReleasedBindingCount,
result.ReleasedResourceCount,
result.ReleasedAnchorNodeCount,
result.ActiveOwnedCount,
result.SnapshotMismatchCount,
result.AlreadyGoneOrInvalidCount);
return result;
}
private async Task<int> ReleaseStandaloneAnchorNodeIfUnboundAsync(ResetProtectedLockContext context)
{
var nodeKey = BuildNodeKey(context.MapCode, context.AnchorNodeCode);
var nodeSetKey = BuildRobotNodesKey(context.RobotId);
const string luaScript = @"
local key = KEYS[1]
local robotId = ARGV[1]
local current = redis.call('HGET', key, 'rid')
if current ~= robotId then
return 0
end
local bindings = redis.call('HGET', key, 'bindings')
if bindings ~= false and bindings ~= '' and bindings ~= '[]' then
return 0
end
redis.call('DEL', key)
return 1
";
var released = (int)await _redis.GetDatabase().ScriptEvaluateAsync(
luaScript,
new RedisKey[] { nodeKey },
new RedisValue[] { context.RobotId.ToString() });
if (released == 1)
{
await _redis.GetDatabase().SetRemoveAsync(nodeSetKey, nodeKey);
}
return released;
}
private async Task<HashSet<string>> GetActivePathCacheBindingIdsAsync(Guid robotId)
{
var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var endpoints = _redis.GetEndPoints();
if (endpoints.Length == 0)
{
return result;
}
var server = _redis.GetServer(endpoints.First());
var db = _redis.GetDatabase();
var pattern = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robotId}:*";
foreach (var key in server.Keys(pattern: pattern))
{
var keyText = key.ToString();
if (!IsVdaPathCachePayloadKey(keyText, robotId))
{
continue;
}
var cacheValue = await db.StringGetAsync(key);
if (cacheValue.IsNullOrEmpty)
{
continue;
}
VdaSegmentedPathCache? cache;
try
{
cache = JsonSerializer.Deserialize<VdaSegmentedPathCache>(cacheValue.ToString());
}
catch (Exception ex) when (ex is JsonException or NotSupportedException)
{
_logger.LogDebug(ex, "[复位保护锁] 跳过无法反序列化的路径缓存Key: {CacheKey}", keyText);
continue;
}
if (cache == null)
{
continue;
}
foreach (var bindingId in cache.LockBindingPlans
.Where(plan => plan.IsLocked && !plan.IsReleased && !string.IsNullOrWhiteSpace(plan.BindingId))
.Select(plan => plan.BindingId))
{
result.Add(bindingId);
}
}
return result;
}
private string BuildNodeKey(string mapCode, string nodeCode) =>
$"{_settings.Redis.KeyPrefixes.NodeLockPrefix}:{mapCode}:{nodeCode}";
private string BuildRobotBindingsKey(Guid robotId) =>
$"{_settings.Redis.KeyPrefixes.RobotLockResourcesPrefix}:{robotId}:{_settings.Redis.KeyPrefixes.RobotLockBindingsSuffix}";
private string BuildRobotNodesKey(Guid robotId) =>
$"{_settings.Redis.KeyPrefixes.RobotLockResourcesPrefix}:{robotId}:{_settings.Redis.KeyPrefixes.RobotLockNodesSuffix}";
private string BuildBindingIndexKey(Guid robotId, string bindingId) =>
$"{BuildRobotBindingsKey(robotId)}:{bindingId}";
private string? TryExtractBindingId(Guid robotId, string bindingIndexKey)
{
var prefix = $"{BuildRobotBindingsKey(robotId)}:";
if (!bindingIndexKey.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return null;
}
var bindingId = bindingIndexKey[prefix.Length..];
return string.IsNullOrWhiteSpace(bindingId) ? null : bindingId;
}
private static bool IsVdaPathCachePayloadKey(string keyText, Guid robotId)
{
if (string.IsNullOrWhiteSpace(keyText))
{
return false;
}
var parts = keyText.Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length < 3)
{
return false;
}
return Guid.TryParse(parts[^3], out var keyRobotId) &&
keyRobotId == robotId &&
Guid.TryParse(parts[^2], out _) &&
Guid.TryParse(parts[^1], out _);
}
private static bool IsNodeCodeMatchWithVirtualSuffix(string? actualNodeCode, string? expectedNodeCode)
{
if (string.IsNullOrWhiteSpace(actualNodeCode) || string.IsNullOrWhiteSpace(expectedNodeCode))
{
return false;
}
if (string.Equals(actualNodeCode, expectedNodeCode, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return string.Equals(
NormalizeVirtualNodeCodeForComparison(actualNodeCode),
NormalizeVirtualNodeCodeForComparison(expectedNodeCode),
StringComparison.OrdinalIgnoreCase);
}
private static string NormalizeVirtualNodeCodeForComparison(string nodeCode)
{
var trimCode = nodeCode.Trim();
var dashIndex = trimCode.LastIndexOf('-');
if (dashIndex <= 0 || dashIndex >= trimCode.Length - 1)
{
return trimCode;
}
var suffix = trimCode[(dashIndex + 1)..];
return suffix.All(char.IsDigit) ? trimCode[..dashIndex] : trimCode;
}
}
public sealed class ResetProtectedLockContext
{
public Guid RobotId { get; set; }
public string MapCode { get; set; } = string.Empty;
public string AnchorNodeCode { get; set; } = string.Empty;
public DateTime CreatedAtUtc { get; set; }
public List<ResetProtectedBindingSnapshot> Bindings { get; set; } = new();
}
public sealed class ResetProtectedBindingSnapshot
{
public string BindingId { get; set; } = string.Empty;
public List<string> ResourceKeys { get; set; } = new();
}
public sealed class ResetProtectedReleaseResult
{
public bool HasContext { get; set; }
public bool StillAtAnchor { get; set; }
public bool ContextDeleted { get; set; }
public int ReleasedBindingCount { get; set; }
public int ReleasedResourceCount { get; set; }
public int ReleasedAnchorNodeCount { get; set; }
public int ActiveOwnedCount { get; set; }
public int SnapshotMismatchCount { get; set; }
public int AlreadyGoneOrInvalidCount { get; set; }
}