liufumingren 290f29e547 跨公司取流:云端边缘任务通道 + 三级降级
场景:查询机 A 和打包仓库 B 在不同网络,B 没有公网 IP。
B 只能主动出站,所以云端从不反向连它 —— 复用设备出站链路做任务通道。

云端(backend)
- 新增 edge_task 服务:Redis List 做队列、短 TTL 存结果,
  多实例共享,不依赖 sticky session
- POST /api/scanner/tasks/poll:设备长轮询领任务(挂 20 秒,
  有任务立刻返回,没任务 204)
- POST /api/scanner/tasks/:id/result:设备回结果
- POST /api/web/edge/check:查询机问「这段有没有录像」,
  云端按主体选出在线扫码服务 → 下发 check → 等结果(默认 8 秒)
- 不阻塞共享 Redis 连接:任务用短间隔轮询而非 BLPOP
  (egg-redis 是共享连接,阻塞命令会卡住其它请求)

桌面端(desktop)
- AgentHost 新增边缘任务循环:长轮询领任务 → 交 worker 执行 → 回结果,
  与扫码链路完全解耦,异常只退避重试
- worker 新增 check 能力(复用 HikPlaybackService.CheckAsync)
- ApiClient 长轮询单独用不限时客户端(共享 HttpClient 的 15 秒超时会掐断)

三级降级(桌面端校验)
1. 局域网有设备管理服务 → 交给它(共用 NVR 会话池)
2. 没有 → 问云端;云端确认有录像时**隐藏预览、只显示下载**
   (跨网拉流成本高,短片段/下载更合适)
3. 云端也判断不了 → 本机自己校验(仓库内操作员的常规路径)

实测(真实 NVR 192.168.8.241 通道 34)
  设备心跳 → 领任务 → worker 校验 → 回结果 → 网页拿到结论
  端到端 2.17 秒(其中 NVR 拉流约 2 秒)

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

56 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

'use strict';
const { Controller } = require('egg');
/**
* 设备态:边缘任务通道(**需长期设备 JWT**)
*
* 打包仓库的扫码服务没有公网 IP,只能自己出站来领任务:
* - `POST /api/scanner/tasks/poll?wait=25`:没有任务就挂住,有任务立刻返回;
* - `POST /api/scanner/tasks/:id/result`:回执行结果。
*
* 云端从不主动连设备 —— 这也正是跨公司场景能成立的原因。
*/
class DeviceEdgeController extends Controller {
/**
* 领任务(长轮询)
*
* 返回 204 表示这段时间没有任务,客户端立刻再发起下一次即可。
*/
async poll() {
const { ctx } = this;
const scanner = ctx.state.scanner;
// 上限 25 秒:比心跳间隔短,也能避开大多数反代的读超时(默认 60s)
const wait = Math.min(Math.max(Number(ctx.query.wait) || 25, 1), 25);
const task = await ctx.service.edgeTask.poll(scanner.id, wait * 1000);
if (!task) {
ctx.status = 204;
return;
}
ctx.logger.info('[edge] 设备 %s 领取任务 %s(%s)', scanner.sn, task.id, task.type);
ctx.body = { ok: true, data: task };
}
/**
* 回任务结果
*
* body: `{ ok: true, ... }` 或 `{ ok: false, error: '...' }`
*/
async result() {
const { ctx } = this;
const id = String(ctx.params.id || '').trim();
if (!id) ctx.throw(400, '缺少任务 id');
const body = ctx.request.body || {};
await ctx.service.edgeTask.submitResult(id, body);
ctx.logger.info('[edge] 设备 %s 回任务 %s:ok=%s', ctx.state.scanner.sn, id, body.ok);
ctx.body = { ok: true };
}
}
module.exports = DeviceEdgeController;