dsh-qianchuan-toolkit 1.0.10 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # 更新日志
2
2
 
3
+ ## 1.0.11
4
+
5
+ - **看门狗(watchdog.mjs,新)**:独立进程,每 60 秒查三件事 —— ① 心跳文件 `heartbeat.json` 是否新鲜(超过 6 分钟没更新 / 超过 `nextAt` 判定卡死);② `supervisor.pid` / `watch.pid` 是否还活着;③ CDP 9222 是否连得上。发现问题立即推 **QQ + 企业微信**(同一故障 30 分钟内只推一次),能把守夜进程拉起来就自动拉起,恢复后再推一条「已恢复」。窗口外不检查、不打扰。
6
+ - **整点播报**:`hourly.mjs` 默认开启,每个整点(09:00、10:00…)推一条「X点播报」:本小时轮次数与时间点、最后一次的小时消耗/净成交/ROI/判定、本小时控量次数与结果、异常条数。**整点没收到播报 = 巡航掉线**,与看门狗互为兜底。`--no-digest` 可关闭。
7
+ - **开工 与 收工日报**:守夜进程每个窗口只推一次「已开工(窗口 07:00 ~ 次日 01:00)」;`--until` 到点收工前推「收工日报」(本次轮次数、控量成功/失败、异常条数、下一窗口时间)。
8
+ - 心跳由 `hourly.mjs` 每轮写入(含下一轮预计时间),看门狗据此判断是否卡死;`daily-supervisor.mjs` 负责拉起并每 2 分钟确认看门狗存活。
9
+ - 调试:`node hourly.mjs --digest-now --no-send` 只渲染上个小时播报;`node watchdog.mjs --once` 只检查一次并打印结果。
3
10
  ## 1.0.10
4
11
 
5
12
  - **计划复制·批量跑通**:新增 `assets/plan-copy/scripts/capture.mjs`(按 ID 搜索 → 详情页抓抖音号/素材/ROI/预算/商品 → 生成 `qc/params-<原ID>.json`)。抖音号解析只取在投行(过滤「已删除」「无抖音号(仅含商城流量)」与计划行),aweme ID 支持 `_`/`.` 字符,修掉漏号与误取商品 ID。
@@ -13,9 +13,11 @@ import { spawn } from 'node:child_process'
13
13
  import path from 'node:path'
14
14
  import fs from 'node:fs'
15
15
  import { fileURLToPath } from 'node:url'
16
+ import { notify } from './notify.mjs'
16
17
 
17
18
  const here = path.dirname(fileURLToPath(import.meta.url))
18
19
  const HOURLY = process.env.QC_HOURLY || path.join(here, 'hourly.mjs')
20
+ const WATCHDOG = process.env.QC_WATCHDOG || path.join(here, 'watchdog.mjs')
19
21
  if (!fs.existsSync(HOURLY)) { console.error('找不到 hourly.mjs:' + HOURLY + '(可用 QC_HOURLY 指定)'); process.exit(2) }
20
22
  const HOME = process.env.QC_HOME || path.join(here, '..', 'prod')
21
23
  const argv = process.argv.slice(2)
