fix(agent): 面单识别断流死循环改指数退避 + 后台服务单实例

- label-scan 断流重连从固定 3s 改为 3s 起指数退避到 60s;连上稳定 30s 才清零;
  内存不足(OutOfMemory / Cannot allocate memory)固定等 60s。
  现场 2026-11-18:两路主码流 + 系统提交内存耗尽时,每 3 秒重拉一次 ffmpeg 自己踩自己
- AgentHost 加 Global\YuncangTraceAgent.instance 单实例锁:服务与 --agent-run 双开时
  第二个实例直接退出,不再重复拉流、抢写 agent-status.json、抢 hik-worker 管道
- hik-worker 管道创建失败改为 3→30s 退避重试,连续 12 次失败退出(交给主进程熔断)
- agent-status.json 的「变了就写」判据剔除每帧都变的诊断计数器,不再 2.5 次/秒重写
- scan-records.json 改为共享读 + 原子替换(File.Move),桌面端不再刷「文件被另一个进程占用」
- publish-desktop:releaseNotes 用 node 侧字符串回写 version.json,避免命令行中文乱码

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-19 00:46:05 +08:00
parent cfe318d817
commit 5bd90a45ff
7 changed files with 215 additions and 18 deletions

View File

@ -178,6 +178,14 @@ function main() {
const versionJson = JSON.parse(fs.readFileSync(versionPath, 'utf8'));
// --notes 要穿过 shell/powershell 两层命令行,中文偶尔会被按 GBK 解一遍(上一次发布就是乱码)。
// 这里用 node 里这份(Unicode 一定正确)覆盖写回,保证客户端更新弹窗里的说明不乱码。
if (options.notes && versionJson.releaseNotes !== options.notes) {
versionJson.releaseNotes = options.notes;
fs.writeFileSync(versionPath, JSON.stringify(versionJson, null, 2), 'utf8');
console.log('更新说明已按 UTF-8 重新写入 version.json');
}
// version.json 里有 downloadUrlExe 就必须把 EXE 一起传上去,否则新客户端拿到的是 404
const packages = [];
if (fs.existsSync(msiPath)) packages.push(msiPath);

View File

@ -798,9 +798,10 @@ xstack 只做一遍。实测(本机 i5-12400 + UHD 730,机器同时在跑别
| 安装 / 卸载 | 开启 / 关闭设备服务时用 `runas` 提权(**各弹一次 UAC**),之后日常使用无 UAC |
| 升级 | 新版本启动后检测服务副本版本,提示更新(一次 UAC) |
| 日志 | `%ProgramData%\YuncangTrace\agent\logs\log_*.txt` |
| 日志策略 | 按天一个文件,**自动保留 14 天**;状态文件改为「内容变化才写 + 30 秒保活」(不再每 2 秒重写);面单压着扫码器时同一个码每 5 分钟才记一行 |
| 日志策略 | 按天一个文件,**自动保留 14 天**;状态文件改为「内容变化才写 + 30 秒保活」(每帧都变的诊断计数器不算变化,不再 2.5 次/秒重写);面单压着扫码器时同一个码每 5 分钟才记一行 |
| 手动排障 | `sc query YuncangTraceAgent` / `sc start|stop YuncangTraceAgent` |
| 调试 | `YuncangTrace.LocalService.exe --agent-run`(不经 SCM,直接跑后台循环) |
| 单实例 | `Global\YuncangTraceAgent.instance`:服务/manual 双开会被第二个实例直接拒绝(不重复拉流、不抢写 `agent-status.json`、不抢 hik-worker 管道) |
> **退出登录不会关闭设备服务**:服务模式下只清登录态,设备令牌和 `agent.json` 保留,扫码继续上报。
> 要停止必须走「服务 → 关闭设备服务」。
@ -895,7 +896,8 @@ xstack 只做一遍。实测(本机 i5-12400 + UHD 730,机器同时在跑别
顶部状态行显示 `已拉取 N 路 · 时间`,底部的黄字是服务端提示(例如「摄像头找不到录像机」「录像机没有保存密码」)。
数据来源:服务模式下由**后台服务**拉配置 + 识别,界面读 `agent-status.json` 的 `LabelScan`
(后台服务每 **400ms** 写一轮、界面每 **300ms** 轮询一次,识别到就是几百毫秒内能看到);
(后台服务每 **400ms** 检查一轮状态、**内容变化才写**文件、界面每 **300ms** 轮询一次,识别到就是几百毫秒内能看到;
`FramesRead` / `LastWaitMs` 这类每帧都变的排障计数器不参与「变化即写」的判据,只随 30 秒保活写回去);
普通模式下直接读本进程 `ScanService.LabelScan`。
#### 配置拉取(`LabelScanMonitor`)
@ -945,7 +947,9 @@ ffmpeg(RTSP, tcp) → 灰度 rawvideo 帧 → 读帧线程只留最新一帧(
3. 两个码都在历史里时,上报/续期的是**最后出现的那个**,不是检测器先解出来的那个;
已有的码只更新时间、不重排,避免同框两码每帧互相顶掉导致上报抖动。
- 同一张面单连续命中节流到 500ms 一次:足够维持「在场」状态,又不会刷上报;
- 断流自动重连(3 秒),连续失败按 3/10 次节流打日志;不影响扫码枪链路。
- 断流自动重连:**3 秒起、按 2 的幂退避到 60 秒**,连续失败按 3/10 次节流打日志;
连上后要稳定跑够 30 秒才算恢复(连上就断的话间隔会一直涨,不会每 3 秒重拉一次 ffmpeg);
**内存不足(OutOfMemory / Cannot allocate memory)固定等 60 秒**再试,别在系统已经吃紧时反复申请内存。不影响扫码枪链路。
排障字段(`agent-status.json` 的 `LabelScan.Items[]`):

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
using YuncangTrace.LocalService.Services.Scan;
@ -42,6 +43,16 @@ public static class AgentHost
{
AgentPaths.MachineMode = true;
AgentPaths.IsServiceProcess = true;
// 一台机器只允许一个后台扫码服务:两个实例会同时拉两套面单摄像头(内存/带宽翻倍)、
// 同时写 agent-status.json(后写的撞上「拒绝访问」)、同时抢 hik-worker 命名管道。
using var instanceLock = TryAcquireInstanceLock();
if (instanceLock is null)
{
AppLog.Write("[agent] 已有另一个后台服务实例在运行,本进程直接退出(不重复拉流、不抢写状态文件)");
return;
}
AppLog.Write("[agent] 后台扫码服务启动");
try
@ -99,6 +110,59 @@ public static class AgentHost
private static string Version =>
typeof(AgentHost).Assembly.GetName().Version?.ToString() ?? "1.0.0";
/// <summary>
/// 后台服务单实例锁。
///
/// 服务跑在 Session 0、手动 <c>--agent-run</c> 跑在用户会话,而 <c>Local\</c> 是按会话隔离的
/// (根本抓不到这种"同机双实例"),所以优先用 <c>Global\</c>。
/// 普通用户没有 SeCreateGlobalPrivilege 时会拿不到对象:这时只要服务已安装且在跑,
/// 就同样判定为"已有实例";否则退化成 <c>Local\</c>,至少挡住同一会话内的重复启动。
/// </summary>
private static Mutex? TryAcquireInstanceLock()
{
foreach (var name in new[] { @"Global\YuncangTraceAgent.instance", @"Local\YuncangTraceAgent.instance" })
{
Mutex mutex;
try
{
mutex = new Mutex(initiallyOwned: false, name);
}
catch (UnauthorizedAccessException)
{
if (IsAgentServiceRunning()) return null;
continue;
}
try
{
if (mutex.WaitOne(TimeSpan.Zero)) return mutex;
}
catch (AbandonedMutexException)
{
return mutex; // 上一个实例没释放就退出了:这个锁现在归我们
}
mutex.Dispose();
return null; // 对象建得出来但抢不到 → 确实有实例在跑
}
// 两个命名空间都建不了(极端权限情况):不阻塞启动,交一个空锁占位
return new Mutex();
}
private static bool IsAgentServiceRunning()
{
try
{
using var service = new System.ServiceProcess.ServiceController(ServiceInstaller.ServiceName);
return service.Status != System.ServiceProcess.ServiceControllerStatus.Stopped;
}
catch
{
return false; // 没安装 / 查不到:当作没有
}
}
private static async Task RunCoreAsync(AgentConfig config, CancellationToken ct)
{
// 用内存里的设置喂给 DeviceService:它只用到 DeviceToken / DeviceSn / SubjectId / Enabled
@ -374,7 +438,9 @@ public static class AgentHost
nextNtpAt = DateTime.UtcNow.AddMinutes(Math.Max(config.NtpIntervalMinutes, 5));
}
// ⑦ 状态:内容变化才写,30 秒没变化保活写一次(避免每 2 秒重写文件)
// ⑦ 状态:内容变化才写,30 秒没变化保活写一次。
// 每帧都在变的诊断计数器(FramesRead / LastWaitMs…)不参与比较 ——
// 否则 400ms 一轮里几乎每轮都在重写文件(2.5 次/秒),对现场机械盘是纯磨损。
{
var status = BuildStatus(scan, device, config, ntp, hikStatus);
status.TokenExpiresAt = JwtUtil.Expiry(settings.DeviceToken);
@ -385,7 +451,7 @@ public static class AgentHost
status.LastHeartbeatError = lastHeartbeatError;
status.UpdatedAt = default; // 签名忽略时间戳
var signature = JsonSerializer.Serialize(status);
var signature = StatusSignature(status);
if (signature != lastStatusJson || DateTime.UtcNow - lastStatusWriteAt >= StatusKeepAlive)
{
@ -552,6 +618,47 @@ public static class AgentHost
};
}
/// <summary>
/// 状态文件的「内容签名」:剔掉每帧都变的诊断计数器,只留真正值得立刻让界面看到的变化。
///
/// 400ms 一轮里这些计数器几乎每轮都是新值,参与比较就等于每 400ms 重写一次状态文件
/// (2.5 次/秒、一天二十万次),对现场机械盘毫无意义。诊断字段靠 30 秒保活写回去。
/// </summary>
private static string StatusSignature(AgentStatus status)
{
var node = JsonSerializer.SerializeToNode(status)!.AsObject();
if (node[nameof(AgentStatus.LabelScan)] is JsonObject labelScan
&& labelScan[nameof(AgentLabelScanStatus.Items)] is JsonArray items)
{
foreach (var item in items.OfType<JsonObject>())
{
foreach (var name in VolatileLabelFields) item.Remove(name);
}
}
return node.ToJsonString();
}
/// <summary>面单识别里每帧都会变的排障字段(不参与状态文件的「变了就写」判据)</summary>
private static readonly string[] VolatileLabelFields =
{
nameof(AgentLabelCameraStatus.FramesRead),
nameof(AgentLabelCameraStatus.FrameThrottled),
nameof(AgentLabelCameraStatus.FramesDecoded),
nameof(AgentLabelCameraStatus.LastWaitMs),
nameof(AgentLabelCameraStatus.LastLoopMs),
nameof(AgentLabelCameraStatus.FrameLag),
nameof(AgentLabelCameraStatus.FrameDropped),
nameof(AgentLabelCameraStatus.LastDecodeMs),
nameof(AgentLabelCameraStatus.LastCvMs),
nameof(AgentLabelCameraStatus.LastPath),
nameof(AgentLabelCameraStatus.RoiFailStreak),
nameof(AgentLabelCameraStatus.SteadyHits),
nameof(AgentLabelCameraStatus.RoiText),
nameof(AgentLabelCameraStatus.RoiRatio),
};
/// <summary>
/// 边缘任务循环:长轮询领任务 → 交给 worker 执行 → 回结果。
///

View File

@ -24,6 +24,9 @@ namespace YuncangTrace.LocalService.Services;
/// </summary>
public static class HikWorker
{
/// <summary>管道连续建不起来多少次就退出(约 4~5 分钟,交给主进程的熔断逻辑处理)</summary>
private const int MaxPipeFailures = 12;
/// <summary>worker 入口;返回进程退出码</summary>
public static async Task<int> RunAsync(CancellationToken ct)
{
@ -55,6 +58,7 @@ public static class HikWorker
_ = Task.Run(() => RunLanResponderAsync(ct), CancellationToken.None);
_ = Task.Run(() => edgeHttp.RunAsync(download, playback, ct), CancellationToken.None);
var pipeFailures = 0;
try
{
while (!ct.IsCancellationRequested)
@ -68,12 +72,27 @@ public static class HikWorker
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous);
pipeFailures = 0;
}
catch (Exception ex)
{
// 管道建不起来通常是被占用/权限问题:等一会再来,不能退出
AppLog.Write($"[hik-worker] 创建管道失败(3 秒后重试):{ex.Message}");
if (!await DelayAsync(TimeSpan.FromSeconds(3), ct).ConfigureAwait(false)) break;
// 管道建不起来通常是被占用/权限问题(另一个实例已经用这个管道名,
// 而且它的 ACL 不放行我们)。3 秒一次地重试会永远刷日志,
// 所以逐步退避到 30 秒;一直建不起来就退出,别留一个抢不到管道的空 worker 常驻。
pipeFailures++;
if (pipeFailures >= MaxPipeFailures)
{
AppLog.Write($"[hik-worker] 创建管道连续失败 {pipeFailures} 次,退出:{ex.Message}");
return 3;
}
var seconds = Math.Min(3 * Math.Pow(2, Math.Min(pipeFailures - 1, 4)), 30);
if (pipeFailures <= 3 || pipeFailures % 10 == 0)
{
AppLog.Write($"[hik-worker] 创建管道失败({seconds:0} 秒后重试):{ex.Message}");
}
if (!await DelayAsync(TimeSpan.FromSeconds(seconds), ct).ConfigureAwait(false)) break;
continue;
}

View File

@ -293,7 +293,15 @@ public sealed class LabelScanWorker : IDisposable
internal sealed class LabelCameraRunner
{
private const int ConnectTimeoutMs = 6000;
private const int ReconnectDelayMs = 3000;
/// <summary>断流重连的起始间隔</summary>
private const int MinReconnectDelayMs = 3000;
/// <summary>断流重连的最大间隔(指数退避上限)</summary>
private const int MaxReconnectDelayMs = 60_000;
/// <summary>连上后至少稳定跑这么久才算「恢复正常」,失败计数才清零</summary>
private const long StableStreamMs = 30_000;
/// <summary>
/// 解码帧率:面单放进去会停住,8fps 足够(主码流单帧解码+识别约 15~45ms,吃得下)。
@ -551,6 +559,9 @@ internal sealed class LabelCameraRunner
while (!ct.IsCancellationRequested)
{
Process? process = null;
long connectedAt = 0;
var delayMs = MinReconnectDelayMs;
try
{
SetState("starting", null);
@ -560,9 +571,9 @@ internal sealed class LabelCameraRunner
Runtime.StreamText = stream.Text;
process = StartFfmpeg(stream);
_process = process;
connectedAt = Environment.TickCount64;
SetState("running", null);
if (attempts > 0) AppLog.Write($"[label-scan] {Runtime.Summary} 已重新连上码流({stream.Text})");
attempts = 0;
DecodeLoop(process, stream, ct);
if (ct.IsCancellationRequested) break;
@ -574,12 +585,17 @@ internal sealed class LabelCameraRunner
}
catch (Exception ex)
{
// 只有「连上并稳定跑够 StableStreamMs」才算恢复:连上就断说明故障还在,
// 退避要继续涨,否则每 3 秒拉起一次 ffmpeg / 探测一轮,机器越紧张越缓不过来。
if (connectedAt > 0 && Environment.TickCount64 - connectedAt >= StableStreamMs) attempts = 0;
attempts++;
SetState("error", ex.Message);
delayMs = NextReconnectDelayMs(attempts, ex);
var note = $"(第 {attempts} 次失败,{delayMs / 1000} 秒后重试)";
SetState("error", ex.Message + note);
if (attempts <= 3 || attempts % 10 == 0)
{
AppLog.Write($"[label-scan] {Runtime.Summary} 识别失败({ex.Message}),{ReconnectDelayMs / 1000} 秒后重试"
+ (attempts > 1 ? $";已重试 {attempts} 次" : string.Empty));
AppLog.Write($"[label-scan] {Runtime.Summary} 识别失败({ex.Message}){note}");
}
}
finally
@ -590,7 +606,7 @@ internal sealed class LabelCameraRunner
try
{
await Task.Delay(ReconnectDelayMs, ct).ConfigureAwait(false);
await Task.Delay(delayMs, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@ -601,6 +617,38 @@ internal sealed class LabelCameraRunner
SetState("stopped", null);
}
/// <summary>
/// 断流重连间隔:3 秒起按 2 的幂退避到 60 秒。
///
/// 内存不足时固定按最长间隔等:每次重连都要新建 ffmpeg + 三块整帧缓冲,
/// 内存已经不够时 3 秒重试一次只会把系统按得更死(2026-11-18 现场那次死循环)。
/// </summary>
internal static int NextReconnectDelayMs(int attempts, Exception error)
{
if (IsMemoryPressure(error)) return MaxReconnectDelayMs;
var shift = Math.Min(Math.Max(attempts - 1, 0), 5);
return Math.Min(MinReconnectDelayMs << shift, MaxReconnectDelayMs);
}
private static bool IsMemoryPressure(Exception error)
{
for (Exception? e = error; e is not null; e = e.InnerException)
{
if (e is OutOfMemoryException) return true;
var message = e.Message;
if (message.Contains("Cannot allocate memory", StringComparison.OrdinalIgnoreCase)
|| message.Contains("not enough memory", StringComparison.OrdinalIgnoreCase)
|| message.Contains("内存不足", StringComparison.Ordinal))
{
return true;
}
}
return false;
}
/// <summary>
/// 选码流 + 找到可用的 RTSP 序号 + 拿分辨率。
///

View File

@ -203,7 +203,17 @@ public static class ScanRecordStore
return;
}
var list = JsonSerializer.Deserialize<List<ScanRecordItem>>(File.ReadAllText(FilePath), Options);
// 共享读:服务模式下面单/扫码记录是后台服务在写,桌面端这边读的一瞬间
// 对方正好在替换文件(File.Move 覆盖)也不会失败,更不会误判成「空库」。
string text;
using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete))
using (var reader = new StreamReader(stream))
{
text = reader.ReadToEnd();
}
var list = JsonSerializer.Deserialize<List<ScanRecordItem>>(text, Options);
if (list is null) return;
_items = list.Where(item => !string.IsNullOrWhiteSpace(item.Code)).ToList();
@ -715,8 +725,9 @@ public static class ScanRecordStore
Directory.CreateDirectory(Dir);
var temp = FilePath + ".tmp";
File.WriteAllText(temp, json);
File.Copy(temp, FilePath, overwrite: true);
File.Delete(temp);
// 先写 .tmp 再原子替换:对方(桌面端)正在读的时候也只是看到旧内容,
// 不会撞上「文件被另一个进程占用」;File.Copy 覆盖会拿独占句柄,正是之前刷错的来源。
File.Move(temp, FilePath, overwrite: true);
}
catch (Exception ex)
{

View File

@ -42,7 +42,7 @@
<ServerBaseUrl Condition="'$(Configuration)' == 'Debug' and '$(ServerBaseUrl)' == ''">http://127.0.0.1:7300</ServerBaseUrl>
<ServerBaseUrl Condition="'$(Configuration)' == 'Release' and '$(ServerBaseUrl)' == ''">https://packs.example.com</ServerBaseUrl>
<Version>1.0.162</Version>
<Version>1.0.164</Version>
<Product>云仓视频溯源软件</Product>
<Company>云仓</Company>
<AssemblyTitle>云仓视频溯源软件(本机服务)</AssemblyTitle>