From 46e4f128023437173bd0af7201bcf98d55ad712d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 21 Oct 2026 22:48:09 +0800 Subject: [PATCH] =?UTF-8?q?=EF=BB=BFdesktop:=20=E5=8F=96=E6=B5=81=E5=AD=90?= =?UTF-8?q?=E8=BF=9B=E7=A8=8B=E9=9A=94=E7=A6=BB=20+=20=E5=B1=80=E5=9F=9F?= =?UTF-8?q?=E7=BD=91=E8=AF=A2=E9=97=AE=E5=BA=94=E7=AD=94=20+=20=E8=B7=A8?= =?UTF-8?q?=E7=BD=91=E4=B8=8B=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 把海康取流从扫码服务主进程拆到 --hik-worker 子进程,原生 SDK 崩溃 不再连带扫码收码;新增局域网询问-应答与跨网下载通道。 隔离与守护 - 新增 HikWorker(子进程):独占 HCNetSDK 与 NVR 会话池 - 新增 HikWorkerSupervisor(主进程):懒启动、管道通信、 5 分钟内失败 3 次熔断 10 分钟 - 管道协议为 [4 字节长度][JSON],进程退出即知,不占端口 - ServiceInstaller 复制 native(HCNetSDK/ffmpeg),先删后拷, 避免 SDK 升级残留旧 DLL;安装时放行 TCP 17311 / UDP 17310 局域网询问-应答(不是主动公告) - UDP 17310 收询问,只回同 subjectId;带了 nvrHosts 时先实测可达, 连不上就不应答,让查询机继续走本机 - 应答带 TCP 17311,查询机一次连接即可判定是否同 LAN 跨网下载 - TCP 17311 提供 /health、/probe、/download、/download/{id} - 除 /health 外均要求 X-Edge-Subject 且与配置主体一致 - 成片在传输完成后立即删除,另有 done 10 分钟 / failed 15 分钟 TTL 兜底,避免现场磁盘被临时文件吃满 桌面端选路 - DownloadAsync 先探 NVR 8000(600ms):通则沿用原有本机直连, 不通才广播找取流服务,取回后落到本机录像目录 - DownloadByPlanAsync 拆分:不查库、不需要用户令牌, 供只有设备令牌的服务端复用 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- desktop/Program.cs | 11 + desktop/Services/Agent/AgentFiles.cs | 35 ++ desktop/Services/Agent/AgentHost.cs | 72 ++- desktop/Services/Agent/EdgeDownloadTasks.cs | 175 ++++++ desktop/Services/Agent/EdgeHttpService.cs | 532 ++++++++++++++++++ desktop/Services/Agent/HikWorker.cs | 473 ++++++++++++++++ desktop/Services/Agent/HikWorkerProtocol.cs | 130 +++++ desktop/Services/Agent/HikWorkerSupervisor.cs | 380 +++++++++++++ desktop/Services/Agent/ServiceInstaller.cs | 96 +++- desktop/Services/AgentPaths.cs | 8 + desktop/Services/Edge/EdgeClient.cs | 175 ++++++ desktop/Services/Edge/EdgeDiscoveryClient.cs | 198 +++++++ desktop/Services/PlaybackDownloadService.cs | 180 +++++- desktop/Services/Scan/DeviceScanner.cs | 2 +- 14 files changed, 2447 insertions(+), 20 deletions(-) create mode 100644 desktop/Services/Agent/EdgeDownloadTasks.cs create mode 100644 desktop/Services/Agent/EdgeHttpService.cs create mode 100644 desktop/Services/Agent/HikWorker.cs create mode 100644 desktop/Services/Agent/HikWorkerProtocol.cs create mode 100644 desktop/Services/Agent/HikWorkerSupervisor.cs create mode 100644 desktop/Services/Edge/EdgeClient.cs create mode 100644 desktop/Services/Edge/EdgeDiscoveryClient.cs diff --git a/desktop/Program.cs b/desktop/Program.cs index e149842..7ed97cf 100644 --- a/desktop/Program.cs +++ b/desktop/Program.cs @@ -38,6 +38,17 @@ public static class Program return; } + // ①-c 海康取流子进程(由服务主进程拉起)。 + // 单独成进程是为了隔离原生 SDK 崩溃:HCNetSDK 访问越界会直接杀进程, + // 放在服务主进程里会把扫码收码一起带走。 + if (args.Any(arg => arg.Equals("--hik-worker", StringComparison.OrdinalIgnoreCase))) + { + using var cts = new CancellationTokenSource(); + AppDomain.CurrentDomain.ProcessExit += (_, _) => cts.Cancel(); + HikWorker.RunAsync(cts.Token).GetAwaiter().GetResult(); + return; + } + // ② 提权 helper(安装/卸载/启停服务) if (ServiceInstaller.IsHelperCall(args)) { diff --git a/desktop/Services/Agent/AgentFiles.cs b/desktop/Services/Agent/AgentFiles.cs index e109395..861125e 100644 --- a/desktop/Services/Agent/AgentFiles.cs +++ b/desktop/Services/Agent/AgentFiles.cs @@ -57,6 +57,9 @@ public sealed class AgentStatus public string? LastError { get; set; } + /// 取流子进程(--hik-worker)状态;没有取流能力时 为 false + public AgentHikStatus Hik { get; set; } = new(); + public string NtpLastSyncAt { get; set; } = ""; public double NtpLastOffsetSeconds { get; set; } public double NtpRoundTripMs { get; set; } @@ -93,6 +96,38 @@ public sealed class AgentChannelStatus public DateTime? LastCodeAt { get; set; } } +/// +/// 取流子进程的运行时状态(桌面端/客服排障用)。 +/// +/// 为 false 只表示"取不到视频",**扫码/上报照常工作**。 +/// +public sealed class AgentHikStatus +{ + /// SDK 与 ffmpeg 是否就位(自检结果) + public bool Available { get; set; } + + /// worker 进程当前是否已连接 + public bool Connected { get; set; } + + /// HCNetSDK.dll 所在目录(找不到为 null) + public string? SdkDir { get; set; } + + /// ffmpeg.exe 路径(找不到为 null) + public string? FfmpegPath { get; set; } + + /// 成片根目录 + public string VideoRoot { get; set; } = ""; + + /// 连续失败熔断到什么时候(null = 未熔断) + public DateTime? BlockedUntil { get; set; } + + /// 最近一次失败原因 + public string? LastError { get; set; } + + /// 最近一次自检时间 + public DateTime? ProbedAt { get; set; } +} + /// 桌面端 → 后台服务的一次性命令(写文件,服务每秒轮询) public sealed class AgentCommand { diff --git a/desktop/Services/Agent/AgentHost.cs b/desktop/Services/Agent/AgentHost.cs index 258dd67..5dc08bb 100644 --- a/desktop/Services/Agent/AgentHost.cs +++ b/desktop/Services/Agent/AgentHost.cs @@ -140,11 +140,47 @@ public static class AgentHost var lastStatusJson = string.Empty; var lastStatusWriteAt = DateTime.MinValue; + // 取流子进程:懒启动,崩了只影响取流,扫码链路完全不受影响 + var hikStatus = new AgentHikStatus { VideoRoot = AgentPaths.VideosRoot }; + await using var hikWorker = new HikWorkerSupervisor(); + hikWorker.StateChanged += () => + { + hikStatus.Connected = hikWorker.IsConnected; + hikStatus.BlockedUntil = hikWorker.BlockedUntil; + hikStatus.LastError = hikWorker.LastError; + }; + try { device.EnsureUploadLoop(); await scan.StartAsync().ConfigureAwait(false); scan.StartDiscovery(); // 常驻发现:设备 DHCP 换 IP 时能自己重连 + + // 延后自检:不抢服务启动的 CPU,也能让状态文件尽快反映「SDK 是否就位」 + _ = Task.Run(async () => + { + try + { + if (!await DelayAsync(TimeSpan.FromSeconds(20), ct).ConfigureAwait(false)) return; + + ApplyHikProbe(hikStatus, await hikWorker.ProbeAsync(ct).ConfigureAwait(false)); + hikStatus.Connected = hikWorker.IsConnected; + + AppLog.Write($"[agent] 取流自检:sdk={hikStatus.SdkDir ?? "未找到"}," + + $"ffmpeg={hikStatus.FfmpegPath ?? "未找到"}"); + } + catch (OperationCanceledException) + { + // 服务停止,正常 + } + catch (Exception ex) + { + hikStatus.Available = false; + hikStatus.LastError = ex.Message; + AppLog.Write($"[agent] 取流自检失败(扫码不受影响):{ex.Message}"); + } + }, CancellationToken.None); + AppLog.Write($"[agent] 扫码已启动:{scan.Channels.Count} 个通道" + $"(SN {config.DeviceSn},主体 {config.SubjectId})"); @@ -313,7 +349,7 @@ public static class AgentHost // ⑦ 状态:内容变化才写,30 秒没变化保活写一次(避免每 2 秒重写文件) { - var status = BuildStatus(scan, device, config, ntp); + var status = BuildStatus(scan, device, config, ntp, hikStatus); status.TokenExpiresAt = JwtUtil.Expiry(settings.DeviceToken); status.RefreshTokenExpiresAt = AgentFiles.LoadToken()?.RefreshExpiresAt; status.LastTokenRefreshAt = lastTokenRefreshAt; @@ -339,7 +375,7 @@ public static class AgentHost scan.Stop(); device.StopUploadLoop(); - AgentFiles.SaveStatus(BuildStatus(scan, device, config, ntp, running: false)); + AgentFiles.SaveStatus(BuildStatus(scan, device, config, ntp, hikStatus, running: false)); AppLog.Write("[agent] 扫码链路已停止"); } } @@ -417,7 +453,7 @@ public static class AgentHost } private static AgentStatus BuildStatus(ScanService scan, DeviceService device, AgentConfig config, - NtpState ntp, bool running = true) + NtpState ntp, AgentHikStatus hik, bool running = true) { return new AgentStatus { @@ -437,6 +473,7 @@ public static class AgentHost LastCodeAt = channel.LastCodeAt, }).ToList(), LastError = ntp.Error, + Hik = hik, NtpLastSyncAt = ntp.LastSyncAt, NtpLastOffsetSeconds = ntp.OffsetSeconds, NtpRoundTripMs = ntp.RoundTripMs, @@ -444,6 +481,35 @@ public static class AgentHost }; } + /// 把 worker 自检结果落到状态里(失败只标记不可用,不影响扫码) + private static void ApplyHikProbe(AgentHikStatus status, JsonElement? probe) + { + if (probe is not { } element || element.ValueKind != JsonValueKind.Object) + { + status.Available = false; + return; + } + + status.Available = element.TryGetProperty("sdkFound", out var found) + && found.ValueKind == JsonValueKind.True; + status.SdkDir = ReadString(element, "sdkDir"); + status.FfmpegPath = ReadString(element, "ffmpegPath"); + + var root = ReadString(element, "videoRoot"); + if (!string.IsNullOrWhiteSpace(root)) status.VideoRoot = root; + + status.ProbedAt = DateTime.Now; + if (!status.Available) + { + status.LastError ??= "未找到 HCNetSDK.dll(服务目录 native\\HCNetSDK 缺失)"; + } + } + + private static string? ReadString(JsonElement element, string name) + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; + private static void SaveDiscovered(ScanService scan) { var devices = scan.DiscoveredDevices diff --git a/desktop/Services/Agent/EdgeDownloadTasks.cs b/desktop/Services/Agent/EdgeDownloadTasks.cs new file mode 100644 index 0000000..c14b04e --- /dev/null +++ b/desktop/Services/Agent/EdgeDownloadTasks.cs @@ -0,0 +1,175 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace YuncangTrace.LocalService.Services; + +/// +/// 一次「跨网取流」任务(服务端临时产物)。 +/// +/// 生命周期刻意做得**很短**:下载合成 → 等查询机来取 → 取完立即删。 +/// 现场机器常年不清理磁盘,如果只"下载不删",几个月的录像能把 C 盘吃满。 +/// +public sealed class EdgeDownloadTask +{ + public string Id { get; init; } = ""; + public string Code { get; init; } = ""; + public DateTime CreatedAt { get; init; } = DateTime.UtcNow; + + /// queued / running / done / failed + public string State { get; set; } = "queued"; + + /// 最近一条进度(给查询机展示,不保证实时) + public string? Progress { get; set; } + + /// 成片路径(done 时才有) + public string? FilePath { get; set; } + + /// 成片大小(字节) + public long Size { get; set; } + + public string? Error { get; set; } + + public DateTime? FinishedAt { get; set; } + + /// 被查询机取走的时间(取走后在下一次清理里删除) + public DateTime? DeliveredAt { get; set; } +} + +/// +/// 任务表 + 临时文件清理。 +/// +/// 清理规则(都在这一个地方,避免散落): +/// - done 但 10 分钟没被取 → 删; +/// - 已被取走(DeliveredAt)→ 立刻删; +/// - failed / queued 超过 15 分钟 → 删; +/// - running 不动(由执行方自己收尾)。 +/// +public sealed class EdgeDownloadTasks +{ + private static readonly TimeSpan DoneTtl = TimeSpan.FromMinutes(10); + private static readonly TimeSpan FailedTtl = TimeSpan.FromMinutes(15); + + private readonly ConcurrentDictionary _tasks = new(StringComparer.OrdinalIgnoreCase); + private readonly string _root; + + public EdgeDownloadTasks(string root) + { + _root = root; + } + + public EdgeDownloadTask Create(string code) + { + var task = new EdgeDownloadTask + { + Id = Guid.NewGuid().ToString("N"), + Code = code, + }; + _tasks[task.Id] = task; + return task; + } + + public EdgeDownloadTask? Get(string id) + => !string.IsNullOrWhiteSpace(id) && _tasks.TryGetValue(id, out var task) ? task : null; + + public string WorkDirectory(string id) => Path.Combine(_root, ".edge-tasks", id); + + public void Finish(EdgeDownloadTask task, string filePath) + { + task.FilePath = filePath; + task.Size = TryGetSize(filePath); + task.State = "done"; + task.FinishedAt = DateTime.UtcNow; + } + + public void Fail(EdgeDownloadTask task, string error) + { + task.Error = error; + task.State = "failed"; + task.FinishedAt = DateTime.UtcNow; + } + + /// 查询机把文件取走之后调用:立刻释放磁盘 + public void Delivered(EdgeDownloadTask task) + { + task.DeliveredAt = DateTime.UtcNow; + Remove(task.Id); + } + + public void Remove(string id) + { + if (!_tasks.TryRemove(id, out var task)) return; + + TryDeleteDirectory(WorkDirectory(id)); + + // 单路时不走工作目录(直接落在 root 下),这里兜底删文件 + if (!string.IsNullOrEmpty(task.FilePath)) + { + try + { + var dir = Path.GetDirectoryName(task.FilePath); + if (!string.IsNullOrEmpty(dir) + && dir.StartsWith(Path.Combine(_root, ".edge-tasks"), StringComparison.OrdinalIgnoreCase)) + { + TryDeleteDirectory(dir); + } + else if (File.Exists(task.FilePath)) + { + File.Delete(task.FilePath); + } + } + catch (Exception ex) + { + AppLog.Write($"[edge] 删除临时文件失败:{ex.Message}"); + } + } + } + + /// 定时清理(由 worker 每分钟调用一次) + public void Cleanup() + { + var now = DateTime.UtcNow; + + foreach (var task in _tasks.Values.ToList()) + { + var expired = task.State switch + { + "done" => task.DeliveredAt is not null + || (task.FinishedAt is { } finished && now - finished > DoneTtl), + "failed" => task.FinishedAt is { } failed && now - failed > FailedTtl, + "queued" => now - task.CreatedAt > FailedTtl, + _ => false, + }; + + if (expired) Remove(task.Id); + } + } + + private static long TryGetSize(string path) + { + try + { + return File.Exists(path) ? new FileInfo(path).Length : 0; + } + catch + { + return 0; + } + } + + private static void TryDeleteDirectory(string dir) + { + try + { + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + } + catch (Exception ex) + { + AppLog.Write($"[edge] 清理目录失败({dir}):{ex.Message}"); + } + } +} diff --git a/desktop/Services/Agent/EdgeHttpService.cs b/desktop/Services/Agent/EdgeHttpService.cs new file mode 100644 index 0000000..809c770 --- /dev/null +++ b/desktop/Services/Agent/EdgeHttpService.cs @@ -0,0 +1,532 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace YuncangTrace.LocalService.Services; + +/// +/// 取流服务对外提供的极简 HTTP 接口(TCP )。 +/// +/// 端点: +/// +/// GET /health —— 连通性 + 身份(同 LAN 判定就靠它) +/// POST /probe —— 我这台机器能不能连到指定 NVR(查询机据此决定要不要把活派过来) +/// POST /download —— 下发下载计划,立即返回 taskId(后台执行) +/// GET /download/{id} —— 查进度 / 结果 +/// GET /download/{id}/file —— 取成片,**传完立即删除** +/// +/// +/// 为什么不用 HttpListener:绑定非 localhost 需要 urlacl(安装时要多一步提权操作), +/// 而这几个端点的报文都很简单,直接 TcpListener + 手写 HTTP 更可控。 +/// +public sealed class EdgeHttpService +{ + /// 单次下载请求体的上限(流计划带几十个通道也远小于它) + private const int MaxBodyBytes = 4 * 1024 * 1024; + + /// 探测 NVR 的超时 + private static readonly TimeSpan ProbeTimeout = TimeSpan.FromMilliseconds(800); + + private readonly EdgeDownloadTasks _tasks; + private readonly SemaphoreSlim _downloadGate; + private readonly Func _subjectGuard; + + /// 主体校验:返回 false 直接 403(避免跨主体取流) + public EdgeHttpService(EdgeDownloadTasks tasks, SemaphoreSlim downloadGate, Func subjectGuard) + { + _tasks = tasks; + _downloadGate = downloadGate; + _subjectGuard = subjectGuard; + } + + public async Task RunAsync(PlaybackDownloadService download, CancellationToken ct) + { + TcpListener listener; + try + { + listener = new TcpListener(IPAddress.Any, HikWorkerPorts.Http); + listener.Start(); + } + catch (Exception ex) + { + AppLog.Write($"[edge] 取流端口 {HikWorkerPorts.Http} 监听失败(跨网取流不可用):{ex.Message}"); + return; + } + + AppLog.Write($"[edge] 取流接口已就绪:TCP {HikWorkerPorts.Http}"); + + // 每分钟清理一次过期临时文件 + _ = Task.Run(async () => + { + while (!ct.IsCancellationRequested) + { + try + { + await Task.Delay(TimeSpan.FromMinutes(1), ct).ConfigureAwait(false); + _tasks.Cleanup(); + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + AppLog.Write($"[edge] 清理任务异常:{ex.Message}"); + } + } + }, CancellationToken.None); + + try + { + while (!ct.IsCancellationRequested) + { + TcpClient client; + try + { + client = await listener.AcceptTcpClientAsync(ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + AppLog.Write($"[edge] 接受连接失败(继续):{ex.Message}"); + continue; + } + + _ = Task.Run(() => HandleAsync(client, download, ct), CancellationToken.None); + } + } + finally + { + try + { + listener.Stop(); + } + catch + { + // 忽略 + } + } + } + + private sealed record HttpRequest(string Method, string Path, Dictionary Headers, byte[] Body); + + private async Task HandleAsync(TcpClient client, PlaybackDownloadService download, CancellationToken ct) + { + try + { + using (client) + using (var stream = client.GetStream()) + using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct)) + { + timeout.CancelAfter(TimeSpan.FromMinutes(5)); + + var request = await ReadRequestAsync(stream, timeout.Token).ConfigureAwait(false); + if (request is null) return; + + await RouteAsync(stream, request, download, timeout.Token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + // 超时/取消:不记日志(探测连接本来就短) + } + catch (Exception ex) + { + AppLog.Write($"[edge] 请求处理失败:{ex.Message}"); + } + } + + private async Task RouteAsync(Stream stream, HttpRequest request, PlaybackDownloadService download, + CancellationToken ct) + { + var path = request.Path.Split('?')[0]; + + if (path.Equals("/health", StringComparison.OrdinalIgnoreCase)) + { + var config = AgentFiles.LoadConfig(); + await WriteJsonAsync(stream, 200, "OK", new + { + ok = true, + service = "yuncang-edge", + sn = config?.DeviceSn, + subjectId = config?.SubjectId, + port = HikWorkerPorts.Http, + }, ct).ConfigureAwait(false); + return; + } + + // 除 health 外都要校验主体 + if (!CheckSubject(request, out var subjectError)) + { + await WriteJsonAsync(stream, 403, "Forbidden", new { ok = false, error = subjectError }, ct) + .ConfigureAwait(false); + return; + } + + if (path.Equals("/probe", StringComparison.OrdinalIgnoreCase) + && request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + await HandleProbeAsync(stream, request, ct).ConfigureAwait(false); + return; + } + + if (path.Equals("/download", StringComparison.OrdinalIgnoreCase) + && request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + await HandleDownloadAsync(stream, request, download, ct).ConfigureAwait(false); + return; + } + + if (path.StartsWith("/download/", StringComparison.OrdinalIgnoreCase) + && request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + var rest = path["/download/".Length..]; + var isFile = rest.EndsWith("/file", StringComparison.OrdinalIgnoreCase); + var id = isFile ? rest[..^"/file".Length] : rest; + + var task = _tasks.Get(id); + if (task is null) + { + await WriteJsonAsync(stream, 404, "Not Found", new { ok = false, error = "任务不存在或已过期" }, ct) + .ConfigureAwait(false); + return; + } + + if (isFile) + { + await WriteFileAsync(stream, task, ct).ConfigureAwait(false); + return; + } + + await WriteJsonAsync(stream, 200, "OK", new + { + ok = true, + taskId = task.Id, + state = task.State, + progress = task.Progress, + size = task.Size, + error = task.Error, + }, ct).ConfigureAwait(false); + return; + } + + await WriteJsonAsync(stream, 404, "Not Found", new { ok = false, error = "未知接口" }, ct) + .ConfigureAwait(false); + } + + /// 主体校验:优先看请求头,缺省按"不允许"处理 + private bool CheckSubject(HttpRequest request, out string error) + { + error = ""; + + if (!request.Headers.TryGetValue("x-edge-subject", out var raw) || !int.TryParse(raw, out var subjectId)) + { + error = "缺少 X-Edge-Subject"; + return false; + } + + if (!_subjectGuard(subjectId)) + { + error = "主体不匹配"; + return false; + } + + return true; + } + + private static async Task HandleProbeAsync(Stream stream, HttpRequest request, CancellationToken ct) + { + string host; + int port = 8000; + + try + { + using var doc = JsonDocument.Parse(request.Body); + host = doc.RootElement.TryGetProperty("nvrHost", out var h) ? h.GetString() ?? "" : ""; + if (doc.RootElement.TryGetProperty("nvrPort", out var p) && p.TryGetInt32(out var parsed)) port = parsed; + } + catch + { + await WriteJsonAsync(stream, 400, "Bad Request", new { ok = false, error = "请求体不是合法 JSON" }, ct) + .ConfigureAwait(false); + return; + } + + if (string.IsNullOrWhiteSpace(host) || port is <= 0 or > 65535) + { + await WriteJsonAsync(stream, 400, "Bad Request", new { ok = false, error = "nvrHost/nvrPort 不合法" }, ct) + .ConfigureAwait(false); + return; + } + + var sw = Stopwatch.StartNew(); + var reachable = false; + try + { + using var tcp = new TcpClient(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(ProbeTimeout); + await tcp.ConnectAsync(host, port, timeout.Token).ConfigureAwait(false); + reachable = tcp.Connected; + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + reachable = false; + } + catch (Exception) + { + reachable = false; + } + + await WriteJsonAsync(stream, 200, "OK", new + { + ok = true, + reachable, + latencyMs = sw.ElapsedMilliseconds, + }, ct).ConfigureAwait(false); + } + + private async Task HandleDownloadAsync(Stream stream, HttpRequest request, PlaybackDownloadService download, + CancellationToken ct) + { + string code; + List streams; + Dictionary credentials; + DateTime scanTime; + + try + { + using var doc = JsonDocument.Parse(request.Body); + var root = doc.RootElement; + + code = root.TryGetProperty("code", out var c) ? c.GetString() ?? "" : ""; + if (code.Length == 0) throw new InvalidOperationException("缺少运单号"); + + streams = root.TryGetProperty("streams", out var s) + ? s.Deserialize>(HikWorkerJson.Options) ?? new List() + : new List(); + if (streams.Count == 0) throw new InvalidOperationException("缺少 streams"); + + credentials = new Dictionary(); + if (root.TryGetProperty("credentials", out var cr) && cr.ValueKind == JsonValueKind.Array) + { + foreach (var item in cr.EnumerateArray()) + { + var id = item.TryGetProperty("nvrId", out var idElement) ? idElement.GetInt32() : 0; + if (id <= 0) continue; + + credentials[id] = new NvrCredential( + id, + ReadString(item, "name") ?? "", + ReadString(item, "host") ?? "", + item.TryGetProperty("port", out var portElement) ? portElement.GetInt32() : 8000, + ReadString(item, "username") ?? "", + ReadString(item, "password") ?? ""); + } + } + + var missing = streams.Select(item => item.NvrId).Distinct() + .Where(id => !credentials.ContainsKey(id)).ToList(); + if (missing.Count > 0) throw new InvalidOperationException($"缺少录像机凭据:{string.Join("、", missing)}"); + + scanTime = root.TryGetProperty("scanTime", out var st) && st.TryGetDateTimeOffset(out var parsed) + ? parsed.LocalDateTime + : streams[0].StartTime.LocalDateTime; + } + catch (Exception ex) + { + await WriteJsonAsync(stream, 400, "Bad Request", new { ok = false, error = ex.Message }, ct) + .ConfigureAwait(false); + return; + } + + var task = _tasks.Create(code); + var workDir = _tasks.WorkDirectory(task.Id); + + // 后台执行:接口立刻返回,查询机轮询 /download/{id} + _ = Task.Run(async () => + { + try + { + task.State = "running"; + task.Progress = "开始下载"; + AppLog.Write($"[edge] 任务 {task.Id} 开始:{code},{streams.Count} 路"); + + await _downloadGate.WaitAsync(CancellationToken.None).ConfigureAwait(false); + try + { + var result = await download.DownloadByPlanAsync( + code, + streams, + scanTime, + workDir, + (nvrId, _) => Task.FromResult(credentials[nvrId]), + new Progress(text => task.Progress = text), + CancellationToken.None).ConfigureAwait(false); + + var file = result.Merged + ?? result.Segments.FirstOrDefault(); + if (string.IsNullOrEmpty(file) || !File.Exists(file)) + { + _tasks.Fail(task, "下载完成但没有生成成片"); + AppLog.Write($"[edge] 任务 {task.Id} 失败:没有生成成片"); + return; + } + + _tasks.Finish(task, file); + AppLog.Write($"[edge] 任务 {task.Id} 完成:{file}({task.Size / 1024 / 1024} MB),等待查询机取走"); + } + finally + { + _downloadGate.Release(); + } + } + catch (Exception ex) + { + _tasks.Fail(task, ex.Message); + AppLog.Write($"[edge] 任务 {task.Id} 失败:{ex.Message}"); + } + }, CancellationToken.None); + + await WriteJsonAsync(stream, 200, "OK", new { ok = true, taskId = task.Id }, ct).ConfigureAwait(false); + } + + /// 流式返回成片;**写完立即删除**,查询机那边才负责落盘 + private async Task WriteFileAsync(Stream stream, EdgeDownloadTask task, CancellationToken ct) + { + if (task.State != "done" || string.IsNullOrEmpty(task.FilePath) || !File.Exists(task.FilePath)) + { + await WriteJsonAsync(stream, 409, "Conflict", new { ok = false, error = "任务还没完成", state = task.State }, ct) + .ConfigureAwait(false); + return; + } + + var fileInfo = new FileInfo(task.FilePath); + var name = Path.GetFileName(task.FilePath); + + var header = "HTTP/1.1 200 OK\r\n" + + "Content-Type: video/mp4\r\n" + + $"Content-Length: {fileInfo.Length}\r\n" + + $"Content-Disposition: attachment; filename=\"{Uri.EscapeDataString(name)}\"\r\n" + + "Connection: close\r\n\r\n"; + + await stream.WriteAsync(Encoding.UTF8.GetBytes(header), ct).ConfigureAwait(false); + + try + { + using var file = File.OpenRead(task.FilePath); + await file.CopyToAsync(stream, 81920, ct).ConfigureAwait(false); + await stream.FlushAsync(ct).ConfigureAwait(false); + } + finally + { + // 无论传完还是中途断开,都释放磁盘:现场机器不会有人来打扫 + _tasks.Delivered(task); + AppLog.Write($"[edge] 任务 {task.Id} 已投递并清理"); + } + } + + private static async Task WriteJsonAsync(Stream stream, int status, string reason, object payload, + CancellationToken ct) + { + var body = JsonSerializer.SerializeToUtf8Bytes(payload, HikWorkerJson.Options); + var header = $"HTTP/1.1 {status} {reason}\r\n" + + "Content-Type: application/json; charset=utf-8\r\n" + + $"Content-Length: {body.Length}\r\n" + + "Connection: close\r\n\r\n"; + + await stream.WriteAsync(Encoding.UTF8.GetBytes(header), ct).ConfigureAwait(false); + await stream.WriteAsync(body, ct).ConfigureAwait(false); + await stream.FlushAsync(ct).ConfigureAwait(false); + } + + /// 读一个 HTTP 请求(只支持 Content-Length,够我们这些端点用) + private static async Task ReadRequestAsync(Stream stream, CancellationToken ct) + { + var buffer = new MemoryStream(); + var chunk = new byte[4096]; + var headerEnd = -1; + + while (headerEnd < 0 && buffer.Length < 64 * 1024) + { + var read = await stream.ReadAsync(chunk, ct).ConfigureAwait(false); + if (read == 0) return null; + + buffer.Write(chunk, 0, read); + headerEnd = FindHeaderEnd(buffer.GetBuffer(), (int)buffer.Length); + } + + if (headerEnd < 0) return null; + + var all = buffer.GetBuffer(); + var headerText = Encoding.UTF8.GetString(all, 0, headerEnd); + var lines = headerText.Split("\r\n", StringSplitOptions.None); + if (lines.Length == 0) return null; + + var requestLine = lines[0].Split(' '); + if (requestLine.Length < 2) return null; + + var method = requestLine[0]; + var path = requestLine[1]; + + var headers = new Dictionary(StringComparer.OrdinalIgnoreCase); + for (var i = 1; i < lines.Length; i++) + { + var index = lines[i].IndexOf(':'); + if (index <= 0) continue; + headers[lines[i][..index].Trim()] = lines[i][(index + 1)..].Trim(); + } + + var contentLength = headers.TryGetValue("Content-Length", out var raw) + && int.TryParse(raw, out var parsed) + ? parsed + : 0; + + if (contentLength is < 0 or > MaxBodyBytes) return null; + + var bodyStart = headerEnd + 4; + var body = new byte[contentLength]; + var available = (int)buffer.Length - bodyStart; + if (available > 0) Array.Copy(all, bodyStart, body, 0, Math.Min(available, contentLength)); + + var remaining = contentLength - Math.Min(available, contentLength); + var offset = Math.Min(available, contentLength); + while (remaining > 0) + { + var read = await stream.ReadAsync(body.AsMemory(offset, remaining), ct).ConfigureAwait(false); + if (read == 0) break; + offset += read; + remaining -= read; + } + + return new HttpRequest(method, path, headers, body); + } + + private static int FindHeaderEnd(byte[] buffer, int length) + { + for (var i = 0; i + 3 < length; i++) + { + if (buffer[i] == '\r' && buffer[i + 1] == '\n' && buffer[i + 2] == '\r' && buffer[i + 3] == '\n') + { + return i; + } + } + return -1; + } + + private static string? ReadString(JsonElement element, string name) + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; +} diff --git a/desktop/Services/Agent/HikWorker.cs b/desktop/Services/Agent/HikWorker.cs new file mode 100644 index 0000000..7a3c74e --- /dev/null +++ b/desktop/Services/Agent/HikWorker.cs @@ -0,0 +1,473 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Pipes; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using YuncangTrace.LocalService.Services.Hik; + +namespace YuncangTrace.LocalService.Services; + +/// +/// 海康取流的**隔离子进程**(--hik-worker)。 +/// +/// 只有它加载 HCNetSDK 并持有 NVR 会话池( 的 _sessions); +/// 扫码服务主进程通过命名管道派任务。这样 SDK 崩掉只会杀掉本进程, +/// 重启即可恢复,收码/上报完全不受影响。 +/// +/// ⚠️ 跑在 Session 0(LocalSystem):没有桌面,PlayM4 渲染窗口之类的功能永远不在这里做。 +/// +public static class HikWorker +{ + /// worker 入口;返回进程退出码 + public static async Task RunAsync(CancellationToken ct) + { + AgentPaths.MachineMode = true; + AgentPaths.IsServiceProcess = true; + AppLog.Write($"[hik-worker] 启动,目录 {AppContext.BaseDirectory}"); + + using var hik = new HikDeviceService(); + using var playback = new HikPlaybackService(hik); + // 服务端不查库(没有用户令牌),只用到 DownloadByPlanAsync + var download = new PlaybackDownloadService( + new OrderQueryService(), + playback, + () => null, + () => 0, + () => null, + () => AgentPaths.VideosRoot); + + // 一次只执行一份计划:避免多个大任务互抢带宽与 ffmpeg CPU,排队交给上层 + using var downloadGate = new SemaphoreSlim(1, 1); + var state = new WorkerState { Download = download, Gate = downloadGate }; + + // 取流接口 + 局域网发现。两个任务都吞异常只记日志 —— + // 发现/取流坏掉不能影响扫码(那是主进程的事,本来就不在这里)。 + var edgeTasks = new EdgeDownloadTasks(AgentPaths.VideosRoot); + var edgeHttp = new EdgeHttpService(edgeTasks, downloadGate, + subjectId => AgentFiles.LoadConfig() is { } config && config.SubjectId == subjectId && subjectId > 0); + + _ = Task.Run(() => RunLanResponderAsync(ct), CancellationToken.None); + _ = Task.Run(() => edgeHttp.RunAsync(download, ct), CancellationToken.None); + + try + { + while (!ct.IsCancellationRequested) + { + NamedPipeServerStream pipe; + try + { + pipe = new NamedPipeServerStream( + HikWorkerPipe.PipeName, + PipeDirection.InOut, + NamedPipeServerStream.MaxAllowedServerInstances, + PipeTransmissionMode.Byte, + PipeOptions.Asynchronous); + } + catch (Exception ex) + { + // 管道建不起来通常是被占用/权限问题:等一会再来,不能退出 + AppLog.Write($"[hik-worker] 创建管道失败(3 秒后重试):{ex.Message}"); + if (!await DelayAsync(TimeSpan.FromSeconds(3), ct).ConfigureAwait(false)) break; + continue; + } + + await using (pipe) + { + try + { + await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false); + await ServeAsync(pipe, state, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + AppLog.Write($"[hik-worker] 会话异常(继续等待新连接):{ex.Message}"); + } + } + + if (state.ShutdownRequested) break; + } + } + finally + { + AppLog.Write("[hik-worker] 退出"); + } + + return 0; + } + + private sealed class WorkerState + { + public PlaybackDownloadService Download { get; init; } = null!; + public SemaphoreSlim Gate { get; init; } = null!; + public bool ShutdownRequested { get; set; } + } + + /// 处理一条连接上的请求(串行,够用:任务本身由上层排队) + private static async Task ServeAsync(Stream pipe, WorkerState state, CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + var request = await HikWorkerPipe.ReadAsync(pipe, ct).ConfigureAwait(false); + if (request is null) return; // 对端关闭 + + var response = await HandleAsync(request, state, ct).ConfigureAwait(false); + await HikWorkerPipe.WriteAsync(pipe, response, ct).ConfigureAwait(false); + + if (state.ShutdownRequested) return; + } + } + + private static async Task HandleAsync(HikWorkerRequest request, WorkerState state, + CancellationToken ct) + { + try + { + switch (request.Op) + { + case HikWorkerOps.Probe: + return Ok(request, Probe()); + + case HikWorkerOps.Shutdown: + state.ShutdownRequested = true; + return Ok(request, new { message = "worker 正在退出" }); + + case HikWorkerOps.Download: + return await DownloadAsync(request, state, ct).ConfigureAwait(false); + + default: + return Fail(request, $"未知操作:{request.Op}"); + } + } + catch (OperationCanceledException) + { + return Fail(request, "任务已取消"); + } + catch (Exception ex) + { + AppLog.Write($"[hik-worker] {request.Op} 失败:{ex.Message}"); + return Fail(request, ex.Message); + } + } + + /// 自检:SDK 与 ffmpeg 是否就位、录像根目录(不触发 NET_DVR_Init,避免探测本身把进程搞崩) + private static object Probe() + { + var sdkDirs = new[] + { + Environment.GetEnvironmentVariable("YUNCANG_HIKSDK_DIR"), + Path.Combine(AppContext.BaseDirectory, "native", "HCNetSDK"), + Path.Combine(AppContext.BaseDirectory, "native"), + Path.Combine(AppContext.BaseDirectory, "HCNetSDK"), + }; + + var sdkDir = sdkDirs.FirstOrDefault(dir => + !string.IsNullOrWhiteSpace(dir) && File.Exists(Path.Combine(dir, "HCNetSDK.dll"))); + + return new + { + version = typeof(HikWorker).Assembly.GetName().Version?.ToString() ?? "1.0.0", + baseDir = AppContext.BaseDirectory, + sdkFound = sdkDir is not null, + sdkDir, + ffmpegPath = HikFfmpegService.ResolveFfmpeg(), + videoRoot = AgentPaths.VideosRoot, + }; + } + + private static async Task DownloadAsync(HikWorkerRequest request, WorkerState state, + CancellationToken ct) + { + if (request.Payload is not { ValueKind: JsonValueKind.Object } payload) + { + return Fail(request, "缺少任务参数"); + } + + var code = GetString(payload, "code") ?? ""; + if (code.Length == 0) return Fail(request, "缺少运单号"); + + if (!payload.TryGetProperty("streams", out var streamsElement) || streamsElement.ValueKind != JsonValueKind.Array) + { + return Fail(request, "缺少 streams"); + } + + var streams = new List(); + foreach (var item in streamsElement.EnumerateArray()) + { + var stream = item.Deserialize(HikWorkerJson.Options); + if (stream is not null) streams.Add(stream); + } + if (streams.Count == 0) return Fail(request, "streams 为空"); + + var credentials = new Dictionary(); + if (payload.TryGetProperty("credentials", out var credentialsElement) + && credentialsElement.ValueKind == JsonValueKind.Array) + { + foreach (var item in credentialsElement.EnumerateArray()) + { + var id = item.TryGetProperty("nvrId", out var idElement) ? idElement.GetInt32() : 0; + if (id <= 0) continue; + + credentials[id] = new NvrCredential( + id, + GetString(item, "name") ?? "", + GetString(item, "host") ?? "", + item.TryGetProperty("port", out var portElement) ? portElement.GetInt32() : 8000, + GetString(item, "username") ?? "", + GetString(item, "password") ?? ""); + } + } + + var scanTime = payload.TryGetProperty("scanTime", out var scanElement) + && scanElement.TryGetDateTimeOffset(out var parsed) + ? parsed.LocalDateTime + : streams[0].StartTime.LocalDateTime; + + var rootDir = GetString(payload, "rootDir"); + if (string.IsNullOrWhiteSpace(rootDir)) rootDir = AgentPaths.VideosRoot; + + // 缺凭据直接报错:下载阶段才发现会让用户白等 + var missing = streams.Select(item => item.NvrId).Distinct() + .Where(id => !credentials.ContainsKey(id)).ToList(); + if (missing.Count > 0) + { + return Fail(request, $"缺少录像机凭据:{string.Join("、", missing)}"); + } + + await state.Gate.WaitAsync(ct).ConfigureAwait(false); + try + { + AppLog.Write($"[hik-worker] 开始下载 {code}:{streams.Count} 路 → {rootDir}"); + + var result = await state.Download.DownloadByPlanAsync( + code, + streams, + scanTime, + rootDir!, + (nvrId, _) => Task.FromResult(credentials[nvrId]), + progress: null, + ct).ConfigureAwait(false); + + AppLog.Write($"[hik-worker] 下载完成 {code}:{result.Merged ?? result.Segments.FirstOrDefault() ?? result.Folder}"); + + return Ok(request, new + { + folder = result.Folder, + merged = result.Merged, + segments = result.Segments, + warnings = result.Warnings, + }); + } + finally + { + state.Gate.Release(); + } + } + + private static HikWorkerResponse Ok(HikWorkerRequest request, object data) + { + var element = JsonSerializer.SerializeToElement(data, HikWorkerJson.Options); + return new HikWorkerResponse(request.Id, true, null, element); + } + + private static HikWorkerResponse Fail(HikWorkerRequest request, string error) + => new(request.Id, false, error, null); + + private static string? GetString(JsonElement element, string name) + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; + + /// + /// 收局域网广播询问并单播应答(**询问-应答**,worker 从不主动公告)。 + /// + /// 只回「同一主体」的询问:主体不一致直接忽略,避免跨租户发现。 + /// 应答里的 就是桌面端要探测的取流端口。 + /// + private static async Task RunLanResponderAsync(CancellationToken ct) + { + UdpClient? udp = null; + try + { + udp = new UdpClient(new IPEndPoint(IPAddress.Any, HikWorkerPorts.UdpQuery)) + { + EnableBroadcast = true, + }; + } + catch (Exception ex) + { + AppLog.Write($"[hik-worker] 局域网应答无法监听 UDP {HikWorkerPorts.UdpQuery}(该功能停用):{ex.Message}"); + udp?.Dispose(); + return; + } + + using (udp) + { + AppLog.Write($"[hik-worker] 局域网应答已就绪:UDP {HikWorkerPorts.UdpQuery} → HTTP {HikWorkerPorts.Http}"); + + while (!ct.IsCancellationRequested) + { + UdpReceiveResult received; + try + { + received = await udp.ReceiveAsync(ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + AppLog.Write($"[hik-worker] 广播接收失败(继续):{ex.Message}"); + continue; + } + + try + { + if (!TryParseQuery(received.Buffer, out var wantedSubject, out var targets)) continue; + + var config = AgentFiles.LoadConfig(); + if (config is null || config.SubjectId <= 0) continue; + if (wantedSubject != config.SubjectId) continue; + + // 询问里带了 NVR:先实测本机能不能连上,连不上就不应答 + // (让查询机继续走「本机直连 NVR」,而不是把活派给一条走不通的路) + var reachable = new List(); + if (targets.Count > 0) + { + var results = await Task.WhenAll(targets.Select(item => ProbeAsync(item.Host, item.Port, ct))) + .ConfigureAwait(false); + + for (var i = 0; i < targets.Count; i++) + { + if (results[i]) reachable.Add(targets[i].Host); + } + + if (reachable.Count == 0) + { + AppLog.Write($"[hik-worker] 询问的 NVR 均不可达({string.Join("、", targets.Select(t => t.Host))}),不应答"); + continue; + } + } + + var reply = JsonSerializer.Serialize(new + { + type = HikWorkerDiscovery.ReplyType, + sn = config.DeviceSn, + subjectId = config.SubjectId, + port = HikWorkerPorts.Http, + reachable, + version = typeof(HikWorker).Assembly.GetName().Version?.ToString() ?? "1.0.0", + }, HikWorkerJson.Options); + + var bytes = Encoding.UTF8.GetBytes(reply); + await udp.SendAsync(bytes, received.RemoteEndPoint, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + AppLog.Write($"[hik-worker] 广播应答失败:{ex.Message}"); + } + } + } + } + + private sealed record NvrProbeTarget(string Host, int Port); + + /// + /// 解析询问报文。可选带 nvrHosts: [{host, port}] —— 带了就要先实测可达性再应答。 + /// + private static bool TryParseQuery(byte[] buffer, out int subjectId, out List targets) + { + subjectId = 0; + targets = new List(); + + var text = Encoding.UTF8.GetString(buffer).TrimStart(); + if (text.Length == 0 || text[0] != '{') return false; + + try + { + using var doc = JsonDocument.Parse(text); + var root = doc.RootElement; + if (!root.TryGetProperty("type", out var type) || type.GetString() != HikWorkerDiscovery.QueryType) + { + return false; + } + + // 不带 subjectId 的询问一律不答(宁可让对端走本机,也不跨主体泄露) + if (!root.TryGetProperty("subjectId", out var wanted) || !wanted.TryGetInt32(out subjectId)) + { + return false; + } + + if (root.TryGetProperty("nvrHosts", out var hostsElement) && hostsElement.ValueKind == JsonValueKind.Array) + { + foreach (var item in hostsElement.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.Object) continue; + + var host = GetString(item, "host"); + if (string.IsNullOrWhiteSpace(host)) continue; + + var port = item.TryGetProperty("port", out var portElement) && portElement.TryGetInt32(out var parsed) + ? parsed + : 8000; + + targets.Add(new NvrProbeTarget(host, port)); + } + } + + return subjectId > 0; + } + catch + { + return false; + } + } + + /// 探测 NVR 端口(只判能不能连上,不发任何设备协议) + private static async Task ProbeAsync(string host, int port, CancellationToken ct) + { + try + { + using var tcp = new TcpClient(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromMilliseconds(800)); + await tcp.ConnectAsync(host, port, timeout.Token).ConfigureAwait(false); + return tcp.Connected; + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + return false; + } + catch + { + return false; + } + } + + private static async Task DelayAsync(TimeSpan delay, CancellationToken ct) + { + try + { + await Task.Delay(delay, ct).ConfigureAwait(false); + return true; + } + catch (OperationCanceledException) + { + return false; + } + } +} diff --git a/desktop/Services/Agent/HikWorkerProtocol.cs b/desktop/Services/Agent/HikWorkerProtocol.cs new file mode 100644 index 0000000..83daf93 --- /dev/null +++ b/desktop/Services/Agent/HikWorkerProtocol.cs @@ -0,0 +1,130 @@ +using System; +using System.Buffers.Binary; +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace YuncangTrace.LocalService.Services; + +/// +/// 服务主进程 ↔ --hik-worker 子进程的管道协议。 +/// +/// 为什么单独开子进程跑海康:HCNetSDK 是原生库,**访问越界会直接杀掉进程** +/// (0xC0000005),放主进程里等于把扫码收码/上报一起带走。 +/// 隔离后 worker 崩了只需重启它,扫码链路无感。 +/// +/// 传输格式:[4 字节小端长度][UTF-8 JSON]。 +/// 选命名管道而不是本机端口:不占端口、管道断开即知对端已死、ACL 天然限制访问者。 +/// +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); + } +} + +/// worker 的响应; 由调用方按 自行反序列化 +public sealed record HikWorkerResponse(string Id, bool Ok, string? Error, JsonElement? Data); + +/// 管道消息的读写(长度前缀 + JSON),两端共用 +public static class HikWorkerPipe +{ + /// 管道名(服务单实例,固定名即可) + public const string PipeName = "YuncangTrace.HikWorker"; + + /// 单条消息上限(流计划带十几个通道也远小于这个值) + private const int MaxMessageBytes = 8 * 1024 * 1024; + + public static async Task WriteAsync(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); + } + + /// 读一条消息;对端正常关闭返回 null + public static async Task ReadAsync(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(buffer, HikWorkerJson.Options); + } + + private static async Task 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; + } +} + +/// 统一的序列化选项(两端必须一致,否则时间/枚举会解析出偏差) +public static class HikWorkerJson +{ + public static readonly JsonSerializerOptions Options = new() + { + PropertyNameCaseInsensitive = true, + // 中文警告/错误直接可读,不转 \uXXXX + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; +} + +/// worker 支持的操作名(两端共用,避免拼错) +public static class HikWorkerOps +{ + /// 自检:返回 SDK / ffmpeg 是否就绪、录像根目录 + public const string Probe = "probe"; + + /// 按流计划下载并合并 + public const string Download = "download"; + + /// 优雅退出 + public const string Shutdown = "shutdown"; +} + +/// +/// 局域网发现用的端口(与 17300/17301 同族,但独立进程独立端口)。 +/// +/// - :收桌面端的广播询问(**询问-应答**,不是主动公告); +/// - :取流健康端点,桌面端用一次 TCP 连接就能判定"是否同 LAN"。 +/// +public static class HikWorkerPorts +{ + public const int UdpQuery = 17310; + public const int Http = 17311; +} + +/// 局域网询问/应答的报文(两端共用) +public static class HikWorkerDiscovery +{ + public const string QueryType = "edge.query"; + public const string ReplyType = "edge.reply"; +} + diff --git a/desktop/Services/Agent/HikWorkerSupervisor.cs b/desktop/Services/Agent/HikWorkerSupervisor.cs new file mode 100644 index 0000000..e83d809 --- /dev/null +++ b/desktop/Services/Agent/HikWorkerSupervisor.cs @@ -0,0 +1,380 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.IO.Pipes; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace YuncangTrace.LocalService.Services; + +/// +/// 主进程这一侧的 worker 管理:拉起、连接、转发任务、崩溃熔断。 +/// +/// 设计取舍: +/// - **懒启动**:第一个取流任务来才拉起 worker,空闲时零开销; +/// - **进程级隔离**:worker 崩了只影响取流,扫码/上报不受影响(这是它存在的唯一理由); +/// - **熔断**:如果某个视频一解码就崩,没有熔断会陷入"重启—崩溃"死循环把 CPU 打满。 +/// +public sealed class HikWorkerSupervisor : IAsyncDisposable +{ + /// 熔断窗口与阈值(窗口内崩够次数就停自动重启) + private static readonly TimeSpan CrashWindow = TimeSpan.FromMinutes(5); + private const int CrashLimit = 3; + private static readonly TimeSpan BlockedDuration = TimeSpan.FromMinutes(10); + + private readonly object _lifecycleGate = new(); + private readonly SemaphoreSlim _connectLock = new(1, 1); + private readonly SemaphoreSlim _writeLock = new(1, 1); + private readonly ConcurrentDictionary> _pending = new(); + private readonly Queue _crashes = new(); + + private Process? _process; + private NamedPipeClientStream? _pipe; + private CancellationTokenSource? _readCts; + private Task? _readLoop; + private bool _disposing; + private DateTime _blockedUntil = DateTime.MinValue; + + /// worker 状态变化(供 agent-status.json 更新) + public event Action? StateChanged; + + public bool IsConnected => _pipe?.IsConnected == true; + + public bool IsBlocked => DateTime.UtcNow < _blockedUntil; + + public DateTime? BlockedUntil => IsBlocked ? _blockedUntil : null; + + public int CrashCount + { + get { lock (_lifecycleGate) return _crashes.Count; } + } + + public string? LastError { get; private set; } + + /// 自检:SDK / ffmpeg 是否就位(失败不影响扫码) + public async Task ProbeAsync(CancellationToken ct = default) + => await SendAsync(HikWorkerOps.Probe, null, ct).ConfigureAwait(false); + + /// 派发一份下载计划 + /// 包含 code / streams / credentials / scanTime / rootDir + public async Task DownloadAsync(object payload, CancellationToken ct = default) + => await SendAsync(HikWorkerOps.Download, payload, ct).ConfigureAwait(false); + + private async Task SendAsync(string op, object? payload, CancellationToken ct) + { + await EnsureConnectedAsync(ct).ConfigureAwait(false); + + var pipe = _pipe ?? throw new InvalidOperationException("hik-worker 未连接"); + var request = HikWorkerRequest.Create(op, payload); + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pending[request.Id] = completion; + + try + { + await _writeLock.WaitAsync(ct).ConfigureAwait(false); + try + { + await HikWorkerPipe.WriteAsync(pipe, request, ct).ConfigureAwait(false); + } + finally + { + _writeLock.Release(); + } + + var response = await completion.Task.WaitAsync(ct).ConfigureAwait(false); + if (!response.Ok) throw new InvalidOperationException(response.Error ?? "hik-worker 执行失败"); + return response.Data; + } + finally + { + _pending.TryRemove(request.Id, out _); + } + } + + /// 确保 worker 已拉起且管道已连接(失败会抛出可直接展示的原因) + private async Task EnsureConnectedAsync(CancellationToken ct) + { + if (IsConnected) return; + + if (IsBlocked) + { + throw new InvalidOperationException( + $"取流服务连续崩溃已暂停({_blockedUntil:HH:mm:ss} 后自动重试):{LastError}"); + } + + await _connectLock.WaitAsync(ct).ConfigureAwait(false); + try + { + if (IsConnected) return; + if (IsBlocked) throw new InvalidOperationException($"取流服务连续崩溃已暂停:{LastError}"); + + StartProcess(); + var pipe = await ConnectPipeAsync(ct).ConfigureAwait(false); + + _pipe = pipe; + _readCts = new CancellationTokenSource(); + _readLoop = Task.Run(() => ReadLoopAsync(pipe, _readCts.Token), CancellationToken.None); + + AppLog.Write("[hik-worker] 已连接"); + StateChanged?.Invoke(); + } + catch (Exception ex) + { + KillProcess(); + RecordFailure(ex.Message); + throw; + } + finally + { + _connectLock.Release(); + } + } + + private void StartProcess() + { + var existing = _process; + if (existing is not null && !existing.HasExited) return; + + existing?.Dispose(); + _process = null; + + var exe = Environment.ProcessPath + ?? throw new InvalidOperationException("取不到当前程序路径,无法启动取流进程"); + + var info = new ProcessStartInfo(exe, "--hik-worker") + { + UseShellExecute = false, + CreateNoWindow = true, + WorkingDirectory = Path.GetDirectoryName(exe) ?? AppContext.BaseDirectory, + RedirectStandardError = true, + RedirectStandardOutput = true, + }; + + var process = new Process { StartInfo = info, EnableRaisingEvents = true }; + process.Exited += (_, _) => OnWorkerGone($"进程退出(code={(TryGetExitCode(process)?.ToString() ?? "?")})"); + process.ErrorDataReceived += (_, e) => + { + if (!string.IsNullOrWhiteSpace(e.Data)) AppLog.Write($"[hik-worker:stderr] {e.Data}"); + }; + process.OutputDataReceived += (_, e) => + { + if (!string.IsNullOrWhiteSpace(e.Data)) AppLog.Write($"[hik-worker:stdout] {e.Data}"); + }; + + process.Start(); + // 必须有读事件订阅,否则重定向缓冲填满会阻塞子进程 + process.BeginErrorReadLine(); + process.BeginOutputReadLine(); + + _process = process; + AppLog.Write($"[hik-worker] 已拉起(pid={process.Id})"); + } + + private static int? TryGetExitCode(Process process) + { + try + { + return process.ExitCode; + } + catch + { + return null; + } + } + + private async Task ConnectPipeAsync(CancellationToken ct) + { + Exception? last = null; + + // worker 从启动到管道可用通常 < 500ms;给到 6 秒足够覆盖冷启动与磁盘慢的情况 + for (var attempt = 0; attempt < 30; attempt++) + { + ct.ThrowIfCancellationRequested(); + + if (_process is { HasExited: true }) + { + throw new InvalidOperationException( + $"取流进程启动后立即退出(code={TryGetExitCode(_process)?.ToString() ?? "?"})," + + "多半是缺 HCNetSDK 或 native 目录未复制到服务目录"); + } + + var pipe = new NamedPipeClientStream(".", HikWorkerPipe.PipeName, + PipeDirection.InOut, PipeOptions.Asynchronous); + try + { + await pipe.ConnectAsync(200, ct).ConfigureAwait(false); + return pipe; + } + catch (OperationCanceledException) + { + pipe.Dispose(); + throw; + } + catch (Exception ex) + { + pipe.Dispose(); + last = ex; + await Task.Delay(200, ct).ConfigureAwait(false); + } + } + + throw new TimeoutException($"连接取流进程超时:{last?.Message}"); + } + + /// 读循环:把响应按 Id 交回对应请求;断开即视为 worker 已死 + private async Task ReadLoopAsync(Stream pipe, CancellationToken ct) + { + var reason = "连接已关闭"; + try + { + while (!ct.IsCancellationRequested) + { + var response = await HikWorkerPipe.ReadAsync(pipe, ct).ConfigureAwait(false); + if (response is null) break; + + if (_pending.TryRemove(response.Id, out var completion)) + { + completion.TrySetResult(response); + } + } + } + catch (OperationCanceledException) + { + return; + } + catch (Exception ex) + { + reason = ex.Message; + } + + if (_disposing) return; + OnWorkerGone(reason); + } + + private void OnWorkerGone(string reason) + { + if (_disposing) return; + + CleanupConnection(); + KillProcess(); + RecordFailure(reason); + } + + /// 记一次失败并判断是否熔断(进程退出和启动失败走同一套阈值) + private void RecordFailure(string reason) + { + lock (_lifecycleGate) + { + if (_disposing) return; + + LastError = reason; + + var now = DateTime.UtcNow; + _crashes.Enqueue(now); + while (_crashes.Count > 0 && now - _crashes.Peek() > CrashWindow) _crashes.Dequeue(); + + if (_crashes.Count >= CrashLimit) + { + _blockedUntil = now.Add(BlockedDuration); + AppLog.Write($"[hik-worker] {CrashWindow.TotalMinutes:0} 分钟内失败 {_crashes.Count} 次 → " + + $"熔断 {BlockedDuration.TotalMinutes:0} 分钟(扫码不受影响):{reason}"); + } + else + { + AppLog.Write($"[hik-worker] 失败({reason}),下次任务到来时重试"); + } + } + + StateChanged?.Invoke(); + } + + private void CleanupConnection() + { + // 断开连接前先把挂起的请求全部失败掉,避免调用方一直等 + foreach (var (_, completion) in _pending) + { + completion.TrySetException(new IOException("取流进程已退出")); + } + _pending.Clear(); + + try + { + _readCts?.Cancel(); + } + catch + { + // 忽略 + } + + _readCts?.Dispose(); + _readCts = null; + _readLoop = null; + + try + { + _pipe?.Dispose(); + } + catch + { + // 忽略 + } + + _pipe = null; + } + + private void KillProcess() + { + var process = _process; + _process = null; + if (process is null) return; + + try + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + process.WaitForExit(3000); + } + } + catch (Exception ex) + { + AppLog.Write($"[hik-worker] 结束进程失败:{ex.Message}"); + } + finally + { + process.Dispose(); + } + } + + public async ValueTask DisposeAsync() + { + lock (_lifecycleGate) + { + if (_disposing) return; + _disposing = true; + } + + // 先请求优雅退出(让 worker 有机会收尾),失败再强杀 + if (IsConnected) + { + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2)); + await SendAsync(HikWorkerOps.Shutdown, null, timeout.Token).ConfigureAwait(false); + } + catch + { + // 忽略:下面还会 Kill + } + } + + CleanupConnection(); + KillProcess(); + + _connectLock.Dispose(); + _writeLock.Dispose(); + } +} diff --git a/desktop/Services/Agent/ServiceInstaller.cs b/desktop/Services/Agent/ServiceInstaller.cs index c5e09c4..b66c6f3 100644 --- a/desktop/Services/Agent/ServiceInstaller.cs +++ b/desktop/Services/Agent/ServiceInstaller.cs @@ -226,6 +226,10 @@ public static class ServiceInstaller } if (copyError is not null) return Fail($"复制后台服务程序失败:{copyError.Message}"); + // 局域网发现端口:不放开的话同 LAN 的桌面端根本探测不到本机, + // 「共用一套 NVR 会话池」就永远走不到内网这条路。 + EnsureFirewallRules(); + var binPath = $"\"{AgentPaths.AgentExe}\" --service"; if (!IsInstalled) @@ -350,10 +354,41 @@ public static class ServiceInstaller TryDelete(file); } TryDeleteDirectory(AgentPaths.AgentDir); + RemoveFirewallRules(); return new HelperResult { Ok = true, Message = "后台服务已卸载" }; } + /// + /// 放行局域网发现端口(TCP 取流健康端点 + UDP 询问应答)。 + /// + /// 只对**域/专用网络**放行:公用网络(咖啡厅 WiFi)不暴露这些端口。 + /// 现场若把办公网识别成「公用」,需要手动改成「专用」或加同名规则。 + /// + private static void EnsureFirewallRules() + { + AddFirewallRule("YuncangTrace Edge (TCP 17311)", "TCP", "17311"); + AddFirewallRule("YuncangTrace Edge (UDP 17310)", "UDP", "17310"); + } + + private static void AddFirewallRule(string name, string protocol, string port) + { + // 已存在就静默覆盖(delete + add 比判断是否存在简单可靠) + RunTool("netsh.exe", "advfirewall", "firewall", "delete", "rule", $"name={name}"); + var result = RunTool("netsh.exe", "advfirewall", "firewall", "add", "rule", + $"name={name}", "dir=in", "action=allow", $"protocol={protocol}", $"localport={port}", + "profile=domain,private"); + if (result.Code != 0) AppLog.Write($"[agent] 添加防火墙规则失败({name}):{result.Output}"); + } + + private static void RemoveFirewallRules() + { + foreach (var name in new[] { "YuncangTrace Edge (TCP 17311)", "YuncangTrace Edge (UDP 17310)" }) + { + RunTool("netsh.exe", "advfirewall", "firewall", "delete", "rule", $"name={name}"); + } + } + private static HelperResult StartCore() { if (!IsInstalled) return Fail("服务未安装"); @@ -389,8 +424,10 @@ public static class ServiceInstaller /// /// 把当前程序复制到 ProgramData 作为服务副本。 - /// 单文件发布只复制一个 exe;开发环境(framework-dependent)连 dll/json 一起复制, - /// 但不复制 native(服务不跑 ffmpeg / 海康 SDK)。 + /// + /// 单文件发布只复制 exe;开发环境(framework-dependent)连 dll/json 一起复制。 + /// **native 运行库(HCNetSDK / ffmpeg)两种模式都要复制** —— + /// 取流由 --hik-worker 子进程执行,缺它就直接不可用。 /// private static void CopyAgentFiles(string source) { @@ -414,19 +451,60 @@ public static class ServiceInstaller if (singleFile) { File.Copy(source, AgentPaths.AgentExe, overwrite: true); + } + else + { + foreach (var file in Directory.EnumerateFiles(sourceDir)) + { + var extension = Path.GetExtension(file).ToLowerInvariant(); + if (extension is not (".exe" or ".dll" or ".json")) continue; + if (Path.GetFileName(file).Contains("ffmpeg", StringComparison.OrdinalIgnoreCase)) continue; + + File.Copy(file, Path.Combine(AgentPaths.AgentDir, Path.GetFileName(file)), overwrite: true); + } + + if (!File.Exists(AgentPaths.AgentExe)) File.Copy(source, AgentPaths.AgentExe, overwrite: true); + } + + CopyNativeDirectory(sourceDir); + } + + /// + /// 复制 native(HCNetSDK + ffmpeg)到服务副本目录。 + /// + /// ⚠️ 每次**先删后拷**:SDK 的组件文件集合会随版本变化, + /// 残留旧 DLL 会让 HCCore 加载错版本(现象是登录莫名失败)。 + /// + private static void CopyNativeDirectory(string sourceDir) + { + var from = Path.Combine(sourceDir, "native"); + if (!Directory.Exists(from)) + { + AppLog.Write("[agent] 程序目录没有 native(缺 HCNetSDK/ffmpeg):服务取流不可用,扫码不受影响"); return; } - foreach (var file in Directory.EnumerateFiles(sourceDir)) + var to = Path.Combine(AgentPaths.AgentDir, "native"); + try { - var extension = Path.GetExtension(file).ToLowerInvariant(); - if (extension is not (".exe" or ".dll" or ".json")) continue; - if (Path.GetFileName(file).Contains("ffmpeg", StringComparison.OrdinalIgnoreCase)) continue; - - File.Copy(file, Path.Combine(AgentPaths.AgentDir, Path.GetFileName(file)), overwrite: true); + if (Directory.Exists(to)) Directory.Delete(to, recursive: true); + } + catch (Exception ex) + { + AppLog.Write($"[agent] 清空旧 native 失败(继续覆盖写):{ex.Message}"); } - if (!File.Exists(AgentPaths.AgentExe)) File.Copy(source, AgentPaths.AgentExe, overwrite: true); + var count = 0; + foreach (var file in Directory.EnumerateFiles(from, "*", SearchOption.AllDirectories)) + { + var target = Path.Combine(to, Path.GetRelativePath(from, file)); + var dir = Path.GetDirectoryName(target); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.Copy(file, target, overwrite: true); + count++; + } + + AppLog.Write($"[agent] 已复制 native 运行库 {count} 个文件到 {to}"); } // ==================== 状态查询(SCM,无需管理员) ==================== diff --git a/desktop/Services/AgentPaths.cs b/desktop/Services/AgentPaths.cs index 29d07d2..88b994b 100644 --- a/desktop/Services/AgentPaths.cs +++ b/desktop/Services/AgentPaths.cs @@ -63,6 +63,14 @@ public static class AgentPaths /// 服务发现到的设备列表(桌面端「扫码通道」页展示用) public static string DiscoveredFile => Path.Combine(MachineRoot, "agent-discovered.json"); + /// + /// 后台服务的录像成片根目录(`C:\ProgramData\YuncangTrace\video`)。 + /// + /// 服务进程没有用户桌面、也读不到用户的「录像根目录」设置, + /// 所以跨网下载由 worker 落到这里;桌面端要取用时按同一路径访问。 + /// + public static string VideosRoot => Path.Combine(MachineRoot, "video"); + /// /// 开启服务模式时把用户目录里已有的通道/扫码记录搬到 ProgramData(**不覆盖已有文件**)。 /// diff --git a/desktop/Services/Edge/EdgeClient.cs b/desktop/Services/Edge/EdgeClient.cs new file mode 100644 index 0000000..a5e155c --- /dev/null +++ b/desktop/Services/Edge/EdgeClient.cs @@ -0,0 +1,175 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace YuncangTrace.LocalService.Services.Edge; + +/// 取流任务的当前状态 +public sealed record EdgeTaskStatus(string TaskId, string State, string? Progress, long Size, string? Error) +{ + public bool IsDone => string.Equals(State, "done", StringComparison.OrdinalIgnoreCase); + + public bool IsFailed => string.Equals(State, "failed", StringComparison.OrdinalIgnoreCase); +} + +/// 探测某台 NVR 从取流服务那边能不能连上 +public sealed record EdgeProbeResult(bool Reachable, long LatencyMs); + +/// +/// 取流服务的 HTTP 客户端(查询机这一侧)。 +/// +/// 所有请求都带 X-Edge-Subject:取流服务只服务同一主体,别的请求一律 403。 +/// +public sealed class EdgeClient : IDisposable +{ + /// 下载大文件可能要几分钟,超时交给 CancellationToken 控制 + private static readonly HttpClient Http = new() { Timeout = Timeout.InfiniteTimeSpan }; + + private readonly string _baseUrl; + private readonly int _subjectId; + + public EdgeClient(EdgePeer peer) + : this(peer.BaseUrl, peer.SubjectId) + { + } + + public EdgeClient(string baseUrl, int subjectId) + { + _baseUrl = baseUrl.TrimEnd('/'); + _subjectId = subjectId; + } + + /// 本机(取流服务那台)能不能连到指定 NVR + public async Task ProbeAsync(string nvrHost, int nvrPort, CancellationToken ct = default) + { + using var response = await SendAsync(HttpMethod.Post, "/probe", + new { nvrHost, nvrPort }, ct).ConfigureAwait(false); + + if (!response.IsSuccessStatusCode) return null; + + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false)); + var root = doc.RootElement; + + var reachable = root.TryGetProperty("reachable", out var value) && value.ValueKind == JsonValueKind.True; + var latency = root.TryGetProperty("latencyMs", out var ms) && ms.TryGetInt64(out var parsed) ? parsed : 0; + return new EdgeProbeResult(reachable, latency); + } + + /// 下发下载计划,返回任务 id(服务端后台执行) + public async Task CreateDownloadAsync(string code, + IReadOnlyList streams, + IReadOnlyList credentials, + DateTime scanTime, + CancellationToken ct = default) + { + var payload = new + { + code, + scanTime = new DateTimeOffset(scanTime).ToString("O"), + streams, + credentials = BuildCredentialPayload(credentials), + }; + + using var response = await SendAsync(HttpMethod.Post, "/download", payload, ct).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) return null; + + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false)); + return doc.RootElement.TryGetProperty("taskId", out var value) ? value.GetString() : null; + } + + public async Task GetStatusAsync(string taskId, CancellationToken ct = default) + { + using var response = await SendAsync(HttpMethod.Get, $"/download/{taskId}", null, ct).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) return null; + + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false)); + var root = doc.RootElement; + + return new EdgeTaskStatus( + GetString(root, "taskId") ?? taskId, + GetString(root, "state") ?? "", + GetString(root, "progress"), + root.TryGetProperty("size", out var size) && size.TryGetInt64(out var parsedSize) ? parsedSize : 0, + GetString(root, "error")); + } + + /// + /// 取成片并写到本机路径。 + /// **服务端在传输完成后立即删除临时文件**,所以这里必须一次成功(失败要重新下发任务)。 + /// + public async Task DownloadFileAsync(string taskId, string savePath, CancellationToken ct = default) + { + using var request = new HttpRequestMessage(HttpMethod.Get, $"{_baseUrl}/download/{taskId}/file"); + request.Headers.TryAddWithoutValidation("X-Edge-Subject", _subjectId.ToString()); + + using var response = await Http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct) + .ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + + var dir = Path.GetDirectoryName(savePath); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + + await using var source = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); + await using var target = File.Create(savePath); + + var buffer = new byte[81920]; + long total = 0; + while (true) + { + var read = await source.ReadAsync(buffer, ct).ConfigureAwait(false); + if (read == 0) break; + await target.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false); + total += read; + } + + await target.FlushAsync(ct).ConfigureAwait(false); + return total; + } + + private Task SendAsync(HttpMethod method, string path, object? payload, + CancellationToken ct) + { + var request = new HttpRequestMessage(method, _baseUrl + path); + request.Headers.TryAddWithoutValidation("X-Edge-Subject", _subjectId.ToString()); + + if (payload is not null) + { + request.Content = JsonContent.Create(payload, options: HikWorkerJson.Options); + } + + return Http.SendAsync(request, ct); + } + + private static object[] BuildCredentialPayload(IReadOnlyList credentials) + { + var list = new List(); + foreach (var item in credentials) + { + list.Add(new + { + nvrId = item.Id, + name = item.Name, + host = item.Host, + port = item.Port, + username = item.Username, + password = item.Password, + }); + } + return list.ToArray(); + } + + private static string? GetString(JsonElement element, string name) + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; + + public void Dispose() + { + // HttpClient 是静态共享的,这里没有需要释放的实例资源 + } +} diff --git a/desktop/Services/Edge/EdgeDiscoveryClient.cs b/desktop/Services/Edge/EdgeDiscoveryClient.cs new file mode 100644 index 0000000..dd5e8e8 --- /dev/null +++ b/desktop/Services/Edge/EdgeDiscoveryClient.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using YuncangTrace.LocalService.Services.Scan; + +namespace YuncangTrace.LocalService.Services.Edge; + +/// 局域网里发现到的一台「取流服务」(即扫码服务拉起的 hik-worker)。 +/// 设备序列号(与 scanners.sn 对应,用于去重与排障) +/// 这次询问里它实测能连通的 NVR 主机(空 = 没带 NVR 询问) +public sealed record EdgePeer( + string Sn, + string Host, + int Port, + int SubjectId, + IReadOnlyList Reachable, + string Version) +{ + public string BaseUrl => $"http://{Host}:{Port}"; + + public string Display => $"{Sn}({Host}:{Port})"; +} + +/// +/// 局域网询问-应答的客户端(查询机这一侧)。 +/// +/// **只问不喊**:发一次广播询问,在同 socket 上收应答 —— 这样回包的源地址天然就是 +/// 「从哪块网卡能到它」,多网卡机器不用自己猜用哪个 IP。 +/// +/// 询问可以带 nvrHosts:对面的服务会先实测能不能连到这些 NVR, +/// 连不上就不应答。所以「收到应答」= 对端确实能替你取流,而不是单纯在线。 +/// +public static class EdgeDiscoveryClient +{ + /// 带 NVR 时给对端留出探测时间(对端最多 800ms 探测) + private static readonly TimeSpan ProbeWait = TimeSpan.FromSeconds(3); + + /// 不带 NVR 时只需等应答返回 + private static readonly TimeSpan QuickWait = TimeSpan.FromSeconds(1); + + /// + /// 找一台能处理这些 NVR 的取流服务。 + /// + /// 当前主体(对端只回同主体的询问) + /// 要问的 NVR(host/port);传空表示只问「有没有服务」 + /// 多台应答时取第一台(同一 LAN 通常只有一台) + public static async Task FindAsync(int subjectId, + IReadOnlyList<(string Host, int Port)>? nvrs, + CancellationToken ct = default) + { + if (subjectId <= 0) return null; + + using var udp = new UdpClient(AddressFamily.InterNetwork); + udp.EnableBroadcast = true; + + var payload = BuildQuery(subjectId, nvrs); + var bytes = Encoding.UTF8.GetBytes(payload); + + foreach (var target in DeviceScanner.BroadcastTargets()) + { + try + { + await udp.SendAsync(bytes, bytes.Length, new IPEndPoint(target, HikWorkerPorts.UdpQuery)) + .WaitAsync(ct).ConfigureAwait(false); + } + catch (Exception ex) + { + AppLog.Write($"[edge] 广播到 {target} 失败:{ex.Message}"); + } + } + + var wait = nvrs is { Count: > 0 } ? ProbeWait : QuickWait; + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(wait); + + var peers = new List(); + + while (!timeout.IsCancellationRequested) + { + UdpReceiveResult received; + try + { + received = await udp.ReceiveAsync(timeout.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + AppLog.Write($"[edge] 接收应答失败:{ex.Message}"); + break; + } + + var peer = TryParseReply(received.Buffer, received.RemoteEndPoint.Address, subjectId); + if (peer is null) continue; + + // 带了 NVR 询问时,对端必须确认能连通其中至少一台(它已经自己筛过,这里再兜一层) + if (nvrs is { Count: > 0 } && !HasAnyReachable(peer, nvrs)) continue; + + peers.Add(peer); + } + + if (peers.Count == 0) return null; + + return peers.OrderBy(item => item.Sn, StringComparer.Ordinal).First(); + } + + private static bool HasAnyReachable(EdgePeer peer, IReadOnlyList<(string Host, int Port)> nvrs) + { + if (peer.Reachable.Count == 0) return false; + + var set = new HashSet(peer.Reachable, StringComparer.OrdinalIgnoreCase); + return nvrs.Any(item => set.Contains(item.Host)); + } + + private static string BuildQuery(int subjectId, IReadOnlyList<(string Host, int Port)>? nvrs) + { + if (nvrs is not { Count: > 0 }) + { + return JsonSerializer.Serialize(new + { + type = HikWorkerDiscovery.QueryType, + subjectId, + }, HikWorkerJson.Options); + } + + return JsonSerializer.Serialize(new + { + type = HikWorkerDiscovery.QueryType, + subjectId, + nvrHosts = nvrs.Select(item => new { host = item.Host, port = item.Port }).ToArray(), + }, HikWorkerJson.Options); + } + + private static EdgePeer? TryParseReply(byte[] buffer, IPAddress from, int expectedSubject) + { + try + { + var text = Encoding.UTF8.GetString(buffer).TrimStart(); + if (text.Length == 0 || text[0] != '{') return null; + + using var doc = JsonDocument.Parse(text); + var root = doc.RootElement; + + if (!root.TryGetProperty("type", out var type) || type.GetString() != HikWorkerDiscovery.ReplyType) + { + return null; + } + + // 应答必须同主体:防止同 LAN 里别的主体广播回来 + if (!root.TryGetProperty("subjectId", out var subjectElement) + || !subjectElement.TryGetInt32(out var subjectId) + || subjectId != expectedSubject) + { + return null; + } + + var port = root.TryGetProperty("port", out var portElement) && portElement.TryGetInt32(out var p) + ? p + : HikWorkerPorts.Http; + + var reachable = new List(); + if (root.TryGetProperty("reachable", out var reachableElement) + && reachableElement.ValueKind == JsonValueKind.Array) + { + foreach (var item in reachableElement.EnumerateArray()) + { + var value = item.GetString(); + if (!string.IsNullOrWhiteSpace(value)) reachable.Add(value); + } + } + + return new EdgePeer( + GetString(root, "sn") ?? "", + from.ToString(), + port, + subjectId, + reachable, + GetString(root, "version") ?? ""); + } + catch + { + return null; + } + } + + private static string? GetString(JsonElement element, string name) + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; +} diff --git a/desktop/Services/PlaybackDownloadService.cs b/desktop/Services/PlaybackDownloadService.cs index c2d30f0..d675e8a 100644 --- a/desktop/Services/PlaybackDownloadService.cs +++ b/desktop/Services/PlaybackDownloadService.cs @@ -2,8 +2,10 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; +using YuncangTrace.LocalService.Services.Edge; using YuncangTrace.LocalService.Services.Hik; namespace YuncangTrace.LocalService.Services; @@ -19,6 +21,14 @@ public sealed record PlaybackDownloadResult( IReadOnlyList Segments, IReadOnlyList Warnings); +/// +/// 按 NVR id 取登录凭据。 +/// +/// 桌面端走用户令牌调后端;后台扫码服务只有设备令牌,走云端下发或本地缓存。 +/// 单独抽成委托,是为了让「按流计划下载」这件事不依赖登录态。 +/// +public delegate Task NvrCredentialProvider(int nvrId, CancellationToken ct); + /// /// 「按运单下载录像」的完整流程(**与界面无关**,桌面端和网页查件都走它) /// @@ -84,8 +94,158 @@ public sealed class PlaybackDownloadService } var scanTime = query.Records[0].ScanTime.LocalDateTime; + + var nvrs = streams + .Select(item => (Host: item.NvrHost, item.NvrPort)) + .Where(item => !string.IsNullOrWhiteSpace(item.Host)) + .Distinct() + .ToList(); + + // 选路:本机能直连 NVR 就自己下(与以前行为完全一致); + // 连不上说明在别的网段 —— 找同主体的取流服务代取,取回来落到本机。 + if (nvrs.Count > 0 && !await CanReachNvrAsync(nvrs[0].Host, nvrs[0].NvrPort, ct).ConfigureAwait(false)) + { + var viaEdge = await TryDownloadViaEdgeAsync(code, streams, scanTime, nvrs, progress, ct) + .ConfigureAwait(false); + + if (viaEdge is not null) return viaEdge; + + progress?.Report("本机连不上录像机,也没有可用的取流服务,尝试直连…"); + } + + return await DownloadByPlanAsync( + code, + streams, + scanTime, + _root(), + FetchCredentialAsync, + progress, + ct).ConfigureAwait(false); + } + + /// 本机能不能连到这台 NVR(只判 TCP,不发设备协议) + private static async Task CanReachNvrAsync(string host, int port, CancellationToken ct) + { + try + { + using var tcp = new TcpClient(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromMilliseconds(600)); + await tcp.ConnectAsync(host, port, timeout.Token).ConfigureAwait(false); + return tcp.Connected; + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + return false; + } + catch + { + return false; + } + } + + /// + /// 跨网路径:广播找同主体的取流服务 → 派任务 → 轮询 → 把成片拉回本机。 + /// + /// 返回 null 表示「没找到/没接单」,调用方继续走本机直连(保持原有失败语义)。 + /// + private async Task TryDownloadViaEdgeAsync( + string code, + IReadOnlyList streams, + DateTime scanTime, + IReadOnlyList<(string Host, int Port)> nvrs, + IProgress? progress, + CancellationToken ct) + { + var subjectId = _subjectId?.Invoke() ?? 0; + if (subjectId <= 0) return null; + + progress?.Report("本机连不上录像机,正在查找取流服务…"); + + var peer = await EdgeDiscoveryClient.FindAsync(subjectId, nvrs, ct).ConfigureAwait(false); + if (peer is null) return null; + + progress?.Report($"已找到取流服务 {peer.Display},正在下发任务…"); + + // 凭据仍从后端取:取流服务那边只有设备令牌,拿不到用户态凭据 + var credentials = new List(); + var seen = new HashSet(); + foreach (var stream in streams) + { + if (!seen.Add(stream.NvrId)) continue; + credentials.Add(await FetchCredentialAsync(stream.NvrId, ct).ConfigureAwait(false)); + } + + using var client = new EdgeClient(peer); + + var taskId = await client.CreateDownloadAsync(code, streams, credentials, scanTime, ct) + .ConfigureAwait(false); + if (string.IsNullOrEmpty(taskId)) + { + progress?.Report("取流服务拒绝了下载任务"); + return null; + } + + progress?.Report("取流服务已接单,等待下载与合并…"); + + var completed = false; + var deadline = DateTime.UtcNow.AddMinutes(15); + while (DateTime.UtcNow < deadline) + { + ct.ThrowIfCancellationRequested(); + + var status = await client.GetStatusAsync(taskId, ct).ConfigureAwait(false); + if (status is null) + { + progress?.Report("取流服务状态查询失败"); + return null; + } + + if (status.IsFailed) throw new InvalidOperationException(status.Error ?? "取流服务下载失败"); + if (status.IsDone) + { + completed = true; + break; + } + + if (!string.IsNullOrEmpty(status.Progress)) progress?.Report(status.Progress); + await Task.Delay(TimeSpan.FromSeconds(2), ct).ConfigureAwait(false); + } + + if (!completed) throw new InvalidOperationException("等待取流服务超时(15 分钟)"); + var folder = VideoStorage.FolderFor(_root(), scanTime); Directory.CreateDirectory(folder); + var target = Path.Combine(folder, $"{Sanitize(code)}_取流_{DateTime.Now:yyyyMMdd_HHmmss}.mp4"); + + progress?.Report("正在接收成片…"); + var size = await client.DownloadFileAsync(taskId, target, ct).ConfigureAwait(false); + progress?.Report($"已保存:{target}({size / 1024.0 / 1024.0:0.0} MB)"); + + return new PlaybackDownloadResult(folder, target, new[] { target }, new List()); + } + + /// + /// 按**流计划**下载并合并(不查库、不依赖用户令牌) + /// + /// 桌面端由 查好计划再调进来; + /// 后台扫码服务只有设备令牌、调不了 `pack-query`,所以直接调这个。 + /// + /// 成片根目录(桌面端用用户设置,服务端用 ProgramData 下的录像目录) + /// 按 NVR id 取凭据(桌面端走 API,服务端走云端下发或本地缓存) + public async Task DownloadByPlanAsync( + string code, + IReadOnlyList streams, + DateTime scanTime, + string rootDir, + NvrCredentialProvider credentialProvider, + IProgress? progress = null, + CancellationToken ct = default) + { + if (streams.Count == 0) throw new InvalidOperationException("没有可下载的流"); + + var folder = VideoStorage.FolderFor(rootDir, scanTime); + Directory.CreateDirectory(folder); var stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); var workDir = Path.Combine(Path.GetTempPath(), "YuncangTrace", "playback", @@ -112,8 +272,8 @@ public sealed class PlaybackDownloadService { progress?.Report($"[{slot + 1}/{streams.Count}] {stream.DisplayName} 连接中…"); - var credential = await CredentialAsync(stream.NvrId, credentials, credentialGate, ct) - .ConfigureAwait(false); + var credential = await CredentialAsync(stream.NvrId, credentials, credentialGate, + credentialProvider, ct).ConfigureAwait(false); var name = $"{Sanitize(code)}_{stream.CameraId}_{stream.CameraName}" + $"_{stream.StartTime.ToLocalTime():yyyyMMdd_HHmmss}.mp4"; @@ -207,18 +367,16 @@ public sealed class PlaybackDownloadService } } + /// 按 NVR id 取凭据并缓存(同一份计划里每个 NVR 只取一次) private async Task CredentialAsync(int nvrId, Dictionary cache, - SemaphoreSlim gate, CancellationToken ct) + SemaphoreSlim gate, NvrCredentialProvider provider, CancellationToken ct) { await gate.WaitAsync(ct).ConfigureAwait(false); try { if (cache.TryGetValue(nvrId, out var cached)) return cached; - var api = _api() ?? throw new InvalidOperationException("本机软件未登录"); - var token = _token() ?? throw new InvalidOperationException("本机软件未登录"); - - var credential = await api.NvrCredentialAsync(token, _subjectId(), nvrId, ct).ConfigureAwait(false); + var credential = await provider(nvrId, ct).ConfigureAwait(false); if (string.IsNullOrEmpty(credential.Password)) { throw new InvalidOperationException( @@ -234,6 +392,14 @@ public sealed class PlaybackDownloadService } } + /// 桌面端默认实现:带用户令牌调后端拿凭据 + private async Task FetchCredentialAsync(int nvrId, CancellationToken ct) + { + var api = _api() ?? throw new InvalidOperationException("本机软件未登录"); + var token = _token() ?? throw new InvalidOperationException("本机软件未登录"); + return await api.NvrCredentialAsync(token, _subjectId(), nvrId, ct).ConfigureAwait(false); + } + private static string Sanitize(string text) { var invalid = Path.GetInvalidFileNameChars(); diff --git a/desktop/Services/Scan/DeviceScanner.cs b/desktop/Services/Scan/DeviceScanner.cs index c5e25ee..e71f837 100644 --- a/desktop/Services/Scan/DeviceScanner.cs +++ b/desktop/Services/Scan/DeviceScanner.cs @@ -233,7 +233,7 @@ public sealed class DeviceScanner } /// 广播目标:255.255.255.255 + 每块网卡的定向广播地址 - private static List BroadcastTargets() + internal static List BroadcastTargets() { var targets = new List { IPAddress.Broadcast };