packServer/desktop/Services/Edge/StreamGateway.cs
liufumingren c280e94b9a 加固局域网询问应答:主体 + 后端身份双校验
主体 id 在各环境的库里都从 1 开始,光比 subjectId 挡不住跨环境串台
(开发库和生产库的测试仓库都是 1),旧机器只要 agent.json 还在就会一直应答。

- 询问必须带 subjectId>0 和 server,缺任一项不应答
- 应答回带 server,A 侧也校验一致;不一致直接丢弃
- 多台应答按 (SN, 主机) 去重,并优先本机地址
- 版本号提到 1.0.105

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-22 01:27:49 +08:00

105 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace YuncangTrace.LocalService.Services.Edge;
/// <summary>
/// 决定「这次取流请求由谁执行」:局域网里的**设备管理服务**,还是本机。
///
/// 规则只有一条 —— **有设备管理服务就全部交给它**,没有才由本机自己连 NVR。
/// 不看"本机能不能连 NVR":多台查询机各自连 NVR 会把录像机的并发登录数打满
/// (海康常见 6~16),而设备管理服务本来就有会话池,能复用、能限流。
///
/// 探测结果缓存 <see cref="CacheTtl"/> 秒(含"没找到"的负结果),
/// 避免每次请求都白等一次广播;转发失败时调用 <see cref="Invalidate"/> 重新探测。
/// </summary>
public sealed class StreamGateway
{
private static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(15);
private readonly Func<int> _subjectId;
private readonly Func<string?> _server;
private readonly SemaphoreSlim _gate = new(1, 1);
private string _cacheKey = "";
private EdgePeer? _cached;
private DateTime _cachedAt = DateTime.MinValue;
/// <param name="subjectIdProvider">当前主体(探测只认同主体应答)</param>
/// <param name="serverProvider">当前后端地址(探测只认同环境应答)</param>
public StreamGateway(Func<int> subjectIdProvider, Func<string?> serverProvider)
{
_subjectId = subjectIdProvider;
_server = serverProvider;
}
/// <summary>找一台能服务这些 NVR 的设备管理服务;没有返回 null(调用方走本机)</summary>
public async Task<EdgePeer?> FindAsync(IReadOnlyList<(string Host, int Port)> nvrs,
CancellationToken ct = default)
{
var subjectId = _subjectId();
if (subjectId <= 0) return null;
var key = BuildKey(subjectId, nvrs);
if (TryGetCached(key, out var cached)) return cached;
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
if (TryGetCached(key, out cached)) return cached;
var peer = await EdgeDiscoveryClient.FindAsync(subjectId, _server(), nvrs, ct).ConfigureAwait(false);
if (peer is not null)
{
AppLog.Write($"[edge] 走设备管理服务 {peer.Display}"
+ $"(可服务 {string.Join("、", peer.Reachable)})");
}
_cacheKey = key;
_cached = peer;
_cachedAt = DateTime.UtcNow;
return peer;
}
finally
{
_gate.Release();
}
}
/// <summary>转发失败时调用:下次重新探测,避免一直指着一台已经不可用的服务</summary>
public void Invalidate()
{
_cached = null;
_cachedAt = DateTime.MinValue;
_cacheKey = "";
}
private bool TryGetCached(string key, out EdgePeer? peer)
{
if (_cachedAt != DateTime.MinValue
&& string.Equals(_cacheKey, key, StringComparison.Ordinal)
&& DateTime.UtcNow - _cachedAt < CacheTtl)
{
peer = _cached;
return true;
}
peer = null;
return false;
}
private static string BuildKey(int subjectId, IReadOnlyList<(string Host, int Port)> nvrs)
{
var hosts = nvrs
.Where(item => !string.IsNullOrWhiteSpace(item.Host))
.Select(item => $"{item.Host}:{item.Port}")
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(item => item, StringComparer.OrdinalIgnoreCase);
return subjectId + "|" + string.Join(",", hosts);
}
}