- 主体状态缓存(Redis 优先、进程内兜底):设备心跳与上报判断不再查库,续期/停用后主动失效 - 上报写接口按缓存校验期限:过期 403 subject_expired、停用 subject_disabled、主体缺失 subject_missing - 心跳与 /api/scanner/me 返回 subject 状态,桌面端据此暂停推送并在续期后自动补传积压 - 新增续期订单(subject_orders)与接口,支付回调 POST /api/pay/notify 幂等、支持 HMAC 签名, 另提供内部令牌模拟支付用于联调 - 顺带提交工作区中已完成的「登录协议」后端改动(agreement):与本次改动共用 router.js / config.default.js Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
159 lines
6.1 KiB
JavaScript
159 lines
6.1 KiB
JavaScript
'use strict';
|
||
|
||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||
const jwt = require('jsonwebtoken');
|
||
|
||
/** 假实例:update 时把字段同时合并回实例自身 */
|
||
const instance = data => {
|
||
const obj = {
|
||
toJSON: () => data,
|
||
update: async fields => {
|
||
Object.assign(data, fields);
|
||
Object.assign(obj, fields);
|
||
},
|
||
};
|
||
return Object.assign(obj, data);
|
||
};
|
||
|
||
/** 与服务端一致的密钥/签发者,造一个中控(扫描器)JWT */
|
||
function signToken() {
|
||
return jwt.sign(
|
||
{ sub: '1', sn: 'SN-HUB-01', typ: 'scanner', jti: 'jti-1' },
|
||
app.config.jwt.secret,
|
||
{
|
||
algorithm: 'HS256',
|
||
expiresIn: '365d',
|
||
issuer: app.config.jwt.issuer,
|
||
audience: app.config.jwt.audience,
|
||
},
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 设备上报的主体期限限制
|
||
*
|
||
* 重点:
|
||
* - 过期 / 停用 → 写接口 403(`subject_expired` / `subject_disabled`);
|
||
* - 状态读 `service.subjectState` 缓存,**连续请求只查一次库**;
|
||
* - 心跳是探测通道:不因过期返回 403,并返回 `subject.expired` 供设备暂停/恢复;
|
||
* - 续期后失效缓存,下一次请求立即恢复。
|
||
*/
|
||
describe('test/app/controller/subject-expiry.test.js', () => {
|
||
const SUBJECT_ID = 21;
|
||
const token = () => `Bearer ${signToken()}`;
|
||
|
||
const authScanner = () => instance({
|
||
id: 1,
|
||
sn: 'SN-HUB-01',
|
||
status: 1,
|
||
tokenJti: 'jti-1',
|
||
subjectId: SUBJECT_ID,
|
||
userId: 1,
|
||
});
|
||
|
||
const authSubject = expireAt => instance({
|
||
id: SUBJECT_ID,
|
||
name: '测试主体',
|
||
adminUserId: 1,
|
||
status: 1,
|
||
expireAt,
|
||
});
|
||
|
||
beforeEach(() => {
|
||
app.createAnonymousContext().service.subjectState.clearLocalCache();
|
||
});
|
||
|
||
/** 正常入库所需的最小模型集合 */
|
||
function mockModels({ subject, reads }) {
|
||
mock(app, 'model', {
|
||
User: {},
|
||
Scanner: { async findByPk() { return authScanner(); } },
|
||
Subject: {
|
||
async findByPk() {
|
||
if (reads) reads.count++;
|
||
return typeof subject === 'function' ? subject() : subject;
|
||
},
|
||
},
|
||
ScanChannel: {
|
||
async findAll() { return []; },
|
||
async bulkCreate(items) { return items; },
|
||
async update() { return [ 1 ]; },
|
||
},
|
||
ScanRecord: {
|
||
async findAll() { return []; },
|
||
async bulkCreate(items) { return items; },
|
||
},
|
||
});
|
||
}
|
||
|
||
const body = { records: [{ barcode: 'B1', scanTime: '2026-10-20 10:00:00', channelId: '1' }] };
|
||
|
||
it('主体过期:上报 403 subject_expired,且第二次请求命中缓存不再查库', async () => {
|
||
const reads = { count: 0 };
|
||
mockModels({ subject: authSubject(new Date(Date.now() - 60 * 1000)), reads });
|
||
|
||
const first = await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send(body).expect(403);
|
||
assert(first.body.status === 'subject_expired', JSON.stringify(first.body));
|
||
assert(first.body.remainingSeconds === 0);
|
||
assert(reads.count === 1, `首次应查库一次,实际 ${reads.count}`);
|
||
|
||
const second = await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send(body).expect(403);
|
||
assert(second.body.status === 'subject_expired');
|
||
assert(reads.count === 1, `第二次应命中缓存(仍为 1 次),实际 ${reads.count}`);
|
||
});
|
||
|
||
it('主体停用:上报 403 subject_disabled', async () => {
|
||
mockModels({ subject: instance({ id: SUBJECT_ID, name: '停用主体', adminUserId: 1, status: 0, expireAt: new Date(Date.now() + 86400000) }) });
|
||
|
||
const res = await app.httpRequest().post('/api/scan/channels').set('Authorization', token())
|
||
.send({ channels: [{ channelId: 'C1', channelName: '通道一' }] }).expect(403);
|
||
assert(res.body.status === 'subject_disabled', JSON.stringify(res.body));
|
||
});
|
||
|
||
it('主体不存在:上报 403 subject_missing(不静默放行)', async () => {
|
||
mockModels({ subject: null });
|
||
|
||
const res = await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send(body).expect(403);
|
||
assert(res.body.status === 'subject_missing', JSON.stringify(res.body));
|
||
});
|
||
|
||
it('续期后失效缓存:下一批上报立即恢复', async () => {
|
||
let expireAt = new Date(Date.now() - 60 * 1000);
|
||
const reads = { count: 0 };
|
||
mockModels({ subject: () => authSubject(expireAt), reads });
|
||
|
||
await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send(body).expect(403);
|
||
|
||
// 模拟续期:写库 + 失效缓存
|
||
expireAt = new Date(Date.now() + 30 * 86400000);
|
||
await app.createAnonymousContext().service.subjectState.invalidate(SUBJECT_ID);
|
||
|
||
const res = await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send(body).expect(200);
|
||
assert(res.body.data.received === 1, JSON.stringify(res.body));
|
||
assert(reads.count === 2, `续期后应重新回源一次,实际 ${reads.count}`);
|
||
});
|
||
|
||
it('心跳返回主体状态(供设备暂停/恢复),且连续心跳不重复查库', async () => {
|
||
const reads = { count: 0 };
|
||
mockModels({ subject: authSubject(new Date(Date.now() + 2 * 3600 * 1000)), reads });
|
||
|
||
const first = await app.httpRequest().post('/api/scanner/heartbeat').set('Authorization', token()).expect(200);
|
||
assert(first.body.data.subject, JSON.stringify(first.body));
|
||
assert(first.body.data.subject.expired === false);
|
||
assert(first.body.data.subject.remainingSeconds > 0);
|
||
assert(typeof first.body.data.serverTime === 'string');
|
||
|
||
const second = await app.httpRequest().post('/api/scanner/heartbeat').set('Authorization', token()).expect(200);
|
||
assert(second.body.data.subject.expired === false);
|
||
assert(reads.count === 1, `心跳应读缓存(仍为 1 次),实际 ${reads.count}`);
|
||
});
|
||
|
||
it('心跳在主体过期时仍 200,并明确返回 expired=true', async () => {
|
||
mockModels({ subject: authSubject(new Date(Date.now() - 1000)) });
|
||
|
||
const res = await app.httpRequest().post('/api/scanner/heartbeat').set('Authorization', token()).expect(200);
|
||
assert(res.body.data.subject.expired === true, JSON.stringify(res.body));
|
||
assert(res.body.data.subject.remainingSeconds === 0);
|
||
});
|
||
});
|