@andy.ian/dsh-homing 2.0.2 → 2.1.0

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 +785 -29
  4. package/lib/devices.mjs +0 -1
  5. package/lib/files-page.mjs +10 -18
  6. package/lib/files.mjs +39 -27
  7. package/package.json +8 -9
  8. package/restart/client.mjs +184 -0
  9. package/restart/config.mjs +187 -0
  10. package/restart/engine.mjs +93 -0
  11. package/restart/face.mjs +62 -0
  12. package/restart/runner.mjs +184 -0
  13. package/restart/service.mjs +91 -0
  14. package/restart-daemon/README.md +66 -0
  15. package/restart-daemon/cli.mjs +321 -0
  16. package/restart-daemon/lib/detach.mjs +126 -0
  17. package/restart-daemon/lib/process-tree.mjs +69 -0
  18. package/restart-daemon/lib/restart-flow.mjs +111 -0
  19. package/restart-daemon/lib/update-state.mjs +72 -0
  20. package/restart-daemon/main.mjs +691 -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,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
+ }
@@ -0,0 +1,66 @@
1
+ # 守护进程(restart-daemon)
2
+
3
+ DSH 崩溃/退出后负责把它重新拉起的后台进程。**不在 DSH 的进程树里**,因此 `taskkill /T` 杀不到它。
4
+
5
+ ## 目录结构
6
+
7
+ ```
8
+ restart-daemon/
9
+ ├─ main.mjs 守护进程本体(探测、重启、升级等待、控制口)
10
+ ├─ cli.mjs 命令行:install / start / status / stop / restart / remove
11
+ └─ lib/
12
+ ├─ process-tree.mjs 授权判定(纯逻辑)
13
+ ├─ update-state.mjs 升级检测(纯逻辑)
14
+ └─ detach.mjs 脱离启动 + 无窗口启动
15
+ ```
16
+
17
+ `bin/restart-daemon.mjs`、`bin/restart.mjs` 只是 3 行薄包装,保持 `package.json` 的 bin 路径不变。
18
+
19
+ ## 启动方式(Windows)
20
+
21
+ | 优先级 | 方式 | 父进程 | 控制台 | 说明 |
22
+ |---|---|---|---|---|
23
+ | 1 | **CIM/WMI**(`startViaCim`) | `WmiPrvSE.exe` | 无 | 首选,进程树与 DSH 无关 |
24
+ | 2 | spawn + `windowsHide`(`startHidden`) | 调用者(随后退出) | 无 | CIM 失败时兜底 |
25
+
26
+ 其他平台:detached spawn(setsid)。
27
+
28
+ ### 两个必须记住的坑
29
+
30
+ 1. **不要用 `New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly`**
31
+ 它建出的对象存不住属性(读回为空),StartupInfo 等于没传,控制台照建。
32
+ 必须用 `([wmiclass]'Win32_ProcessStartup').CreateInstance()`。
33
+
34
+ 2. **`CREATE_NO_WINDOW` 经 WMI 会被拒绝**(`ReturnValue=21`);
35
+ `CREATE_NEW_CONSOLE` 会带出可见控制台;只有 **`DETACHED_PROCESS (0x8)`** 能得到
36
+ "没有控制台"的进程。判据:目标进程没有 `conhost.exe` 子进程。
37
+
38
+ ## 开机自启(Windows)
39
+
40
+ | 优先级 | 方式 | 需要管理员 | 说明 |
41
+ |---|---|---|---|
42
+ | 1 | 任务计划(`schtasks /sc onlogon`) | 是 | 微软推荐,可查运行结果 |
43
+ | 2 | `HKCU\...\Run` + PowerShell 隐藏启动 | 否 | 无管理员时的兜底 |
44
+
45
+ VBScript 已弃用,代码中不再生成 VBS。
46
+
47
+ ## 安全模型
48
+
49
+ - 控制口只监听 `127.0.0.1:8790`
50
+ - 变更加操作必须满足:**请求来源 PID == 插件宿主 PID**(监听 8787 的进程),且该 PID 属于 DSH 进程集合
51
+ - 外部进程调用 `/restart-now` 一律 403
52
+
53
+ ## 常用命令
54
+
55
+ ```bash
56
+ node bin/restart.mjs install # 安装开机自启
57
+ node bin/restart.mjs start # 启动(CIM 优先)
58
+ node bin/restart.mjs status # 状态(含自启项校验)
59
+ node bin/restart.mjs stop # 停止
60
+ ```
61
+
62
+ ## 测试
63
+
64
+ ```bash
65
+ node --test test/unit.detach*.test.mjs test/unit.process-tree.test.mjs test/unit.update-state.test.mjs
66
+ ```