using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace YuncangTrace.LocalService.Services.Edge;
///
/// 决定「这次取流请求由谁执行」:局域网里的**设备管理服务**,还是本机。
///
/// 规则只有一条 —— **有设备管理服务就全部交给它**,没有才由本机自己连 NVR。
/// 不看"本机能不能连 NVR":多台查询机各自连 NVR 会把录像机的并发登录数打满
/// (海康常见 6~16),而设备管理服务本来就有会话池,能复用、能限流。
///
/// 探测结果缓存 秒(含"没找到"的负结果),
/// 避免每次请求都白等一次广播;转发失败时调用 重新探测。
///
public sealed class StreamGateway
{
private static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(15);
private readonly Func _subjectId;
private readonly Func _server;
private readonly SemaphoreSlim _gate = new(1, 1);
private string _cacheKey = "";
private EdgePeer? _cached;
private DateTime _cachedAt = DateTime.MinValue;
/// 当前主体(探测只认同主体应答)
/// 当前后端地址(探测只认同环境应答)
public StreamGateway(Func subjectIdProvider, Func serverProvider)
{
_subjectId = subjectIdProvider;
_server = serverProvider;
}
/// 找一台能服务这些 NVR 的设备管理服务;没有返回 null(调用方走本机)
public async Task 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))
{
// 缓存命中就不再广播了:不记一行的话,现场会以为「探测根本没跑」
AppLog.Write(cached is null
? "[edge] 局域网探测(15 秒缓存):没有可用的设备管理服务"
: $"[edge] 局域网探测(15 秒缓存):{cached.Display}");
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();
}
}
/// 转发失败时调用:下次重新探测,避免一直指着一台已经不可用的服务
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);
}
}