@andy.ian/dsh-homing 2.0.3 → 2.1.1

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.
Files changed (138) hide show
  1. package/bin/restart-daemon.mjs +3 -0
  2. package/bin/restart.mjs +3 -0
  3. package/index.js +714 -21
  4. package/lib/devices.mjs +0 -1
  5. package/lib/files-page.mjs +0 -18
  6. package/lib/files.mjs +39 -27
  7. package/package.json +7 -9
  8. package/restart/client.mjs +184 -0
  9. package/restart/config.mjs +187 -0
  10. package/restart/daemon/README.md +102 -0
  11. package/restart/daemon/cli.mjs +366 -0
  12. package/restart/daemon/lib/detach.mjs +126 -0
  13. package/restart/daemon/lib/process-tree.mjs +69 -0
  14. package/restart/daemon/lib/restart-flow.mjs +111 -0
  15. package/restart/daemon/lib/update-state.mjs +72 -0
  16. package/restart/daemon/main.mjs +691 -0
  17. package/restart/engine.mjs +93 -0
  18. package/restart/face.mjs +62 -0
  19. package/restart/runner.mjs +184 -0
  20. package/restart/service.mjs +91 -0
  21. package/bin/supervisor.mjs +0 -488
  22. package/bin/watchdog.mjs +0 -144
  23. package/lib/vendor/node_modules/ssh2/examples/server-chat.js +0 -238
  24. package/lib/vendor/node_modules/ssh2/examples/sftp-server-download-only.js +0 -134
  25. package/lib/vendor/node_modules/ssh2/test/common.js +0 -316
  26. package/lib/vendor/node_modules/ssh2/test/fixtures/bad_rsa_private_key +0 -26
  27. package/lib/vendor/node_modules/ssh2/test/fixtures/https_cert.pem +0 -33
  28. package/lib/vendor/node_modules/ssh2/test/fixtures/https_key.pem +0 -52
  29. package/lib/vendor/node_modules/ssh2/test/fixtures/id_dsa +0 -12
  30. package/lib/vendor/node_modules/ssh2/test/fixtures/id_ecdsa +0 -5
  31. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa +0 -15
  32. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa.ppk +0 -26
  33. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa_enc +0 -30
  34. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +0 -21
  35. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +0 -1
  36. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +0 -7
  37. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +0 -7
  38. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +0 -22
  39. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +0 -1
  40. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +0 -7
  41. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +0 -7
  42. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +0 -23
  43. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +0 -1
  44. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +0 -7
  45. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +0 -7
  46. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +0 -9
  47. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +0 -1
  48. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +0 -7
  49. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +0 -7
  50. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +0 -10
  51. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +0 -1
  52. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +0 -8
  53. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +0 -7
  54. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +0 -10
  55. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +0 -1
  56. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +0 -8
  57. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +0 -7
  58. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +0 -7
  59. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +0 -1
  60. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +0 -7
  61. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +0 -7
  62. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +0 -27
  63. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +0 -1
  64. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +0 -7
  65. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +0 -7
  66. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +0 -28
  67. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +0 -1
  68. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +0 -8
  69. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +0 -7
  70. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +0 -29
  71. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +0 -1
  72. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +0 -8
  73. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +0 -7
  74. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +0 -12
  75. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +0 -1
  76. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +0 -7
  77. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +0 -7
  78. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +0 -15
  79. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +0 -1
  80. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +0 -8
  81. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +0 -7
  82. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +0 -5
  83. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +0 -1
  84. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +0 -7
  85. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +0 -7
  86. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +0 -8
  87. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +0 -1
  88. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +0 -8
  89. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +0 -7
  90. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa +0 -27
  91. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +0 -1
  92. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +0 -7
  93. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +0 -7
  94. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +0 -30
  95. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +0 -1
  96. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +0 -8
  97. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +0 -7
  98. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +0 -54
  99. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +0 -1
  100. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +0 -6
  101. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +0 -6
  102. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +0 -17
  103. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +0 -7
  104. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +0 -26
  105. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +0 -7
  106. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +0 -18
  107. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +0 -7
  108. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +0 -9
  109. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +0 -7
  110. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +0 -10
  111. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +0 -7
  112. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +0 -11
  113. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +0 -7
  114. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +0 -11
  115. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +0 -7
  116. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +0 -8
  117. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +0 -7
  118. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +0 -13
  119. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +0 -7
  120. package/lib/vendor/node_modules/ssh2/test/fixtures/openssh_new_rsa +0 -27
  121. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +0 -12
  122. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +0 -5
  123. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +0 -15
  124. package/lib/vendor/node_modules/ssh2/test/test-exec.js +0 -578
  125. package/lib/vendor/node_modules/ssh2/test/test-integration-openssh.js +0 -486
  126. package/lib/vendor/node_modules/ssh2/test/test-keygen.js +0 -60
  127. package/lib/vendor/node_modules/ssh2/test/test-misc-client-server.js +0 -1460
  128. package/lib/vendor/node_modules/ssh2/test/test-openssh.js +0 -261
  129. package/lib/vendor/node_modules/ssh2/test/test-protocol-crypto.js +0 -631
  130. package/lib/vendor/node_modules/ssh2/test/test-protocol-keyparser.js +0 -177
  131. package/lib/vendor/node_modules/ssh2/test/test-server-hostkeys.js +0 -138
  132. package/lib/vendor/node_modules/ssh2/test/test-sftp.js +0 -842
  133. package/lib/vendor/node_modules/ssh2/test/test-shell.js +0 -109
  134. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent-openssh.js +0 -110
  135. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent.js +0 -171
  136. package/lib/vendor/node_modules/ssh2/test/test-userauth.js +0 -611
  137. package/lib/vendor/node_modules/ssh2/test/test-worker-imports.js +0 -25
  138. package/lib/vendor/node_modules/ssh2/test/test.js +0 -20
