主体 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>
173 lines
6.8 KiB
C#
173 lines
6.8 KiB
C#
using System;
|
||
using System.Buffers.Binary;
|
||
using System.IO;
|
||
using System.Text.Json;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace YuncangTrace.LocalService.Services;
|
||
|
||
/// <summary>
|
||
/// 服务主进程 ↔ <c>--hik-worker</c> 子进程的管道协议。
|
||
///
|
||
/// 为什么单独开子进程跑海康:HCNetSDK 是原生库,**访问越界会直接杀掉进程**
|
||
/// (0xC0000005),放主进程里等于把扫码收码/上报一起带走。
|
||
/// 隔离后 worker 崩了只需重启它,扫码链路无感。
|
||
///
|
||
/// 传输格式:<c>[4 字节小端长度][UTF-8 JSON]</c>。
|
||
/// 选命名管道而不是本机端口:不占端口、管道断开即知对端已死、ACL 天然限制访问者。
|
||
/// </summary>
|
||
public sealed record HikWorkerRequest(string Id, string Op, JsonElement? Payload)
|
||
{
|
||
public static HikWorkerRequest Create(string op, object? payload = null)
|
||
{
|
||
var element = payload is null
|
||
? (JsonElement?)null
|
||
: JsonSerializer.SerializeToElement(payload, HikWorkerJson.Options);
|
||
return new HikWorkerRequest(Guid.NewGuid().ToString("N"), op, element);
|
||
}
|
||
}
|
||
|
||
/// <summary>worker 的响应;<see cref="Data"/> 由调用方按 <see cref="Op"/> 自行反序列化</summary>
|
||
public sealed record HikWorkerResponse(string Id, bool Ok, string? Error, JsonElement? Data);
|
||
|
||
/// <summary>管道消息的读写(长度前缀 + JSON),两端共用</summary>
|
||
public static class HikWorkerPipe
|
||
{
|
||
/// <summary>管道名(服务单实例,固定名即可)</summary>
|
||
public const string PipeName = "YuncangTrace.HikWorker";
|
||
|
||
/// <summary>单条消息上限(流计划带十几个通道也远小于这个值)</summary>
|
||
private const int MaxMessageBytes = 8 * 1024 * 1024;
|
||
|
||
public static async Task WriteAsync<T>(Stream stream, T payload, CancellationToken ct)
|
||
{
|
||
var json = JsonSerializer.SerializeToUtf8Bytes(payload, HikWorkerJson.Options);
|
||
var header = new byte[4];
|
||
BinaryPrimitives.WriteInt32LittleEndian(header, json.Length);
|
||
|
||
await stream.WriteAsync(header, ct).ConfigureAwait(false);
|
||
await stream.WriteAsync(json, ct).ConfigureAwait(false);
|
||
await stream.FlushAsync(ct).ConfigureAwait(false);
|
||
}
|
||
|
||
/// <summary>读一条消息;对端正常关闭返回 null</summary>
|
||
public static async Task<T?> ReadAsync<T>(Stream stream, CancellationToken ct) where T : class
|
||
{
|
||
var header = new byte[4];
|
||
if (!await ReadExactAsync(stream, header, ct).ConfigureAwait(false)) return null;
|
||
|
||
var length = BinaryPrimitives.ReadInt32LittleEndian(header);
|
||
if (length is <= 0 or > MaxMessageBytes)
|
||
{
|
||
throw new InvalidDataException($"管道消息长度非法:{length}");
|
||
}
|
||
|
||
var buffer = new byte[length];
|
||
if (!await ReadExactAsync(stream, buffer, ct).ConfigureAwait(false))
|
||
{
|
||
throw new EndOfStreamException("管道消息被截断");
|
||
}
|
||
|
||
return JsonSerializer.Deserialize<T>(buffer, HikWorkerJson.Options);
|
||
}
|
||
|
||
private static async Task<bool> ReadExactAsync(Stream stream, byte[] buffer, CancellationToken ct)
|
||
{
|
||
var offset = 0;
|
||
while (offset < buffer.Length)
|
||
{
|
||
var read = await stream.ReadAsync(buffer.AsMemory(offset), ct).ConfigureAwait(false);
|
||
if (read == 0) return offset > 0 ? throw new EndOfStreamException("管道消息被截断") : false;
|
||
offset += read;
|
||
}
|
||
return true;
|
||
}
|
||
}
|
||
|
||
/// <summary>统一的序列化选项(两端必须一致,否则时间/枚举会解析出偏差)</summary>
|
||
public static class HikWorkerJson
|
||
{
|
||
public static readonly JsonSerializerOptions Options = new()
|
||
{
|
||
PropertyNameCaseInsensitive = true,
|
||
// 中文警告/错误直接可读,不转 \uXXXX
|
||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||
};
|
||
}
|
||
|
||
/// <summary>worker 支持的操作名(两端共用,避免拼错)</summary>
|
||
public static class HikWorkerOps
|
||
{
|
||
/// <summary>自检:返回 SDK / ffmpeg 是否就绪、录像根目录</summary>
|
||
public const string Probe = "probe";
|
||
|
||
/// <summary>校验某时段有没有录像(真拉一小段)</summary>
|
||
public const string Check = "check";
|
||
|
||
/// <summary>按流计划下载并合并</summary>
|
||
public const string Download = "download";
|
||
|
||
/// <summary>优雅退出</summary>
|
||
public const string Shutdown = "shutdown";
|
||
}
|
||
|
||
/// <summary>
|
||
/// 局域网发现用的端口(与 17300/17301 同族,但独立进程独立端口)。
|
||
///
|
||
/// - <see cref="UdpQuery"/>:收桌面端的广播询问(**询问-应答**,不是主动公告);
|
||
/// - <see cref="Http"/>:取流健康端点,桌面端用一次 TCP 连接就能判定"是否同 LAN"。
|
||
/// </summary>
|
||
public static class HikWorkerPorts
|
||
{
|
||
/// <summary>可用 <c>YUNCANG_EDGE_UDP_PORT</c> 临时覆盖(同机并行跑两个实例测试时用)</summary>
|
||
public static int UdpQuery { get; } = Resolve("YUNCANG_EDGE_UDP_PORT", 17310);
|
||
|
||
/// <summary>可用 <c>YUNCANG_EDGE_HTTP_PORT</c> 临时覆盖</summary>
|
||
public static int Http { get; } = Resolve("YUNCANG_EDGE_HTTP_PORT", 17311);
|
||
|
||
/// <summary>
|
||
/// 监听地址。默认 <c>0.0.0.0</c>(局域网可发现可直连);
|
||
/// 设 <c>YUNCANG_EDGE_BIND=127.0.0.1</c> 则只给本机用,不对局域网暴露。
|
||
/// </summary>
|
||
public static string BindAddress { get; } = ResolveBind();
|
||
|
||
private static int Resolve(string name, int fallback)
|
||
{
|
||
var raw = Environment.GetEnvironmentVariable(name);
|
||
return int.TryParse(raw, out var port) && port is > 0 and < 65536 ? port : fallback;
|
||
}
|
||
|
||
private static string ResolveBind()
|
||
{
|
||
var raw = Environment.GetEnvironmentVariable("YUNCANG_EDGE_BIND");
|
||
return string.IsNullOrWhiteSpace(raw) ? "0.0.0.0" : raw.Trim();
|
||
}
|
||
}
|
||
|
||
/// <summary>局域网询问/应答的报文(两端共用)</summary>
|
||
public static class HikWorkerDiscovery
|
||
{
|
||
public const string QueryType = "edge.query";
|
||
public const string ReplyType = "edge.reply";
|
||
|
||
/// <summary>
|
||
/// 规范化后端地址,只保留「协议 + 主机 + 端口」用于比对。
|
||
///
|
||
/// 主体 id 在各个环境的库里都可能从 1 开始,光比 subjectId 挡不住跨环境串台
|
||
/// (开发库和生产库的「测试仓库」都是 1),所以询问和应答都必须带上后端地址。
|
||
/// </summary>
|
||
public static string NormalizeServer(string? raw)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(raw)) return string.Empty;
|
||
|
||
var text = raw.Trim();
|
||
if (!text.Contains("://", StringComparison.Ordinal)) text = "http://" + text;
|
||
|
||
return Uri.TryCreate(text, UriKind.Absolute, out var uri)
|
||
? uri.Scheme.ToLowerInvariant() + "://" + uri.Host.ToLowerInvariant() + (uri.IsDefaultPort ? "" : ":" + uri.Port)
|
||
: string.Empty;
|
||
}
|
||
}
|
||
|