dsh-ris-ide 1.7.1 → 1.7.3

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/lib/janitor.js ADDED
@@ -0,0 +1,286 @@
1
+ /**
2
+ * Janitor: make sure the proxy layers die with dsh, even when dsh does not.
3
+ *
4
+ * The engine is a detached child and the ProxyBridge bridge runs outside our
5
+ * process tree (its Windows side is a separate elevated process), so nothing
6
+ * stops them when dsh is killed with SIGKILL, crashes, or the terminal is closed.
7
+ * A plain `process.on('exit')` hook covers the graceful cases only.
8
+ *
9
+ * So we arm a tiny detached watcher that polls the owning dsh pid and, once it
10
+ * is gone, performs the same cleanup the exit hook does: stop the engine, stop
11
+ * the bridge, put the Windows service back, drop the git proxy entries, remove
12
+ * the pid files. It is spawned detached (own session) so it outlives dsh, and it
13
+ * only touches state that actually exists, so an idle session leaves nothing
14
+ * behind to clean.
15
+ */
16
+
17
+ import { spawn, spawnSync } from 'node:child_process'
18
+ import { existsSync, readFileSync, unlinkSync, writeFileSync, mkdirSync } from 'node:fs'
19
+ import { dirname, join } from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+
22
+ import {
23
+ PROXY_MARKER,
24
+ proxyHomeDir,
25
+ proxyPidPath,
26
+ proxyLogPath,
27
+ readTail,
28
+ runWindowsGitConfig,
29
+ stopProxySync,
30
+ windowsGitPath,
31
+ } from './proxy.js'
32
+ import {
33
+ detectRunningRedirector,
34
+ legacyServiceStatePath,
35
+ restoreWindowsService,
36
+ serviceStatePath,
37
+ stopRedirectorSync,
38
+ } from './redirector.js'
39
+
40
+ /** File holding the janitor's own pid + the dsh pid it watches. */
41
+ export const JANITOR_STATE_FILENAME = 'proxy-janitor.json'
42
+
43
+ /** How often the watcher asks whether its owner is still alive. */
44
+ export const JANITOR_POLL_MS = 3000
45
+
46
+ /** State files that mean "something of ours is running". */
47
+ const ENGINE_PID = () => proxyPidPath()
48
+ const GIT_STATE = () => join(proxyHomeDir(), 'git-proxy.json')
49
+
50
+ /** True when a parked-service state file exists at either the canonical or old path. */
51
+ function hasServiceState() {
52
+ return existsSync(serviceStatePath()) || existsSync(legacyServiceStatePath())
53
+ }
54
+
55
+ /**
56
+ * Is a bridge running (any side, tracked or hand-started)?
57
+ *
58
+ * A test run must never touch the real machine — a Windows CI box may well have a
59
+ * real ProxyBridge_CLI running, and "clean up" would kill it. `detect` lets a test
60
+ * state the answer, and without the seam a test context answers "nothing running"
61
+ * (the machine is not this test's property).
62
+ * @param {Function} [detect] - override.
63
+ * @returns {boolean} whether bridge cleanup is due.
64
+ */
65
+ function bridgeRunning(detect) {
66
+ if (typeof detect === 'function') return detect() === true
67
+ if (process.env.NODE_TEST_CONTEXT !== undefined) return false
68
+ try {
69
+ return detectRunningRedirector().pid > 0
70
+ } catch {
71
+ return false
72
+ }
73
+ }
74
+
75
+ /** @returns {string} absolute path of the janitor state file. */
76
+ export function janitorStatePath() {
77
+ return join(proxyHomeDir(), JANITOR_STATE_FILENAME)
78
+ }
79
+
80
+ /** The script this module spawns (kept next to bin/, so installs and links agree). */
81
+ function janitorScript() {
82
+ return join(dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'proxy-janitor.mjs')
83
+ }
84
+
85
+ function pidAlive(pid) {
86
+ if (!Number.isInteger(pid) || pid <= 0) return false
87
+ try {
88
+ process.kill(pid, 0)
89
+ return true
90
+ } catch (error) {
91
+ return error?.code === 'EPERM'
92
+ }
93
+ }
94
+
95
+ function readJson(path) {
96
+ try {
97
+ return JSON.parse(readFileSync(path, 'utf8'))
98
+ } catch {
99
+ return null
100
+ }
101
+ }
102
+
103
+ function removeQuietly(path) {
104
+ try {
105
+ unlinkSync(path)
106
+ return true
107
+ } catch {
108
+ return false
109
+ }
110
+ }
111
+
112
+ /**
113
+ * What the janitor would clean right now (also used to decide whether it is worth
114
+ * starting one at all).
115
+ * @param {{detect?: Function}} [options] - test seam for the bridge probe.
116
+ * @returns {{engine: boolean, bridge: boolean, service: boolean, git: boolean}} per-layer state.
117
+ */
118
+ export function pendingSideEffects(options = {}) {
119
+ return {
120
+ engine: existsSync(ENGINE_PID()),
121
+ // Detection, not just our pid file: a hand-started bridge keeps intercepting
122
+ // after its record is gone, so it must still be cleaned up (B5).
123
+ bridge: bridgeRunning(options.detect),
124
+ service: hasServiceState(),
125
+ git: existsSync(GIT_STATE()),
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Stop everything we may have started, the same way the exit hook does.
131
+ *
132
+ * Safe to call when nothing runs: every step is guarded by its own state file.
133
+ * @param {{log?: Function, detect?: Function, stopBridge?: Function, restore?: Function}} [options] - logger and test seams.
134
+ * @returns {{engine: boolean, bridge: boolean, service: boolean, git: boolean, log: string[]}}
135
+ */
136
+ export function cleanupSideEffects({ log, detect, stopBridge, restore } = {}) {
137
+ const done = { engine: false, bridge: false, service: false, git: false, log: [] }
138
+ const say = (line) => {
139
+ done.log.push(line)
140
+ log?.(line)
141
+ }
142
+ const restoreService = typeof restore === 'function' ? restore : restoreWindowsService
143
+ const stopBridgeNow = typeof stopBridge === 'function' ? stopBridge : stopRedirectorSync
144
+
145
+ // Engine: pid file + identity check happen inside stopProxySync.
146
+ if (existsSync(ENGINE_PID())) {
147
+ done.engine = stopProxySync() === true
148
+ say(`engine: ${done.engine ? '已停止' : '未运行/未停止'}`)
149
+ }
150
+
151
+ // Bridge (ProxyBridge CLI on either side) + the Windows service we parked.
152
+ const bridgeDue = bridgeRunning(detect)
153
+ const serviceDue = hasServiceState()
154
+ if (bridgeDue) {
155
+ try {
156
+ const stopped = stopBridgeNow()
157
+ done.bridge = stopped?.stopped === true
158
+ say(`bridge: ${done.bridge ? `已停止 pid=${stopped.pid}` : `未停止(${stopped?.reason ?? '未知原因'})`}`)
159
+ } catch (error) {
160
+ say(`bridge: 停止失败(${error?.message ?? error})`)
161
+ }
162
+ }
163
+ if (serviceDue) {
164
+ const restored = restoreService()
165
+ // restoreWindowsService answers `{restored:true}` — the old check read `.ok`,
166
+ // which never exists, so a recovered service was reported as failed (or worse,
167
+ // a failed one as fine when both were undefined).
168
+ done.service = restored?.restored === true
169
+ say(`service: ${done.service ? '已恢复启动方式' : (restored?.reason ?? '未恢复')}`)
170
+ }
171
+
172
+ // git: undo exactly the entries we wrote, on both sides.
173
+ const gitState = readJson(GIT_STATE())
174
+ if (gitState !== null) {
175
+ const key = typeof gitState.key === 'string' ? gitState.key : ''
176
+ if (key !== '') {
177
+ for (const args of [['--global', '--unset', key]]) {
178
+ try {
179
+ spawnSyncGit(args)
180
+ } catch (error) {
181
+ say(`git: 清理失败(${error?.message ?? error})`)
182
+ }
183
+ }
184
+ const winGit = windowsGitPath()
185
+ if (winGit !== '') {
186
+ try {
187
+ runWindowsGitConfig(['--global', '--unset', key])
188
+ } catch {
189
+ /* Windows side is best effort: no git / no rights */
190
+ }
191
+ }
192
+ done.git = true
193
+ say(`git: 已清除 ${key}`)
194
+ }
195
+ removeQuietly(GIT_STATE())
196
+ }
197
+ return done
198
+ }
199
+
200
+ function spawnSyncGit(args) {
201
+ const result = spawnSync('git', ['config', ...args], { encoding: 'utf8', timeout: 5000, windowsHide: true })
202
+ if (result?.status !== 0 && result?.status !== undefined) {
203
+ throw new Error((result.stderr ?? '').trim().slice(0, 160) || `git config ${args.join(' ')} 失败`)
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Arm (or re-arm) the watcher for this dsh process.
209
+ *
210
+ * Idempotent per owner: an existing watcher whose owner is the same process is
211
+ * left alone, one watching a dead process is replaced.
212
+ * @param {{ownerPid?: number}} [options] - defaults to the current process.
213
+ * @returns {{armed: boolean, pid: number, owner: number, reason?: string}} state.
214
+ */
215
+ export function armJanitor(options = {}) {
216
+ const owner = Number.isInteger(options.ownerPid) ? options.ownerPid : process.pid
217
+ const existing = janitorStatus()
218
+ if (existing.running === true && existing.owner === owner) {
219
+ return { armed: true, pid: existing.pid, owner, reason: '已在运行' }
220
+ }
221
+ if (existing.running === true) disarmJanitor()
222
+
223
+ const script = janitorScript()
224
+ if (!existsSync(script)) return { armed: false, pid: 0, owner, reason: `找不到 ${script}` }
225
+ try {
226
+ mkdirSync(proxyHomeDir(), { recursive: true, mode: 0o700 })
227
+ const child = spawn(process.execPath, [script, '--owner', String(owner), '--home', proxyHomeDir()], {
228
+ detached: true,
229
+ stdio: 'ignore',
230
+ windowsHide: true,
231
+ })
232
+ child.unref()
233
+ const state = { pid: child.pid, owner, log: join(proxyHomeDir(), 'janitor.log') }
234
+ writeFileSync(janitorStatePath(), `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 })
235
+ return { armed: true, pid: child.pid, owner }
236
+ } catch (error) {
237
+ return { armed: false, pid: 0, owner, reason: error?.message ?? String(error) }
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Stop the watcher (graceful shutdown: the host cleans up itself).
243
+ * @returns {{stopped: boolean, pid: number}} outcome.
244
+ */
245
+ export function disarmJanitor() {
246
+ const state = readJson(janitorStatePath())
247
+ const pid = Number.isInteger(state?.pid) ? state.pid : 0
248
+ let stopped = false
249
+ if (pidAlive(pid)) {
250
+ try {
251
+ process.kill(pid, 'SIGTERM')
252
+ stopped = true
253
+ } catch {
254
+ stopped = false
255
+ }
256
+ }
257
+ removeQuietly(janitorStatePath())
258
+ return { stopped, pid }
259
+ }
260
+
261
+ /**
262
+ * @returns {{running: boolean, pid: number, owner: number, log: string}} watcher state.
263
+ */
264
+ export function janitorStatus() {
265
+ const state = readJson(janitorStatePath())
266
+ const pid = Number.isInteger(state?.pid) ? state.pid : 0
267
+ const owner = Number.isInteger(state?.owner) ? state.owner : 0
268
+ const running = pid > 0 && pidAlive(pid)
269
+ return { running, pid, owner, log: typeof state?.log === 'string' ? state.log : '' }
270
+ }
271
+
272
+ /** One line for the dialog / `yds proxy status`. */
273
+ export function describeJanitor() {
274
+ const status = janitorStatus()
275
+ if (status.running !== true) return '守护进程: 未运行'
276
+ return `守护进程: 运行中(pid ${status.pid},监视 dsh ${status.owner})`
277
+ }
278
+
279
+ /** Exported for the watching script: tail of the last engine log, for diagnostics. */
280
+ export function janitorDiagnostics() {
281
+ return {
282
+ marker: PROXY_MARKER,
283
+ engineLog: readTail(proxyLogPath(), 2048),
284
+ state: janitorStatus(),
285
+ }
286
+ }