feat: 新增阶梯提醒与请求失败告警规则

- 阶梯提醒:以「上次提醒时的价格」为基准,每偏离一个步长提醒一次并更新基准;
  方向支持每上涨/每下跌/双向,步长可填具体变动值或百分比,基准落盘 rule-state.json
- 请求失败告警:某品种连续抓取失败达到设定次数时提醒一次;抓取成功即清零,
  下一波连续失败可重新触发;支持「持续失败每 N 秒重复提醒」与生效时段
- 配置归一化接受 ladder / failure 类型,失败告警的 value 按次数取整、冷却固定为 0
- 规则弹窗补充两类规则的字段显隐、方向文案、预览与说明;重复间隔标签按类型切换
- 规则列表新增橙色「阶梯」、红色「失败告警」标签,失败告警不展示冷却
- README 补阶梯提醒与请求失败告警章节,规则类型更新为六类
This commit is contained in:
2026-11-24 18:01:49 +08:00
parent eb9b6d534f
commit 9e88456f73
7 changed files with 309 additions and 34 deletions
+168 -3
View File
@@ -120,6 +120,31 @@ class Monitor {
for (const key of [...this.quotes.keys()]) {
if (!ids.has(key)) this.quotes.delete(key);
}
this.pruneRuleStates(cfg);
}
/**
* 清掉已删除规则 / 品种残留的触发状态,避免 rule-state.json 无限增长
* @param {object} cfg 配置
*/
pruneRuleStates(cfg) {
const ruleIds = new Set(cfg.rules.map((r) => r.id));
const instIds = new Set(cfg.instruments.map((i) => i.id));
let changed = false;
for (const key of [...this.ruleStates.keys()]) {
// 定时提醒的去重键由 pruneScheduleStates 按时间清理
if (key.includes('::schedule::')) continue;
const parts = key.split('::');
const ruleId = parts[0];
const instId = parts[parts.length - 1];
// 价差规则的 key 是「规则::spread」,没有品种部分
const keepInst = key.endsWith('::spread') || !instId ? true : instIds.has(instId);
if (!ruleIds.has(ruleId) || !keepInst) {
this.ruleStates.delete(key);
changed = true;
}
}
if (changed) this.persistRuleStates();
}
/**
@@ -187,6 +212,9 @@ class Monitor {
state.updatedAt = nowText();
state.updatedAtMs = now;
this.pushHistory(state, now, quote.price);
// 抓取成功说明「请求失败告警」的条件已经不成立了,把状态归零,
// 这样下一波连续失败还能重新触发提醒
this.resetFailureStates(inst.id);
// 评估与该品种相关的规则
await this.evaluateRules(inst);
@@ -199,6 +227,8 @@ class Monitor {
if (state.errorCount <= 3 || state.errorCount % 20 === 0) {
log.warn(`【${inst.name}】抓取失败(第 ${state.errorCount} 次):${err.message}`);
}
// 抓取失败也要评估「请求失败告警」规则,否则这条规则永远不会响
await this.evaluateFailureRules(inst, state, err);
return state;
} finally {
this.inflight.delete(id);
@@ -333,10 +363,14 @@ class Monitor {
const cfg = this.store.get();
for (const rule of cfg.rules) {
if (!rule.enabled) continue;
// 「请求失败告警」只在抓取失败时评估(见 tick 的 catch 分支),这里跳过
if (rule.type === 'failure') continue;
// 生效时段之外直接跳过("22:00-02:00" 这类跨零点区间也支持)
if (rule.activeRange && !inTimeRange(rule.activeRange)) {
// 时段外不评估,但把状态压成「不满足」:这样进入时段后条件一旦成立,
// 仍会按边沿触发正常提醒,而不是被当成「首次评估」静默掉。
// 阶梯提醒不使用 met 状态(它记录的是基准价),时段外直接跳过即可
if (rule.type === 'ladder') continue;
const key = rule.type === 'spread' ? `${rule.id}::spread` : `${rule.id}::${inst.id}`;
const st = this.ruleStates.get(key);
if (!st) {
@@ -353,6 +387,8 @@ class Monitor {
if (rule.instrumentId === inst.id || rule.compareInstrumentId === inst.id) {
await this.evaluateSpread(rule, cfg);
}
} else if (rule.type === 'ladder') {
if (rule.instrumentId === inst.id) await this.evaluateLadder(rule, inst, cfg);
} else if (rule.instrumentId === inst.id) {
await this.evaluateSingle(rule, inst, cfg);
}
@@ -629,6 +665,129 @@ class Monitor {
if (changed) this.persistRuleStates();
}
/**
* 阶梯提醒:以「上次提醒时的价格」为基准,每偏离一个步长就提醒一次,然后把基准更新到当前价。
* 例:步长 2 元、方向「每上涨」;780 建基准 → 782 提醒(基准变 782)→ 784 再提醒。
* 基价与上次提醒时间存在 ruleStates 里(key = 规则::ladder::品种),会随 rule-state.json 一起落盘。
* @param {object} rule 规则
* @param {object} inst 品种
* @param {object} cfg 配置
*/
async evaluateLadder(rule, inst, cfg) {
const state = this.quotes.get(inst.id);
if (!state || !state.price) return;
const price = state.price;
const key = `${rule.id}::ladder::${inst.id}`;
let saved = this.ruleStates.get(key);
// 第一次见到这个品种:先把当前价记成基准,不打扰
if (!saved || typeof saved.anchor !== 'number') {
this.ruleStates.set(key, { anchor: price, lastTriggerAt: 0 });
this.persistRuleStates();
return;
}
/** 步长口径:amount = 具体价格变动(元/克等);percent = 百分比 */
const basis = rule.changeBasis === 'amount' ? 'amount' : 'percent';
const step = Math.abs(rule.value);
/** 相对基准的变动量(amount 为价格差,percent 为百分数) */
const delta = basis === 'amount' ? price - saved.anchor : ((price - saved.anchor) / saved.anchor) * 100;
let hit = false;
if (rule.direction === 'down') hit = delta <= -step;
else if (rule.direction === 'both') hit = Math.abs(delta) >= step;
else hit = delta >= step; // 默认「每上涨」
if (!hit) return;
// 冷却期内先不提醒、也不移动基准,等冷却过了再判断
const cooldownMs = (rule.cooldownSec || 0) * 1000;
if (cooldownMs > 0 && Date.now() - Number(saved.lastTriggerAt || 0) < cooldownMs) return;
const anchor = saved.anchor;
this.ruleStates.set(key, { anchor: price, lastTriggerAt: Date.now() });
this.persistRuleStates();
const word = delta >= 0 ? '上涨' : '下跌';
const moveText = basis === 'amount'
? `${fmtPrice(Math.abs(delta), inst.digits)} ${inst.unit}`
: `${Math.abs(delta).toFixed(2)}%`;
const stepText = basis === 'amount'
? `${fmtPrice(step, inst.digits)} ${inst.unit}`
: `${step.toFixed(2)}%`;
const anchorText = `${fmtPrice(anchor, inst.digits)} ${inst.unit}`;
await this.raise(rule, {
title: `${inst.name} 阶梯提醒:较上次提醒${word} ${moveText}`,
message: `最新价 ${fmtPrice(price, inst.digits)} ${inst.unit},较上次提醒基准 ${anchorText} ${word} ${moveText},已达到步长 ${stepText}。基准已更新,下次再偏离 ${stepText} 时再提醒。`,
lines: [
`${inst.name} 最新价:<b>${fmtPrice(price, inst.digits)} ${inst.unit}</b>`,
`上次提醒基准:${anchorText}`,
`本次${word}:${moveText}(步长 ${stepText})`,
`触发时间:${nowText()}`,
],
snapshot: this.snapshot(),
}, cfg);
}
/**
* 请求失败告警:某个品种连续抓取失败达到指定次数时提醒一次。
* 失败次数用 state.errorCount 计(抓取成功会归零),因此「连续」的语义天然成立;
* 状态键 = 规则::failure::品种,成功抓取时由 resetFailureStates 归零,便于下一波失败重新提醒。
* @param {object} inst 品种
* @param {object} state 该品种的行情状态(errorCount 已自增)
* @param {Error} err 本次失败的错误
*/
async evaluateFailureRules(inst, state, err) {
const cfg = this.store.get();
const count = state.errorCount || 0;
for (const rule of cfg.rules) {
if (!rule.enabled || rule.type !== 'failure') continue;
if (rule.instrumentId !== inst.id) continue;
// 生效时段之外不评估(比如只在盘中盯数据源)
if (rule.activeRange && !inTimeRange(rule.activeRange)) continue;
/** 连续失败多少次算异常(至少 1 次) */
const limit = Math.max(1, Math.round(Number(rule.value) || 3));
const met = count >= limit;
const key = `${rule.id}::failure::${inst.id}`;
// 失败告警属于「异常即提醒」,第一次评估就满足也应该响,不受 alertOnFirstCheck 限制
if (!this.markAndCheck(rule, key, met, cfg, { alertOnFirst: true })) continue;
const lastOkText = state.updatedAt || '尚未成功抓取过';
const sourceText = `${inst.source}${inst.sourceOptions?.code ? ` / ${inst.sourceOptions.code}` : ''}`
+ `${inst.sourceOptions?.key ? ` / ${inst.sourceOptions.key}` : ''}`
+ `${inst.sourceOptions?.url ? ` / ${inst.sourceOptions.url}` : ''}`;
await this.raise(rule, {
title: `${inst.name} 连续抓取失败 ${count} 次`,
message: `${inst.name} 已连续 ${count} 次查询行情失败(阈值 ${limit} 次),最近一次报错:${err?.message || state.error || '未知原因'}。最后一次成功:${lastOkText}。请检查网络或数据源是否变更。`,
lines: [
`品种:<b>${inst.name}</b>(数据源 ${sourceText})`,
`连续失败:<b>${count} 次</b>(告警阈值 ${limit} 次)`,
`最近错误:${err?.message || state.error || '未知原因'}`,
`最后一次成功:${lastOkText}`,
`触发时间:${nowText()}`,
],
snapshot: this.snapshot(),
}, cfg);
}
}
/**
* 抓取成功后把该品种所有「请求失败告警」规则的状态压回不满足,
* 这样下一次连续失败还能重新触发(否则一直停在已触发状态,只会按重复间隔响)
* @param {string} instId 品种 id
*/
resetFailureStates(instId) {
const suffix = `::failure::${instId}`;
let changed = false;
for (const [key, value] of this.ruleStates) {
if (!key.endsWith(suffix)) continue;
if (value && value.met === false) continue;
this.ruleStates.set(key, { ...value, met: false });
changed = true;
}
if (changed) this.persistRuleStates();
}
/**
* 记录规则当前是否满足,并判断此刻是否应该发提醒。
* 采用「边沿触发」:只有从「不满足」变成「满足」才提醒(可选按 repeatIntervalSec 重复)。
@@ -636,9 +795,10 @@ class Monitor {
* @param {string} key 状态键
* @param {boolean} met 当前是否满足
* @param {object} cfg 配置
* @param {{alertOnFirst?: boolean}} [opts] alertOnFirst=true 时首次评估就满足也提醒
* @returns {boolean} 是否触发
*/
markAndCheck(rule, key, met, cfg) {
markAndCheck(rule, key, met, cfg, opts = {}) {
const now = Date.now();
let state = this.ruleStates.get(key);
const isFirst = !state;
@@ -650,7 +810,7 @@ class Monitor {
if (met) {
if (isFirst) {
// 首次评估:默认不打扰(可配置成也提醒),但把状态记下来
trigger = cfg.monitor?.alertOnFirstCheck === true;
trigger = opts.alertOnFirst === true ? true : cfg.monitor?.alertOnFirstCheck === true;
} else if (state.met !== true) {
trigger = true;
} else if (rule.repeatIntervalSec > 0 && now - state.lastTriggerAt >= rule.repeatIntervalSec * 1000) {
@@ -777,7 +937,12 @@ class Monitor {
if (!saved) return;
for (const [key, value] of Object.entries(saved)) {
if (value && typeof value === 'object') {
this.ruleStates.set(key, { met: value.met === true ? true : (value.met === false ? false : null), lastTriggerAt: Number(value.lastTriggerAt) || 0 });
// 保留各类型自己的附加字段(阶梯提醒要保住 anchor 基准价)
this.ruleStates.set(key, {
...value,
met: value.met === true ? true : (value.met === false ? false : null),
lastTriggerAt: Number(value.lastTriggerAt) || 0,
});
}
}
}