@@ -0,0 +1,93 @@
1
+ /**
2
+ * 策略引擎:纯决策函数
3
+ *
4
+ * 输入:当前状态 + 这一轮的观测(是否繁忙、会话标题)+ 时间
5
+ * 输出:下一状态 + 该执行的动作
6
+ *
7
+ * 不碰定时器、不碰文件、不调守护进程 —— 因此可以用固定时间戳做单元测试。
8
+ */
9
+
10
+ export const ACTION = Object.freeze({
11
+ WAIT_EARLIEST: 'wait-earliest',
12
+ BUSY: 'busy',
13
+ START_QUIET: 'start-quiet',
14
+ WAIT_QUIET: 'wait-quiet',
15
+ TRIGGER: 'trigger',
16
+ });
17
+
18
+ /** 排队时的初始状态 */
19
+ export function initialState(now, earliestSeconds = 0) {
20
+ return {
21
+ active: true,
22
+ startedAt: now,
23
+ afterSeconds: earliestSeconds,
24
+ quietSince: null,
25
+ round: 0,
26
+ reason: '已排队,等待空闲',
27
+ };
28
+ }
29
+
30
+ export function idleState(reason = '未排队') {
31
+ return { active: false, startedAt: 0, afterSeconds: 0, quietSince: null, round: 0, reason };
32
+ }
33
+
34
+ /**
35
+ * 单步决策(纯函数,不修改入参)
36
+ *
37
+ * @param {object} state 上一轮状态
38
+ * @param {object} spec 已校验的策略配置
39
+ * @param {{ now: number, busyNow: boolean, busyTitles: string[], lastActivityAt: number }} input
40
+ * @returns {{ state: object, action: string, reason: string }}
41
+ */
42
+ export function decide(state, spec, input) {
43
+ const { now, busyNow, busyTitles = [] } = input;
44
+ const next = { ...state, round: state.round + 1 };
45
+ const quietMs = spec.idle.quietMs;
46
+
47
+ if (!next.active) {
48
+ return { state: next, action: ACTION.WAIT_QUIET, reason: next.reason || '未排队' };
49
+ }
50
+
51
+ const notBefore = next.startedAt + next.afterSeconds * 1000;
52
+ if (now < notBefore) {
53
+ next.reason = `等待最早重启时间(还差 ${Math.ceil((notBefore - now) / 1000)} 秒)`;
54
+ return { state: next, action: ACTION.WAIT_EARLIEST, reason: next.reason };
55
+ }
56
+
57
+ if (busyNow) {
58
+ next.quietSince = null;
59
+ next.reason = busyTitles.length
60
+ ? '有会话在运行:' + busyTitles.join('、')
61
+ : '最近有用户输入';
62
+ return { state: next, action: ACTION.BUSY, reason: next.reason };
63
+ }
64
+
65
+ if (next.quietSince === null) {
66
+ next.quietSince = now;
67
+ next.reason = `会话已结束,开始 ${Math.round(quietMs / 1000)} 秒安静窗口`;
68
+ return { state: next, action: ACTION.START_QUIET, reason: next.reason };
69
+ }
70
+
71
+ const waited = now - next.quietSince;
72
+ if (waited >= quietMs) {
73
+ next.reason = '满足重启条件,准备触发';
74
+ return { state: next, action: ACTION.TRIGGER, reason: next.reason };
75
+ }
76
+
77
+ next.reason = `安静窗口中(还差 ${Math.ceil((quietMs - waited) / 1000)} 秒)`;
78
+ return { state: next, action: ACTION.WAIT_QUIET, reason: next.reason };
79
+ }
80
+
81
+ /**
82
+ * 触发前的复查:忙则取消并重新计时
83
+ * @returns {{ state: object, cancelled: boolean, reason: string }}
84
+ */
85
+ export function recheckBeforeTrigger(state, spec, input, guardKey = 'recheckBeforeTrigger') {
86
+ if (!spec.guard[guardKey]) return { state, cancelled: false, reason: 'skipped' };
87
+ if (!input.busyNow) return { state, cancelled: false, reason: 'idle' };
88
+ return {
89
+ state: { ...state, quietSince: null, reason: '刚要重启时检测到新活动,已取消并重新计时' },
90
+ cancelled: true,
91
+ reason: 'became-busy-before-trigger',
92
+ };
93
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * 重启策略(对外门面)
3
+ *
4
+ * 分层:
5
+ * config.mjs 配置模型(校验、默认值、热加载)
6
+ * engine.mjs 纯决策(输入状态 → 动作),无定时器、无副作用
7
+ * runner.mjs 执行器(轮询、触发、重试、审计)
8
+ * face.mjs 本文件:组合上述模块,保持 queue/force/cancel/status 接口不变
9
+ *
10
+ * 策略来自配置(默认值 = 当前线上行为),改策略不必改代码。
11
+ */
12
+ import { DEFAULT_SPEC, parseSpec } from './config.mjs';
13
+ import { createPolicyRunner } from './runner.mjs';
14
+
15
+ /**
16
+ * @param {object} options
17
+ * @param {() => Array<{title?: string}>} options.busySessions
18
+ * @param {() => number} options.lastActivityAt
19
+ * @param {() => Promise<{ok: boolean}>} options.triggerRestart
20
+ * @param {string} [options.specPath] 策略配置文件路径(不传则用内存默认配置,不读文件)
21
+ * @param {number} [options.pollMs] 覆盖配置(测试用)
22
+ * @param {number} [options.quietMs] 覆盖配置(测试用)
23
+ * @param {number} [options.retryDelayMs] 覆盖配置(测试用)
24
+ */
25
+ export function createRestartPolicy({
26
+ busySessions,
27
+ lastActivityAt,
28
+ triggerRestart,
29
+ log = () => {},
30
+ audit = () => {},
31
+ specPath,
32
+ pollMs,
33
+ quietMs,
34
+ retryDelayMs,
35
+ }) {
36
+ // 显式参数优先(测试/兼容):这是代码不是用户配置,跳过配置文件那套边界校验
37
+ const hasOverrides = Number.isFinite(pollMs) || Number.isFinite(quietMs) || Number.isFinite(retryDelayMs);
38
+ const inline = hasOverrides
39
+ ? {
40
+ ok: true,
41
+ spec: {
42
+ ...DEFAULT_SPEC,
43
+ name: 'inline',
44
+ schedule: { ...DEFAULT_SPEC.schedule, pollMs: Number.isFinite(pollMs) ? Math.max(1, pollMs) : DEFAULT_SPEC.schedule.pollMs },
45
+ idle: { ...DEFAULT_SPEC.idle, quietMs: Number.isFinite(quietMs) ? Math.max(0, quietMs) : DEFAULT_SPEC.idle.quietMs },
46
+ retry: { ...DEFAULT_SPEC.retry, ...(Number.isFinite(retryDelayMs) ? { attempts: 1, delayMs: Math.max(0, retryDelayMs) } : {}) },
47
+ },
48
+ }
49
+ : null;
50
+
51
+ return createPolicyRunner({
52
+ busySessions,
53
+ lastActivityAt,
54
+ triggerRestart,
55
+ log,
56
+ audit,
57
+ specPath: inline ? undefined : specPath,
58
+ spec: inline ? inline.spec : undefined,
59
+ });
60
+ }
61
+
62
+ export { DEFAULT_SPEC };
@@ -0,0 +1,184 @@
1
+ /**
2
+ * 策略执行器:唯一碰定时器与副作用的地方
3
+ *
4
+ * 结构:
5
+ * spec(配置) → engine.decide()(纯决策) → 本模块执行动作
6
+ *
7
+ * 执行器只做四件事:
8
+ * 1. 按 spec.schedule.pollMs 轮询
9
+ * 2. 把观测(繁忙/标题)喂给纯决策函数
10
+ * 3. 需要触发时调用 triggerRestart(含重试与触发前复查)
11
+ * 4. 写审计与日志、维护 status()
12
+ */
13
+ import { ACTION, decide, initialState, idleState, recheckBeforeTrigger } from './engine.mjs';
14
+ import { DEFAULT_SPEC, createSpecWatcher } from './config.mjs';
15
+
16
+ export function createPolicyRunner({
17
+ busySessions,
18
+ lastActivityAt,
19
+ triggerRestart,
20
+ spec,
21
+ specPath,
22
+ log = () => {},
23
+ audit = () => {},
24
+ }) {
25
+ // 统一成 { ok, spec, errors, source } 形状:内联 spec 也要包一层,否则 specNow() 取不到
26
+ const currentSpec = specPath
27
+ ? createSpecWatcher(specPath)
28
+ : () => (spec ? { ok: true, spec, errors: [], source: 'inline' } : { ok: true, spec: DEFAULT_SPEC, errors: [], source: 'default' });
29
+
30
+ let state = idleState('未排队');
31
+ let inFlight = false;
32
+ let lastResult = null;
33
+ let generation = 0;
34
+
35
+ function specNow() {
36
+ const loaded = currentSpec();
37
+ // watcher 在配置无效时会把 spec 换成「上一次有效配置」,因此这里直接用 loaded.spec
38
+ return loaded?.spec ?? DEFAULT_SPEC;
39
+ }
40
+
41
+ function status() {
42
+ const loaded = currentSpec();
43
+ return {
44
+ active: state.active,
45
+ afterSeconds: state.afterSeconds,
46
+ waitedSeconds: state.active ? Math.round((Date.now() - state.startedAt) / 1000) : 0,
47
+ round: state.round,
48
+ reason: state.reason,
49
+ lastResult,
50
+ busy: isBusyNow(),
51
+ config: {
52
+ name: state.active && specNow().name ? specNow().name : (loaded?.spec?.name ?? 'default'),
53
+ source: loaded?.source ?? 'default',
54
+ valid: loaded?.ok !== false,
55
+ usedLastGood: loaded?.usedLastGood === true,
56
+ errors: loaded?.errors ?? [],
57
+ quietMs: specNow().idle.quietMs,
58
+ pollMs: specNow().schedule.pollMs,
59
+ },
60
+ };
61
+ }
62
+
63
+ /** 读观测:会话是否算"忙"由 idle.requireNoBusySessions 决定 */
64
+ function readInput() {
65
+ let sessions = [];
66
+ try { sessions = busySessions() ?? []; } catch { sessions = []; }
67
+ let last = NaN;
68
+ try { last = lastActivityAt(); } catch { last = NaN; }
69
+ const now = Date.now();
70
+ const spec0 = specNow();
71
+ const sessionsBlock = spec0.idle.requireNoBusySessions !== false;
72
+ const sessionBusy = sessionsBlock && sessions.length > 0;
73
+ const beaconBusy = Number.isFinite(last) && now - last < spec0.idle.quietMs;
74
+ return {
75
+ now,
76
+ busyNow: sessionBusy || beaconBusy,
77
+ busyTitles: sessionBusy ? sessions.map((item) => item?.title || '未命名会话') : [],
78
+ lastActivityAt: last,
79
+ };
80
+ }
81
+
82
+ function isBusyNow() {
83
+ const input = readInput();
84
+ return input.busyNow;
85
+ }
86
+
87
+ async function executeTrigger(activeGeneration) {
88
+ const spec0 = specNow();
89
+ inFlight = true;
90
+ try {
91
+ let result = null;
92
+ let attempt = 0;
93
+ for (;;) {
94
+ try {
95
+ result = await triggerRestart();
96
+ } catch (error) {
97
+ result = { ok: false, error: error?.message ?? String(error) };
98
+ }
99
+ if (result?.ok !== false) break;
100
+ if (attempt >= spec0.retry.attempts) break;
101
+ attempt += 1;
102
+ log('触发失败,' + spec0.retry.delayMs + 'ms 后重试(第 ' + attempt + ' 次)');
103
+ await new Promise((resolve) => setTimeout(resolve, spec0.retry.delayMs));
104
+ if (generation !== activeGeneration) return null;
105
+ const recheck = recheckBeforeTrigger(state, spec0, readInput(), 'recheckBeforeRetry');
106
+ if (recheck.cancelled) {
107
+ // 取消本次触发,但排队不能就此结束:重新拉起调度循环继续等安静窗口
108
+ state = { ...recheck.state, active: true };
109
+ audit('restart-cancelled', { reason: 'became-busy-before-retry' });
110
+ log('重试前检测到新活动,取消本次触发并继续排队');
111
+ generation += 1;
112
+ const nextGeneration = generation;
113
+ setTimeout(() => { void loop(nextGeneration) }, 0);
114
+ return { cancelled: true, state };
115
+ }
116
+ }
117
+ inFlight = false;
118
+ lastResult = { ok: result?.ok !== false, at: Date.now() };
119
+ state = { ...state, active: false, reason: lastResult.ok ? '已触发重启' : '重启失败:守护进程不可达或拒绝' };
120
+ audit('restart-triggered', { ok: lastResult.ok, reason: result?.error ?? null });
121
+ log('重启' + (lastResult.ok ? '成功' : '失败:' + (result?.error ?? '未知原因')));
122
+ return { ok: lastResult.ok };
123
+ } finally {
124
+ inFlight = false;
125
+ }
126
+ }
127
+
128
+ async function loop(myGeneration) {
129
+ while (state.active && generation === myGeneration) {
130
+ const spec0 = specNow();
131
+ await new Promise((resolve) => setTimeout(resolve, spec0.schedule.pollMs));
132
+ if (!state.active || generation !== myGeneration) return;
133
+
134
+ const result = decide(state, spec0, readInput());
135
+ state = result.state;
136
+
137
+ if (result.action === ACTION.TRIGGER) {
138
+ const recheck = recheckBeforeTrigger(state, spec0, readInput());
139
+ if (recheck.cancelled) {
140
+ state = { ...recheck.state, active: true };
141
+ audit('restart-cancelled', { reason: recheck.reason });
142
+ log('触发前检测到新活动,取消本次并重新等安静窗口');
143
+ continue;
144
+ }
145
+ state = { ...state, active: false };
146
+ await executeTrigger(myGeneration);
147
+ return;
148
+ }
149
+ }
150
+ }
151
+
152
+ function queue(afterSeconds = 0) {
153
+ if (inFlight) return { accepted: false, busy: true, ...status() };
154
+ if (state.active) return { accepted: true, already: true, ...status() };
155
+ const spec0 = specNow();
156
+ const earliest = Number.isFinite(afterSeconds) && afterSeconds > 0
157
+ ? afterSeconds
158
+ : spec0.schedule.earliestSeconds;
159
+ state = initialState(Date.now(), earliest);
160
+ generation += 1;
161
+ const my = generation;
162
+ void loop(my);
163
+ return { accepted: true, already: false, ...status() };
164
+ }
165
+
166
+ async function force() {
167
+ if (inFlight) return { ok: false, skipped: true, ...status() };
168
+ generation += 1;
169
+ state = { ...state, active: false };
170
+ const result = await executeTrigger(generation);
171
+ if (result?.cancelled) return { ok: false, cancelled: true, ...status() };
172
+ return { ok: result?.ok !== false, ...status() };
173
+ }
174
+
175
+ function cancel() {
176
+ if (!state.active) return { ok: false, reason: 'not-queued' };
177
+ generation += 1;
178
+ state = { ...state, active: false, reason: '已取消' };
179
+ audit('restart-cancelled', { reason: 'user-cancelled' });
180
+ return { ok: true };
181
+ }
182
+
183
+ return { queue, force, cancel, status, isBusyNow };
184
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * 重启能力的"服务层"(restart/service.mjs)
3
+ *
4
+ * 分类按目的:本文件服务于「重启」这件事,负责与守护进程通信。
5
+ * - 端口/超时/agent 配置只在这里
6
+ * - 错误一律降级(返回 null / {ok:false}),页面渲染不会因为守护进程没起而崩
7
+ * - 只读:status() / health()
8
+ * - 控制:pause() / resume() / stop()
9
+ * - 执行:restartNow()(必须由 restart/ 里的策略层调用,不直接暴露给页面)
10
+ *
11
+ * 与 restart/face.mjs 的分工:
12
+ * index.mjs 决定「该不该重启」(策略)
13
+ * service.mjs 负责「怎么跟守护进程说话」(通信)
14
+ */
15
+ import http from 'node:http';
16
+
17
+ export const RESTART_DAEMON_HOST = '127.0.0.1';
18
+ export const RESTART_DAEMON_PORT = 8790;
19
+
20
+ function readJson(up, chunks) {
21
+ const text = Buffer.concat(chunks).toString('utf8');
22
+ try { return JSON.parse(text); } catch { return null; }
23
+ }
24
+
25
+ export function createRestartService({
26
+ host = RESTART_DAEMON_HOST,
27
+ port = RESTART_DAEMON_PORT,
28
+ controlToken = () => '',
29
+ statusTimeoutMs = 3000,
30
+ postTimeoutMs = 5000,
31
+ } = {}) {
32
+ /** GET /status(失败返回 null,调用方按"守护进程未运行"处理) */
33
+ function status() {
34
+ return new Promise((resolve) => {
35
+ const request = http.request({ host, port, path: '/status', method: 'GET', timeout: statusTimeoutMs, agent: false }, (up) => {
36
+ const chunks = [];
37
+ up.on('data', (chunk) => chunks.push(chunk));
38
+ up.on('end', () => resolve(readJson(up, chunks)));
39
+ });
40
+ request.on('timeout', () => { request.destroy(); resolve(null); });
41
+ request.on('error', () => resolve(null));
42
+ request.end();
43
+ });
44
+ }
45
+
46
+ /** GET /health(轻量探活:不 spawn 进程、不读文件) */
47
+ function health() {
48
+ return new Promise((resolve) => {
49
+ const request = http.request({ host, port, path: '/health', method: 'GET', timeout: statusTimeoutMs, agent: false }, (up) => {
50
+ const chunks = [];
51
+ up.on('data', (chunk) => chunks.push(chunk));
52
+ up.on('end', () => resolve(readJson(up, chunks)));
53
+ });
54
+ request.on('timeout', () => { request.destroy(); resolve(null); });
55
+ request.on('error', () => resolve(null));
56
+ request.end();
57
+ });
58
+ }
59
+
60
+ /** POST 任意路径;返回 { ok, body, error? },不抛异常 */
61
+ function post(pathAndQuery) {
62
+ return new Promise((resolve) => {
63
+ const request = http.request({
64
+ host,
65
+ port,
66
+ path: pathAndQuery,
67
+ method: 'POST',
68
+ timeout: postTimeoutMs,
69
+ headers: { 'x-dsh-token': controlToken() },
70
+ agent: false,
71
+ }, (up) => {
72
+ const chunks = [];
73
+ up.on('data', (chunk) => chunks.push(chunk));
74
+ up.on('end', () => resolve({ ok: (up.statusCode ?? 500) < 400, status: up.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') }));
75
+ });
76
+ request.on('timeout', () => { request.destroy(); resolve({ ok: false, error: 'timeout' }); });
77
+ request.on('error', () => resolve({ ok: false, error: 'restart-daemon down' }));
78
+ request.end();
79
+ });
80
+ }
81
+
82
+ return {
83
+ status,
84
+ health,
85
+ post,
86
+ pause: (minutes) => post('/pause?minutes=' + encodeURIComponent(minutes)),
87
+ resume: () => post('/resume'),
88
+ restartNow: () => post('/restart-now'),
89
+ stop: () => post('/stop'),
90
+ };
91
+ }