packServer/backend/app/service/edge_task.js
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

252 lines
7.2 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 { Service } = require('egg');
const crypto = require('crypto');
/**
* 云端「边缘任务」通道
*
* 背景:查询机(A)和打包仓库(B)在不同公司/不同网络,B 没有公网 IP。
* 所以**永远由 B 主动出站**领任务,云端从不反向连它 —— 这条通道复用的就是
* 设备心跳那条出站链路(`POST /api/scanner/tasks/poll` 挂住等任务)。
*
* 只做控制面:
* 云端入队 → 设备长轮询领取 → 设备回结果
*
* 队列用 Redis List(多实例共享,天然不依赖 sticky session),
* 结果放短 TTL 的 key,过期即视为「设备没回」。
*/
/** 超过这个时间没心跳就认为设备离线(与心跳间隔 60s 留足余量) */
const SCANNER_ONLINE_MS = 5 * 60 * 1000;
/** 任务与结果的保留时间:任务没人领就丢,结果没人取就丢 */
const TASK_TTL_SECONDS = 180;
const RESULT_TTL_SECONDS = 180;
/** 单次校验最多等多久(设备侧真拉一小段,正常 2~5 秒) */
const DEFAULT_WAIT_MS = 8000;
/** 同一主体最多试几台设备(多仓库时逐个试,连不上 NVR 的会被跳过) */
const MAX_DEVICES = 2;
class EdgeTaskService extends Service {
get redis() {
return this.app.redis;
}
get prefix() {
return (this.config.cache && this.config.cache.prefix) || '';
}
queueKey(scannerId) {
return `${this.prefix}edge:task:${Number(scannerId)}`;
}
resultKey(taskId) {
return `${this.prefix}edge:result:${taskId}`;
}
/**
* 同主体里最近有心跳的扫码服务(可代取的候选,按心跳时间倒序)
* @param {number} subjectId
* @return {Promise<Array>} scanners 原始行
*/
async onlineScanners(subjectId) {
const Scanners = this.app.model.Scanner;
const threshold = new Date(Date.now() - SCANNER_ONLINE_MS);
return Scanners.findAll({
where: {
subjectId: Number(subjectId),
status: 1,
lastSeenAt: { [this.app.Sequelize.Op.gte]: threshold },
},
order: [ [ 'last_seen_at', 'DESC' ] ],
limit: MAX_DEVICES,
raw: true,
});
}
/**
* 入队一个任务
* @param {number} scannerId 目标设备
* @param {string} type 任务类型(check / download)
* @param {object} payload 任务参数
* @return {Promise<object>} 含 id 的任务对象
*/
async enqueue(scannerId, type, payload) {
const task = {
id: crypto.randomUUID(),
type,
payload,
createdAt: new Date().toISOString(),
};
const key = this.queueKey(scannerId);
await this.redis.lpush(key, JSON.stringify(task));
// 队列本身也给个 TTL:设备长期离线时不让任务无限堆积
await this.redis.expire(key, TASK_TTL_SECONDS);
return task;
}
/**
* 设备侧领取任务(长轮询)
*
* ⚠️ 不用 BLPOP:egg-redis 是共享连接,阻塞命令会把其它请求一起卡住。
* 这里用短间隔轮询,代价是一次 task 最多 200ms 的额外延迟,可以接受。
*
* @param {number} scannerId
* @param {number} waitMs 最长挂多久
* @return {Promise<object|null>} 没任务返回 null
*/
async poll(scannerId, waitMs) {
const deadline = Date.now() + Math.max(0, Number(waitMs) || 0);
const key = this.queueKey(scannerId);
for (;;) {
const raw = await this.redis.rpop(key);
if (raw) {
try {
return JSON.parse(raw);
} catch (err) {
this.ctx.logger.warn('[edge] 任务解析失败,丢弃:%s', err.message);
}
}
if (Date.now() >= deadline) return null;
await sleep(200);
}
}
/**
* 设备回结果
* @param {string} taskId
* @param {object} payload { ok, data | error }
*/
async submitResult(taskId, payload) {
const id = String(taskId || '').trim();
if (!id) return false;
await this.redis.setex(this.resultKey(id), RESULT_TTL_SECONDS, JSON.stringify(payload || {}));
return true;
}
/**
* 等结果(调用方是 web 请求,用户正等着)
* @param {string} taskId
* @param {number} timeoutMs
* @return {Promise<object|null>} 超时返回 null
*/
async waitResult(taskId, timeoutMs) {
const key = this.resultKey(taskId);
const deadline = Date.now() + Math.max(0, Number(timeoutMs) || DEFAULT_WAIT_MS);
for (;;) {
const raw = await this.redis.get(key);
if (raw) {
try {
return JSON.parse(raw);
} catch (err) {
return null;
}
}
if (Date.now() >= deadline) return null;
await sleep(150);
}
}
/**
* 问「这段录像有没有帧」
*
* 顺序:本主体在线的扫码服务 → 下发 check → 等结果;连不上 NVR 的换下一台。
*
* @param {object} params
* @param {number} params.subjectId
* @param {string} params.code 运单号
* @param {number} [params.waitMs]
* @return {Promise<object>} 见 controller 的注释
*/
async checkVideo({ subjectId, code, waitMs = DEFAULT_WAIT_MS }) {
const plan = await this.ctx.service.pack.query({ subjectId, code });
const streams = (plan && plan.streams) || [];
// 没有流计划:连"该查哪台 NVR 的哪个通道"都算不出来,无需惊动设备
if (streams.length === 0) {
return { state: 'no-plan', hasVideo: false };
}
const scanners = await this.onlineScanners(subjectId);
if (scanners.length === 0) {
return { state: 'no-device', hasVideo: null };
}
const stream = streams[0];
let credential;
try {
credential = await this.ctx.service.nvr.credentialOf(stream.nvrId, subjectId);
} catch (err) {
return { state: 'no-credential', hasVideo: null, message: err.message };
}
if (!credential.password) {
return { state: 'no-credential', hasVideo: null, message: '录像机没有保存密码' };
}
const payload = {
nvrId: stream.nvrId,
nvrHost: credential.host,
nvrPort: credential.port,
username: credential.username,
password: credential.password,
channelNo: stream.channelNo,
startTime: stream.startTime,
endTime: stream.endTime,
};
const startedAt = Date.now();
let lastError = null;
for (const scanner of scanners) {
let task;
try {
task = await this.enqueue(scanner.id, 'check', payload);
} catch (err) {
lastError = err.message;
continue;
}
const result = await this.waitResult(task.id, waitMs);
if (!result) {
lastError = '设备没有响应';
continue;
}
// 设备明确说连不上(或参数被拒):换下一台试
if (result.ok === false) {
lastError = result.error || '设备执行失败';
continue;
}
return {
state: 'ok',
hasVideo: Boolean(result.hasRecord),
frames: Number(result.frames) || 0,
source: result.source || '',
message: result.error || null,
scannerSn: scanner.sn,
elapsedMs: Date.now() - startedAt,
};
}
return { state: 'no-device', hasVideo: null, message: lastError };
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
module.exports = EdgeTaskService;