@@ -60,6 +62,41 @@ function nextWindow(now = Date.now()) {
60
62
 
61
63
  function fmt(ms) { return new Date(ms).toLocaleString('zh-CN') }
62
64
 
65
+ // ---- 看门狗:独立进程,自己盯着心跳/进程/CDP;本进程负责拉起它,并每 2 分钟确认它还活着 ----
66
+ function watchdogAlive() {
67
+ try {
68
+ const n = Number(String(fs.readFileSync(path.join(HOME, 'watchdog.pid'), 'utf8')).trim())
69
+ if (!n) return false
70
+ process.kill(n, 0)
71
+ return true
72
+ } catch (e) { return e.code === 'EPERM' }
73
+ }
74
+ function ensureWatchdog() {
75
+ if (!fs.existsSync(WATCHDOG)) return
76
+ if (watchdogAlive()) return
77
+ try {
78
+ const out = fs.openSync(path.join(HOME, 'watchdog.out.log'), 'a')
79
+ const c = spawn(process.execPath, [WATCHDOG, '--start', START, '--end', END], { stdio: ['ignore', out, out], env: { ...process.env, QC_HOME: HOME }, windowsHide: true })
80
+ log('看门狗已拉起 pid ' + c.pid)
81
+ c.on('exit', (code) => log('看门狗退出(退出码 ' + code + '),2 分钟后会重新拉起'))
82
+ } catch (e) { log('拉起看门狗失败:' + e.message) }
83
+ }
84
+
85
+ // ---- 每个窗口只推一次「已开工」 ----
86
+ const WINDOW_STATE = path.join(HOME, '.window-notified.json')
87
+ async function notifyWindowStart(w) {
88
+ let last = 0
89
+ try { last = Number(JSON.parse(fs.readFileSync(WINDOW_STATE, 'utf8')).start) || 0 } catch (e) {}
90
+ if (last === w.start) return
91
+ try { fs.mkdirSync(HOME, { recursive: true }); fs.writeFileSync(WINDOW_STATE, JSON.stringify({ start: w.start })) } catch (e) {}
92
+ const text = [
93
+ '窗口:' + fmt(w.start) + ' ~ ' + fmt(w.end),
94
+ '从现在起正常轮次不再打扰你;每个整点推一条「X点播报」,01:00 推收工日报。',
95
+ '整点没有播报 = 巡航掉线,看门狗会同时告警。',
96
+ ].join(String.fromCharCode(10))
97
+ await notify({ dir: HOME, title: '千川巡航:已开工', text, level: 'info', event: 'start', say: (s) => log(' notify: ' + s) }).catch(() => {})
98
+ }
99
+
63
100
  async function runOnce() {
64
101
  const args = ['--watch', '--max-rounds', '1000', '--until', END]
65
102
  log('启动巡航:hourly.mjs ' + args.join(' '))
@@ -81,6 +118,8 @@ if (PLAN_ONLY) {
81
118
  try { fs.writeFileSync(path.join(HOME, 'supervisor.pid'), String(process.pid)) } catch { /* 忽略 */ }
82
119
  process.on('exit', () => { try { if (String(fs.readFileSync(path.join(HOME, 'supervisor.pid'), 'utf8')).trim() === String(process.pid)) fs.unlinkSync(path.join(HOME, 'supervisor.pid')) } catch { /* 忽略 */ } })
83
120
  log('守夜进程启动:每天 ' + START + ' 开始,次日 ' + END + ' 收工(数据目录 ' + HOME + ')')
121
+ ensureWatchdog()
122
+ setInterval(() => { try { ensureWatchdog() } catch (e) { /* 忽略 */ } }, 120000)
84
123
  for (;;) {
85
124
  const w = nextWindow()
86
125
  if (!w.inWindow) {
@@ -89,6 +128,8 @@ for (;;) {
89
128
  continue
90
129
  }
91
130
  log('现在在窗口内(' + fmt(w.start) + ' ~ ' + fmt(w.end) + '),开始巡航')
131
+ ensureWatchdog()
132
+ await notifyWindowStart(w).catch(() => {})
92
133
  const code = await runOnce()
93
134
  const still = nextWindow()
94
135
  if (!still.inWindow) continue // 已到收工点:回到循环顶部睡到下一个开始时间
@@ -31,6 +31,7 @@ const STAGE_MS = Number(arg('stage-timeout', '90')) * 1000
31
31
  const ROUND_MS = Number(arg('round-timeout', '420')) * 1000
32
32
  const SHOTS = arg('shots', paths().home)
33
33
  const REPORT_ALL = has('report-all') // 每轮都把结果推给通知通道(默认只报异常)
34
+ const DIGEST = !has('no-digest') // 整点播报:每个整点推一次上一小时摘要(--no-digest 关闭)
34
35
  const UNTIL = arg('until', '') // 例:--until 01:00 跑到次日 01:00 自动收工
35
36
  function deadlineOf(hhmm) {
36
37
  const m = String(hhmm).match(/^(\d{1,2}):(\d{2})$/)
@@ -546,6 +547,72 @@ async function executeAccount(group, rec) {
546
547
  }
547
548
  }
548
549
 
550
+
551
+ // ---------- 心跳 + 整点播报 ----------
552
+ // 心跳:每轮写入 heartbeat.json,看门狗据 nextAt 判断是否卡死
553
+ const HB_FILE = path.join(P.home, 'heartbeat.json')
554
+ function writeHeartbeat(o) {
555
+ try { fs.mkdirSync(P.home, { recursive: true }); fs.writeFileSync(HB_FILE, JSON.stringify({ ts: new Date().toISOString(), pid: process.pid, ...o })) } catch (e) { /* 心跳失败不影响巡航 */ }
556
+ }
557
+ function hourStartOf(t = Date.now()) { const d = new Date(t); d.setMinutes(0, 0, 0); return d.getTime() }
558
+ const DIGEST_STATE = path.join(P.home, '.digest-state.json')
559
+ function loadDigestLast() { try { const n = Number(JSON.parse(fs.readFileSync(DIGEST_STATE, 'utf8')).lastAt); if (n > 0) return n } catch (e) {} return 0 }
560
+ function saveDigestLast(n) { try { fs.mkdirSync(P.home, { recursive: true }); fs.writeFileSync(DIGEST_STATE, JSON.stringify({ lastAt: n })) } catch (e) {} }
561
+ let DIGEST_LAST = WATCH && DIGEST ? (loadDigestLast() || hourStartOf()) : 0
562
+ function readJsonlFile(f) {
563
+ try { return fs.readFileSync(f, 'utf8').trim().split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch (e) { return null } }).filter(Boolean) } catch (e) { return [] }
564
+ }
565
+ const tms = (s) => new Date(s).getTime()
566
+ const hm2 = (t) => new Date(t).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
567
+
568
+ // 整点播报:把上一个整点小时的巡航日志压成一条,用户看「整点有没有消息」就知道是否还在跑
569
+ function digestInfo(hs) {
570
+ const he = hs + 3600000
571
+ const rounds = readJsonlFile(P.rounds).filter((r) => { const t = tms(r.ts); return t >= hs && t < he })
572
+ const acts = readJsonlFile(P.actions).filter((a) => { const t = tms(a.ts); return t >= hs && t < he })
573
+ const hh = new Date(hs).getHours()
574
+ const head = '千川巡航 · ' + hh + '点播报'
575
+ if (!rounds.length) {
576
+ return { title: '⚠️' + head, level: 'warn', text: ['本小时 0 轮:没有收到任何巡航记录。', '如果不是你手动停的,请检查巡航是否还在跑。'].join('\n') }
577
+ }
578
+ const decisions = []
579
+ let anomalies = 0
580
+ for (const r of rounds) {
581
+ for (const a of r.accounts || []) {
582
+ anomalies += (a.anomalies || []).length
583
+ for (const d of a.decisions || []) decisions.push({ t: tms(r.ts), d })
584
+ }
585
+ }
586
+ const lines = ['轮次 ' + rounds.length + ' 次(' + rounds.map((r) => hm2(tms(r.ts))).join(' / ') + ')']
587
+ if (decisions.length) {
588
+ const lastOne = decisions[decisions.length - 1]
589
+ const d = lastOne.d
590
+ let tail = d.decision.action
591
+ if (d.decision.action === 'control') tail = 'control:应控 ' + (d.decision.budget || '?') + ' 元'
592
+ else if (d.decision.reason) tail += ':' + d.decision.reason
593
+ lines.push('最后 ' + hm2(lastOne.t) + ':消耗 ' + d.cost + ' / 净成交 ' + d.gmv + ' / ROI ' + d.roi + ' → ' + tail)
594
+ }
595
+ if (acts.length) {
596
+ const okN = acts.filter((a) => a.ok).length
597
+ lines.push('控量 ' + acts.length + ' 次(成功 ' + okN + ' / 失败 ' + (acts.length - okN) + '):' + acts.map((a) => hm2(tms(a.ts)) + (a.ok ? ' ✅' : ' ❌')).join('、'))
598
+ }
599
+ lines.push('异常 ' + anomalies + ' 条')
600
+ return { title: (anomalies ? '⚠️' : '') + head, text: lines.join('\n'), level: anomalies ? 'warn' : 'info' }
601
+ }
602
+ async function pushDigest(hs) {
603
+ const d = digestInfo(hs)
604
+ await notify({ dir: P.home, title: d.title, text: d.text, level: d.level, event: 'digest', say: (s) => log(' notify: ' + s) }).catch(() => {})
605
+ log('已推送 ' + d.title)
606
+ }
607
+ async function flushDueDigests() {
608
+ if (!(WATCH && DIGEST)) return
609
+ while (DIGEST_LAST + 3605000 <= Date.now()) {
610
+ await pushDigest(DIGEST_LAST)
611
+ DIGEST_LAST += 3600000
612
+ saveDigestLast(DIGEST_LAST)
613
+ }
614
+ }
615
+
549
616
  // ---------- 每轮结果推送(--report-all 时,不论正常还是异常都发) ----------
550
617
  async function reportRound(i, recs, nextAt) {
551
618
  const lines = []
@@ -596,6 +663,13 @@ function nextSlot(nodes, extraAt = [], lastStart = 0) {
596
663
  }
597
664
 
598
665
  // ---- main ----
666
+ if (has('digest-now')) { // 调试用:只渲染上一个整点的播报内容;加 --no-send 不实际推送
667
+ const hs = hourStartOf(Date.now()) - 3600000
668
+ const d = digestInfo(hs)
669
+ console.log(d.title + String.fromCharCode(10) + d.text)
670
+ if (!has('no-send') && !DRY) await pushDigest(hs)
671
+ process.exit(0)
672
+ }
599
673
  if (has('doctor')) {
600
674
  console.log('数据目录 ' + P.home)
601
675
  for (const g of groupByAccount(cfg)) for (const t of g.targets) {
@@ -628,6 +702,7 @@ if (START_AT_MS) {
628
702
  log('定时启动:等到 ' + new Date(START_AT_MS).toLocaleString('zh-CN') + ' 才开始巡航(约 ' + Math.round(ms / 60000) + ' 分钟后)')
629
703
  await sleep(ms)
630
704
  }
705
+ writeHeartbeat({ round: 0, nextAt: Date.now() + 15 * 60000, phase: 'starting' })
631
706
  log('本轮 ' + groups.length + ' 个账号 / ' + groups.reduce((s, g) => s + g.targets.length, 0) + ' 个目标' + (DRY ? ' [dry-run]' : '') + (REPORT_ALL ? ' [每轮推送]' : '') + (DEADLINE ? ' [跑到 ' + new Date(DEADLINE).toLocaleString('zh-CN') + ']' : ''))
632
707
  if (REPORT_ALL && WATCH) {
633
708
  const r0 = resolveRule(cfg, groups[0].targets[0])
@@ -663,12 +738,25 @@ try {
663
738
  }
664
739
  for (const rec of recs) { delete rec._group }
665
740
  jl(P.rounds, { ts: new Date().toISOString(), round: i, ms: Date.now() - roundStart, accounts: recs })
741
+ writeHeartbeat({ round: i, ms: Date.now() - roundStart, nextAt: 0 })
666
742
  log('本轮耗时 ' + ((Date.now() - roundStart) / 1000).toFixed(1) + 's')
667
743
  const nodes = [...new Set(groups.flatMap((g) => g.targets.flatMap((t) => resolveRule(cfg, t).nodes)))].sort((a, b) => a - b)
668
744
  const last = i === MAX_ROUNDS
669
745
  const next = last ? 0 : nextSlot(nodes, extras, roundStart)
746
+ const digestDue = WATCH && DIGEST ? DIGEST_LAST + 3605000 : 0
747
+ const wakeAt = last ? digestDue : (digestDue && digestDue < next - 5000 ? digestDue : next)
748
+ writeHeartbeat({ round: i, ms: Date.now() - roundStart, nextAt: wakeAt || 0, nextRound: next || 0 })
670
749
  // 有异常时即使没开 --report-all 也要推,异常必须让人看到
671
750
  if (REPORT_ALL || recs.some((r) => (r.anomalies || []).length)) await reportRound(i, recs, next)
751
+ await flushDueDigests()
752
+ if (WATCH && DIGEST && !last) {
753
+ const due = DIGEST_LAST + 3605000
754
+ if (due < next - 5000) {
755
+ log('整点播报:等到 ' + new Date(due).toLocaleString('zh-CN'))
756
+ await sleep(Math.max(0, due - Date.now()))
757
+ await flushDueDigests()
758
+ }
759
+ }
672
760
  if (last) break
673
761
  if (DEADLINE && next > DEADLINE) {
674
762
  const remain = DEADLINE - Date.now()
@@ -680,7 +768,16 @@ try {
680
768
  continue
681
769
  }
682
770
  log('已到收工时间 ' + new Date(DEADLINE).toLocaleString('zh-CN') + ',巡航结束')
683
- if (REPORT_ALL) await notify({ dir: P.home, title: '千川巡航:已收工', text: '本轮后到达停止时间 ' + new Date(DEADLINE).toLocaleString('zh-CN') + ',巡航结束。', level: 'info', event: 'stop', say: (s) => log(' notify: ' + s) }).catch(() => {})
771
+ await flushDueDigests()
772
+ if (WATCH) {
773
+ const since = Date.now() - 20 * 3600000
774
+ const rs = readJsonlFile(P.rounds).filter((r) => tms(r.ts) >= since)
775
+ const acts = readJsonlFile(P.actions).filter((a) => tms(a.ts) >= since)
776
+ const okN = acts.filter((a) => a.ok).length
777
+ const errN = readJsonlFile(P.errors).filter((e) => tms(e.ts) >= since).length
778
+ const text = ['收工时间:' + new Date(DEADLINE).toLocaleString('zh-CN'), '本次共 ' + rs.length + ' 轮,控量 ' + acts.length + ' 次(成功 ' + okN + ' / 失败 ' + (acts.length - okN) + ')', '异常记录 ' + errN + ' 条', '下一窗口:明天 07:00 自动开始(看门狗全程盯着)'].join(String.fromCharCode(10))
779
+ await notify({ dir: P.home, title: '千川巡航:收工日报', text, level: 'info', event: 'stop', say: (s) => log(' notify: ' + s) }).catch(() => {})
780
+ }
684
781
  break
685
782
  }
686
783
  const waitMs = Math.max(0, next - Date.now())
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * watchdog.mjs —— 巡航看门狗(独立进程,60 秒一轮)
4
+ *
5
+ * 为什么需要它:巡航进程自己死了就发不出消息,必须有一个「旁观者」。
6
+ * 它做三件事:
7
+ * 1) 心跳检查:读 <QC_HOME>/heartbeat.json,超过 stale-min 分钟没更新 → 判卡死
8
+ * 2) 进程检查:supervisor.pid / watch.pid 是否还活着
9
+ * 3) 环境检查:CDP 9222 是否还能连上(Chrome 是否被关掉)
10
+ * 发现问题 → 能自动重启的就重启(守夜进程死了直接拉起来),然后推送告警;
11
+ * 恢复后再推一条「已恢复」。同一故障 30 分钟内只推一次,避免刷屏。
12
+ *
13
+ * node watchdog.mjs 长时间运行(由守夜进程拉起)
14
+ * node watchdog.mjs --once 只检查一次,打印结果(调试用)
15
+ * node watchdog.mjs --start 07:00 --end 01:00
16
+ * node watchdog.mjs --stale-min 6 --interval 60
17
+ */
18
+ import fs from 'node:fs'
19
+ import path from 'node:path'
20
+ import { spawn } from 'node:child_process'
21
+ import { fileURLToPath } from 'node:url'
22
+ import { notify } from './notify.mjs'
23
+
24
+ const here = path.dirname(fileURLToPath(import.meta.url))
25
+ const HOME = process.env.QC_HOME || path.join(here, '..', 'prod')
26
+ const SUPERVISOR = process.env.QC_SUPERVISOR || path.join(here, 'daily-supervisor.mjs')
27
+ const argv = process.argv.slice(2)
28
+ const arg = (k, d) => { const i = argv.indexOf('--' + k); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : d }
29
+ const has = (k) => argv.includes('--' + k)
30
+
31
+ const START = arg('start', '07:00')
32
+ const END = arg('end', '01:00')
33
+ const ONCE = has('once')
34
+ const INTERVAL = Math.max(20, Number(arg('interval', '60'))) * 1000
35
+ const STALE_MS = Math.max(2, Number(arg('stale-min', '6'))) * 60000
36
+ const ALERT_WIN = 30 * 60000
37
+
38
+ const log = (...a) => console.log(new Date().toLocaleString('zh-CN'), ...a)
39
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
40
+ const P = (f) => path.join(HOME, f)
41
+
42
+ const hm = (s) => { const m = String(s).match(/^(\d{1,2}):(\d{2})$/); if (!m) throw new Error('时间格式应为 HH:MM:' + s); return Number(m[1]) * 3600000 + Number(m[2]) * 60000 }
43
+ const START_OFF = hm(START)
44
+ const END_OFF = hm(END)
45
+ const midnight = (now = Date.now()) => { const d = new Date(now); d.setHours(0, 0, 0, 0); return d.getTime() }
46
+ function windowOfDay(dayStart) {
47
+ const start = dayStart + START_OFF
48
+ let end = dayStart + END_OFF
49
+ if (end <= start) end += 86400000
50
+ return { start, end }
51
+ }
52
+ function inWindow(now = Date.now()) {
53
+ const d0 = midnight(now)
54
+ for (let i = -1; i <= 1; i++) { const w = windowOfDay(d0 + i * 86400000); if (now >= w.start && now < w.end) return true }
55
+ return false
56
+ }
57
+ function nextStart(now = Date.now()) {
58
+ const d0 = midnight(now)
59
+ for (let i = 0; i <= 2; i++) { const w = windowOfDay(d0 + i * 86400000); if (w.start > now) return w.start }
60
+ return now + 86400000
61
+ }
62
+
63
+ const readJson = (f) => { try { return JSON.parse(fs.readFileSync(P(f), 'utf8')) } catch (e) { return null } }
64
+ const readPid = (f) => { try { const n = Number(String(fs.readFileSync(P(f), 'utf8')).trim()); return n > 0 ? n : 0 } catch (e) { return 0 } }
65
+ function alive(pid) { if (!pid) return false; try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } }
66
+
67
+ // 告警去重:同一 kind 30 分钟一次
68
+ function readAlerts() { return readJson('.watchdog-alerts.json') || {} }
69
+ function saveAlerts(o) { const now = Date.now(); for (const k of Object.keys(o)) if (now - Number(o[k] || 0) > 7 * 86400000) delete o[k]; try { fs.mkdirSync(HOME, { recursive: true }); fs.writeFileSync(P('.watchdog-alerts.json'), JSON.stringify(o)) } catch (e) {} }
70
+ async function alertOnce(kind, title, text, level = 'error') {
71
+ const m = readAlerts()
72
+ if (Date.now() - Number(m[kind] || 0) < ALERT_WIN) { log('(' + kind + ' 30 分钟内已报过,不重复推送)'); return false }
73
+ m[kind] = Date.now(); saveAlerts(m)
74
+ await notify({ dir: HOME, title, text, level, event: kind, say: (s) => log(' notify: ' + s) }).catch(() => {})
75
+ return true
76
+ }
77
+
78
+ async function cdpOk() {
79
+ try {
80
+ const r = await fetch('http://127.0.0.1:9222/json/version', { signal: AbortSignal.timeout(5000) })
81
+ return r.ok
82
+ } catch (e) { return false }
83
+ }
84
+
85
+ function startSupervisor() {
86
+ try {
87
+ const out = fs.openSync(P('supervisor.out.log'), 'a')
88
+ const child = spawn(process.execPath, [SUPERVISOR, '--start', START, '--end', END], { stdio: ['ignore', out, out], env: { ...process.env, QC_HOME: HOME }, detached: true, windowsHide: true })
89
+ child.unref()
90
+ log('已重新拉起守夜进程 pid ' + child.pid)
91
+ return child.pid
92
+ } catch (e) { log('拉起守夜进程失败:' + e.message); return 0 }
93
+ }
94
+
95
+ async function check() {
96
+ const now = Date.now()
97
+ const hb = readJson('heartbeat.json')
98
+ const supPid = readPid('supervisor.pid')
99
+ const watchPid = readPid('watch.pid')
100
+ const issues = []
101
+
102
+ if (!hb) issues.push({ kind: 'no-heartbeat', msg: '还没有心跳文件(巡航可能从未成功跑过一轮)' })
103
+ else {
104
+ const hbMs = new Date(hb.ts).getTime()
105
+ const age = now - hbMs
106
+ const overdue = hb.nextAt && now > Number(hb.nextAt) + STALE_MS
107
+ if (age > STALE_MS || overdue) issues.push({ kind: 'heartbeat-stale', msg: '心跳停止 ' + Math.round(age / 60000) + ' 分钟(最后 ' + new Date(hb.ts).toLocaleString('zh-CN') + ',第 ' + (hb.round || '?') + ' 轮' + (hb.nextAt ? ',应于 ' + new Date(hb.nextAt).toLocaleString('zh-CN') + ' 有新心跳' : '') + ')' })
108
+ }
109
+ if (!alive(supPid)) issues.push({ kind: 'supervisor-dead', msg: '守夜进程不存在(supervisor.pid=' + (supPid || '无') + ')' })
110
+ if (!alive(watchPid) && inWindow(now)) issues.push({ kind: 'watch-dead', msg: '巡航进程不存在(watch.pid=' + (watchPid || '无') + ')' })
111
+ const cdp = await cdpOk()
112
+ if (!cdp) issues.push({ kind: 'cdp-down', msg: 'CDP 9222 连不上(Chrome 被关掉或未启动)' })
113
+
114
+ if (!issues.length) return { ok: true }
115
+ log('发现问题:' + issues.map((x) => x.kind).join(', '))
116
+ const fixed = []
117
+ if (issues.some((x) => x.kind === 'supervisor-dead')) { const pid = startSupervisor(); if (pid) fixed.push('守夜进程已重启(pid ' + pid + ')') }
118
+ if (!cdp) fixed.push('请双击 start-qc.cmd 重新打开 Chrome 并登录千川')
119
+ if (issues.some((x) => x.kind === 'watch-dead') && alive(supPid)) fixed.push('守夜进程会自动重拉巡航(最多 5 分钟)')
120
+
121
+ const title = '🚨【巡航看门狗】' + (issues.some((x) => x.kind === 'cdp-down' || x.kind === 'supervisor-dead') ? '巡航已中断' : '巡航可能卡住')
122
+ const text = ['检查时间:' + new Date(now).toLocaleString('zh-CN'), ...issues.map((x) => '• ' + x.msg), ...(fixed.length ? ['', '已处理:', ...fixed.map((s) => '• ' + s)] : []), hb && hb.round ? '最后成功轮次:第 ' + hb.round + ' 轮(' + new Date(hb.ts).toLocaleString('zh-CN') + ')' : ''].filter(Boolean).join('\n')
123
+ await alertOnce('watchdog', title, text)
124
+ return { ok: false, issues }
125
+ }
126
+
127
+ async function recovery() {
128
+ const m = readAlerts()
129
+ if (!m['watchdog']) return
130
+ delete m['watchdog']; saveAlerts(m)
131
+ await notify({ dir: HOME, title: '✅【巡航看门狗】已恢复', text: '之前报过的问题已消失,心跳与进程均正常。\n时间:' + new Date().toLocaleString('zh-CN'), level: 'info', event: 'watchdog-recover', say: (s) => log(' notify: ' + s) }).catch(() => {})
132
+ }
133
+
134
+ if (ONCE) {
135
+ const r = await check()
136
+ console.log(JSON.stringify({ inWindow: inWindow(), ...r }))
137
+ process.exit(r.ok ? 0 : 1)
138
+ }
139
+
140
+ // 单实例
141
+ const lock = P('watchdog.pid')
142
+ try {
143
+ const old = readPid('watchdog.pid')
144
+ if (old && old !== process.pid && alive(old)) { console.error('已有看门狗在跑(pid ' + old + '),本次不重复启动'); process.exit(4) }
145
+ } catch (e) {}
146
+ try { fs.mkdirSync(HOME, { recursive: true }); fs.writeFileSync(lock, String(process.pid)) } catch (e) {}
147
+ process.on('exit', () => { try { if (String(fs.readFileSync(lock, 'utf8')).trim() === String(process.pid)) fs.unlinkSync(lock) } catch (e) {} })
148
+
149
+ log('看门狗启动:窗口 ' + START + ' ~ 次日 ' + END + ',每 ' + Math.round(INTERVAL / 1000) + ' 秒检查一次(数据目录 ' + HOME + ')')
150
+ for (;;) {
151
+ if (!inWindow()) { await sleep(Math.min(Math.max(60000, nextStart() - Date.now()), 30 * 60000)); continue }
152
+ let r
153
+ try { r = await check() } catch (e) { log('检查异常:' + e.message); r = { ok: true } }
154
+ if (r.ok) await recovery().catch(() => {})
155
+ await sleep(INTERVAL)
156
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-qianchuan-toolkit",
3
- "version": "1.0.10",
3
+ "version": "1.0.11",
4
4
  "type": "module",
5
5
  "description": "DSH skill bundle for 巨量千川: 直播盯盘自动控量 (qianchuan-live-control) + 乘方计划复制 (qianchuan-plan-copy).",
6
6
  "license": "MIT",
@@ -46,4 +46,4 @@
46
46
  "CHANGELOG.md",
47
47
  "docs"
48
48
  ]
49
- }
49
+ }