dsh-ris-ide 1.8.0 → 1.8.2
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/README.md +5 -3
- package/bin/risd.mjs +14 -17
- package/lib/client.js +400 -93
- package/lib/debug/vendor/README.md +14 -0
- package/lib/debug/vendor/jdwp/client.js +9 -4
- package/lib/debug/vendor/src/jdwp/client.ts +12 -5
- package/lib/index.js +794 -48
- package/lib/proxybridge-bundle.js +1 -1
- package/lib/proxybridge-health.js +206 -0
- package/lib/redirector.js +1181 -90
- package/lib/risd/lifecycle.js +9 -3
- package/lib/risd/server.js +762 -26
- package/lib/risd/ui.js +419 -98
- package/lib/risd-client.js +4 -1
- package/lib/startup.js +27 -7
- package/package.json +2 -2
- package/test/client-viewer.test.mjs +299 -120
- package/test/clipboard.test.mjs +259 -0
- package/test/debug-engine.test.mjs +3 -1
- package/test/dsh-origin.test.mjs +4 -11
- package/test/dsh-window-refresh.test.mjs +166 -1
- package/test/harness.test.mjs +1 -1
- package/test/helpers/cmd.mjs +29 -0
- package/test/helpers/tgz.mjs +71 -0
- package/test/host-search.test.mjs +18 -11
- package/test/host-tail.test.mjs +119 -24
- package/test/proxy-route.test.mjs +61 -0
- package/test/proxy-window.test.mjs +5 -0
- package/test/proxy.test.mjs +13 -1
- package/test/proxybridge-bundle.test.mjs +1 -59
- package/test/proxybridge-health.test.mjs +116 -0
- package/test/redirector-bundle.test.mjs +21 -67
- package/test/redirector.test.mjs +395 -5
- package/test/risd-api.test.mjs +114 -17
- package/test/risd-bridge-degrade.test.mjs +3 -29
- package/test/risd-engine.test.mjs +13 -50
- package/test/risd-entry.test.mjs +0 -37
- package/test/risd-follow-start.test.mjs +101 -0
- package/test/risd-git.test.mjs +7 -5
- package/test/risd-handoff.test.mjs +6 -50
- package/test/risd-helpers.mjs +150 -3
- package/test/risd-host-p2.test.mjs +2 -30
- package/test/risd-lifecycle.test.mjs +25 -0
- package/test/risd-programs.test.mjs +4 -34
- package/test/risd-restart.test.mjs +104 -0
- package/test/risd-review-p2.test.mjs +0 -13
- package/test/risd-shutdown.test.mjs +5 -38
- package/test/risd-teardown.test.mjs +8 -27
- package/test/risd-ui.test.mjs +322 -4
- package/test/risd-write.test.mjs +2 -1
- package/test/startup-reconcile.test.mjs +44 -8
- package/test/proxy-restart.test.mjs +0 -37
package/lib/risd/server.js
CHANGED
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import { spawn } from 'node:child_process'
|
|
18
18
|
import { createServer, request } from 'node:http'
|
|
19
|
-
import {
|
|
19
|
+
import { request as httpsRequest } from 'node:https'
|
|
20
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
20
21
|
import { isAbsolute, join, win32 } from 'node:path'
|
|
21
22
|
import { timingSafeEqual } from 'node:crypto'
|
|
22
23
|
import { fileURLToPath } from 'node:url'
|
|
@@ -29,9 +30,10 @@ import { BUNDLE_URLS, MAX_TGZ_BYTES, ensureBundle, installDir, installFromTgz, i
|
|
|
29
30
|
// module keeps loading (and verification stays disabled) if they are absent.
|
|
30
31
|
import * as bundleApi from '../proxybridge-bundle.js'
|
|
31
32
|
import { armJanitor, disarmJanitor, janitorStatus, markJanitorHandoff } from '../janitor.js'
|
|
32
|
-
import {
|
|
33
|
+
import { bundledBundleDir, posixToWindowsPath, readElevationState, REDIRECTOR_PID_FILENAMES, REDIRECTOR_PID_FILENAME, redirectorCommand, redirectorHome, redirectorProfilePath, redirectorStatusAsync, redirectorStatusCached, reloadRedirectorsWithProfile, startRedirectors, stopRedirector, windowsBundleDir, writeHeartbeat } from '../redirector.js'
|
|
33
34
|
import { risdConfigRevision, risdProxyView } from './view.js'
|
|
34
|
-
import {
|
|
35
|
+
import { buildProfile } from '../redirector.js'
|
|
36
|
+
import { clearGitProxy, readGitProxyState, reconcileGitProxy, syncGitProxy } from './git.js'
|
|
35
37
|
import { findProgram, listPrograms, readProgramLog, restartProgramByKey, startLogFollow, startProgramByKey, stopProgramByKey } from './programs.js'
|
|
36
38
|
import { reconcileStartupLeftovers } from '../startup.js'
|
|
37
39
|
import { createDebugEngine } from './debug.js'
|
|
@@ -40,6 +42,7 @@ import { risdUiHtml } from './ui.js'
|
|
|
40
42
|
import { pingSocks } from './ping.js'
|
|
41
43
|
import { buildStamp } from './build.js'
|
|
42
44
|
import { DebugError, debugErrorStatus } from '../debug/engine.js'
|
|
45
|
+
import { createHealthCache } from '../proxybridge-health.js'
|
|
43
46
|
|
|
44
47
|
/** Request bodies are tiny JSON objects; anything bigger is a bug or an attack. */
|
|
45
48
|
export const RISD_MAX_BODY_BYTES = 64 * 1024
|
|
@@ -60,6 +63,10 @@ const DSH_WINDOW_LIVE_MS = 5 * 60_000
|
|
|
60
63
|
/** Remembered windows older than this are pruned; between the two they show as
|
|
61
64
|
* "未活跃" but stay selectable (m08268: clicking one may still open the IDE). */
|
|
62
65
|
const DSH_WINDOW_RETAIN_MS = 7 * 24 * 60 * 60_000
|
|
66
|
+
/** Cap on the sidebar mirror: a machine with hundreds of workspaces must not make the
|
|
67
|
+
* page huge (the plugin caps its own snapshot at DSH_WINDOW_MAX_WORKSPACES = 50). */
|
|
68
|
+
const DSH_WORKSPACES_MAX = 100
|
|
69
|
+
|
|
63
70
|
|
|
64
71
|
/** The daemon's own page is only for the local browser (no DNS rebinding). */
|
|
65
72
|
export function isLoopbackHost(req) {
|
|
@@ -81,6 +88,165 @@ export function isLoopbackOrigin(origin) {
|
|
|
81
88
|
}
|
|
82
89
|
}
|
|
83
90
|
|
|
91
|
+
/** How long one direct sidebar probe may take before that candidate is skipped. */
|
|
92
|
+
const DSH_PROBE_TIMEOUT_MS = 600
|
|
93
|
+
/** Cap on the hosts probed for one answer: a few live dsh instances, not a scan. */
|
|
94
|
+
const DSH_PROBE_MAX_CANDIDATES = 4
|
|
95
|
+
/** Where each running plugin advertises its own origin (one file per pid). */
|
|
96
|
+
const DSH_INSTANCE_DIRNAME = 'instances'
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Turn a sidebar snapshot into panel rows. Sidebar order is the user's order, so the
|
|
100
|
+
* panel order is the sidebar order; a workspace is identified by its PATH (a rename
|
|
101
|
+
* keeps the path and changes only the label), and a matching remembered window
|
|
102
|
+
* supplies that workspace's origin, sessionId and liveness.
|
|
103
|
+
* @param {Array} sidebar - workspace entries (document or direct probe).
|
|
104
|
+
* @param {Array} windows - remembered windows, already filtered and sorted.
|
|
105
|
+
* @param {string} origin - loopback origin to embed a workspace nobody opened.
|
|
106
|
+
* @returns {Array} rows, possibly empty.
|
|
107
|
+
*/
|
|
108
|
+
function dshSidebarRows(sidebar, windows, origin) {
|
|
109
|
+
const rows = []
|
|
110
|
+
const remembered = new Map(windows.map((row) => [row.cwd, row]))
|
|
111
|
+
const seen = new Set()
|
|
112
|
+
for (const entry of sidebar) {
|
|
113
|
+
if (rows.length >= DSH_WORKSPACES_MAX) break
|
|
114
|
+
if (entry === null || typeof entry !== 'object') continue
|
|
115
|
+
const cwd = typeof entry.cwd === 'string' && isAbsolute(entry.cwd) ? entry.cwd : ''
|
|
116
|
+
if (cwd === '' || seen.has(cwd)) continue
|
|
117
|
+
seen.add(cwd)
|
|
118
|
+
const window = remembered.get(cwd)
|
|
119
|
+
if (window !== undefined) remembered.delete(cwd)
|
|
120
|
+
const title = typeof entry.title === 'string' ? entry.title : ''
|
|
121
|
+
const sessionId = typeof entry.sessionId === 'string' && entry.sessionId !== ''
|
|
122
|
+
? entry.sessionId
|
|
123
|
+
: (window === undefined ? '' : window.sessionId)
|
|
124
|
+
rows.push({
|
|
125
|
+
cwd,
|
|
126
|
+
title: title !== '' ? title : (window === undefined ? '' : window.title),
|
|
127
|
+
sessionId,
|
|
128
|
+
url: window === undefined ? origin : window.url,
|
|
129
|
+
// A listed workspace is reachable even when nobody opened the IDE for it: it is
|
|
130
|
+
// not a remembered window, so it gets no "未活跃" label and no TTL of its own —
|
|
131
|
+
// the snapshot's freshness is the gate.
|
|
132
|
+
ageMs: window === undefined ? DSH_WINDOW_RETAIN_MS : window.ageMs,
|
|
133
|
+
live: window === undefined ? true : window.live,
|
|
134
|
+
// Whether the workspace has a live session right now; the page only hints with
|
|
135
|
+
// it, the row stays selectable either way (m00186).
|
|
136
|
+
...(typeof entry.active === 'boolean' ? { active: entry.active } : {}),
|
|
137
|
+
...(window === undefined ? { source: 'workspace' } : {}),
|
|
138
|
+
})
|
|
139
|
+
}
|
|
140
|
+
// Remembered windows whose workspace has left the sidebar still open: the user may
|
|
141
|
+
// be mid-session there, so they stay listed (as 未活跃 once stale).
|
|
142
|
+
for (const window of remembered.values()) rows.push(window)
|
|
143
|
+
return rows
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Loopback origins worth asking for a snapshot (m00186): the shared document's
|
|
148
|
+
* origin, every remembered window's origin, then the per-pid instance files (newest
|
|
149
|
+
* first). Only an instance file younger than the live window names a live process.
|
|
150
|
+
* @param {string} home - daemon home (holds `dsh-window.json` and `instances/`).
|
|
151
|
+
* @param {number} now - epoch ms.
|
|
152
|
+
* @param {string} documentOrigin - origin the shared document advertises.
|
|
153
|
+
* @param {Array} windows - usable remembered windows.
|
|
154
|
+
* @returns {string[]} distinct loopback origins, capped.
|
|
155
|
+
*/
|
|
156
|
+
function dshProbeCandidates(home, now, documentOrigin, windows) {
|
|
157
|
+
const candidates = []
|
|
158
|
+
const seen = new Set()
|
|
159
|
+
const push = (origin) => {
|
|
160
|
+
if (typeof origin !== 'string' || origin === '' || !isLoopbackOrigin(origin)) return
|
|
161
|
+
if (seen.has(origin) || candidates.length >= DSH_PROBE_MAX_CANDIDATES) return
|
|
162
|
+
seen.add(origin)
|
|
163
|
+
candidates.push(origin)
|
|
164
|
+
}
|
|
165
|
+
push(documentOrigin)
|
|
166
|
+
for (const row of windows) push(row.url)
|
|
167
|
+
const advertised = []
|
|
168
|
+
let names = []
|
|
169
|
+
try {
|
|
170
|
+
names = readdirSync(join(home, DSH_INSTANCE_DIRNAME))
|
|
171
|
+
} catch { /* older plugin: no instance files */ }
|
|
172
|
+
for (const name of names) {
|
|
173
|
+
if (!/^dsh-\d+\.json$/.test(name)) continue
|
|
174
|
+
try {
|
|
175
|
+
const parsed = JSON.parse(readFileSync(join(home, DSH_INSTANCE_DIRNAME, name), 'utf8'))
|
|
176
|
+
const at = Date.parse(String(parsed?.at ?? ''))
|
|
177
|
+
// A file from a dead process (or a reused pid) must not be probed; a timestamp
|
|
178
|
+
// far in the future is junk for the same reason as in the window rows.
|
|
179
|
+
if (!Number.isFinite(at) || now - at > DSH_WINDOW_LIVE_MS || at > now + 5 * 60_000) continue
|
|
180
|
+
advertised.push({ url: parsed?.url, at })
|
|
181
|
+
} catch { /* half-written file: not a candidate */ }
|
|
182
|
+
}
|
|
183
|
+
advertised.sort((a, b) => b.at - a.at)
|
|
184
|
+
for (const row of advertised) push(row.url)
|
|
185
|
+
return candidates
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Ask one live dsh for `GET /dsh-ris-ide/workspaces` (m00186). Never throws and never
|
|
190
|
+
* blocks longer than the probe timeout: a dead candidate is just a `null`.
|
|
191
|
+
* @param {string} origin - loopback http(s) origin.
|
|
192
|
+
* @returns {Promise<object|null>} the plugin's answer, or null.
|
|
193
|
+
*/
|
|
194
|
+
function probeDshWorkspaces(origin) {
|
|
195
|
+
return new Promise((resolveProbe) => {
|
|
196
|
+
let target
|
|
197
|
+
try {
|
|
198
|
+
target = new URL('/dsh-ris-ide/workspaces', origin)
|
|
199
|
+
} catch {
|
|
200
|
+
resolveProbe(null)
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
let settled = false
|
|
204
|
+
const finish = (value) => {
|
|
205
|
+
if (settled) return
|
|
206
|
+
settled = true
|
|
207
|
+
resolveProbe(value)
|
|
208
|
+
}
|
|
209
|
+
const client = target.protocol === 'https:' ? httpsRequest : request
|
|
210
|
+
const probe = client(target, {
|
|
211
|
+
method: 'GET',
|
|
212
|
+
timeout: DSH_PROBE_TIMEOUT_MS,
|
|
213
|
+
// dsh may serve TLS with a certificate this machine signed itself; the origin
|
|
214
|
+
// came from our own state files, not from the network, so trust it here.
|
|
215
|
+
...(target.protocol === 'https:' ? { rejectUnauthorized: false } : {}),
|
|
216
|
+
}, (response) => {
|
|
217
|
+
if (response.statusCode !== 200) {
|
|
218
|
+
response.resume()
|
|
219
|
+
finish(null)
|
|
220
|
+
return
|
|
221
|
+
}
|
|
222
|
+
let body = ''
|
|
223
|
+
response.setEncoding('utf8')
|
|
224
|
+
response.on('data', (chunk) => {
|
|
225
|
+
if (body.length > 512 * 1024) {
|
|
226
|
+
probe.destroy()
|
|
227
|
+
finish(null)
|
|
228
|
+
return
|
|
229
|
+
}
|
|
230
|
+
body += chunk
|
|
231
|
+
})
|
|
232
|
+
response.on('end', () => {
|
|
233
|
+
try {
|
|
234
|
+
finish(JSON.parse(body))
|
|
235
|
+
} catch {
|
|
236
|
+
finish(null)
|
|
237
|
+
}
|
|
238
|
+
})
|
|
239
|
+
response.on('error', () => finish(null))
|
|
240
|
+
})
|
|
241
|
+
probe.on('timeout', () => {
|
|
242
|
+
probe.destroy()
|
|
243
|
+
finish(null)
|
|
244
|
+
})
|
|
245
|
+
probe.on('error', () => finish(null))
|
|
246
|
+
probe.end()
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
|
|
84
250
|
function json(res, status, payload) {
|
|
85
251
|
const body = `${JSON.stringify(payload)}\n`
|
|
86
252
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body) })
|
|
@@ -149,6 +315,20 @@ function readBodyBytes(req, limit, timeoutMs = RISD_BODY_TIMEOUT_MS) {
|
|
|
149
315
|
})
|
|
150
316
|
}
|
|
151
317
|
|
|
318
|
+
/**
|
|
319
|
+
* True when this Linux is WSL with Windows interop: the only case where a Windows
|
|
320
|
+
* bridge side exists (m12029). `/proc/sys/kernel/osrelease` carries "microsoft"
|
|
321
|
+
* under WSL2; a native kernel never does.
|
|
322
|
+
*/
|
|
323
|
+
function isWslHost() {
|
|
324
|
+
if (process.platform !== 'linux') return false
|
|
325
|
+
try {
|
|
326
|
+
return readFileSync('/proc/sys/kernel/osrelease', 'utf8').toLowerCase().includes('microsoft')
|
|
327
|
+
} catch {
|
|
328
|
+
return false
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
152
332
|
/** One download at a time; the page polls GET /v1/proxybridge for the outcome. */
|
|
153
333
|
let bundleDownload = null
|
|
154
334
|
let bundleDownloadResult = null
|
|
@@ -324,22 +504,134 @@ let restarting = false
|
|
|
324
504
|
/** The CLI entry of this package: `bin/risd.mjs` (server.js lives in lib/risd/). */
|
|
325
505
|
const RISD_CLI_PATH = fileURLToPath(new URL('../../bin/risd.mjs', import.meta.url))
|
|
326
506
|
|
|
507
|
+
/**
|
|
508
|
+
* Linux process start time — field 22 of `/proc/<pid>/stat`, an opaque tick count.
|
|
509
|
+
*
|
|
510
|
+
* A pid alone is not an identity: after a restart the OS may hand the same number
|
|
511
|
+
* to an unrelated process, and `kill(pid, 0)` would then wait on the wrong one
|
|
512
|
+
* (review A4-P2-5). The start time is the cheap identity check the kernel offers.
|
|
513
|
+
*
|
|
514
|
+
* @param {number|string} pid - process id to inspect.
|
|
515
|
+
* @returns {string} decimal ticks, or '' when `/proc` is unavailable (non-Linux).
|
|
516
|
+
*/
|
|
517
|
+
export function readStartTime(pid) {
|
|
518
|
+
try {
|
|
519
|
+
const stat = readFileSync(`/proc/${Number(pid)}/stat`, 'utf8')
|
|
520
|
+
// `comm` is in parentheses and may itself contain spaces/parentheses.
|
|
521
|
+
const close = stat.lastIndexOf(')')
|
|
522
|
+
if (close < 0) return ''
|
|
523
|
+
const token = stat.slice(close + 2).split(' ')[19]
|
|
524
|
+
return typeof token === 'string' && /^\d+$/.test(token) ? token : ''
|
|
525
|
+
} catch {
|
|
526
|
+
return ''
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Resolve once `pid` is gone, or once its start time proves the pid was reused.
|
|
532
|
+
*
|
|
533
|
+
* Never throws: a successor must not die because the predecessor's pid file or
|
|
534
|
+
* `/proc` vanished mid-wait. `timedOut` tells the caller whether the deadline (not
|
|
535
|
+
* the exit) ended the wait so it can log that the handover raced the shutdown.
|
|
536
|
+
*
|
|
537
|
+
* @param {number} pid - predecessor pid.
|
|
538
|
+
* @param {number} timeoutMs - upper bound on the wait.
|
|
539
|
+
* @param {string} [expectedStartTime] - predecessor start time; '' = no identity check.
|
|
540
|
+
* @returns {Promise<{ok: boolean, timedOut: boolean}>} outcome, never a rejection.
|
|
541
|
+
*/
|
|
542
|
+
export function waitForPidExit(pid, timeoutMs, expectedStartTime = '') {
|
|
543
|
+
const expected = typeof expectedStartTime === 'string' ? expectedStartTime : ''
|
|
544
|
+
const deadline = Date.now() + timeoutMs
|
|
545
|
+
return new Promise((resolve) => {
|
|
546
|
+
const tick = () => {
|
|
547
|
+
let alive = true
|
|
548
|
+
try { process.kill(pid, 0) } catch (error) { alive = error.code === 'EPERM' }
|
|
549
|
+
// A live pid with a different start time is somebody else: the process we
|
|
550
|
+
// care about has exited (review A4-P2-5).
|
|
551
|
+
if (alive === true && expected !== '') {
|
|
552
|
+
const current = readStartTime(pid)
|
|
553
|
+
if (current !== '' && current !== expected) alive = false
|
|
554
|
+
}
|
|
555
|
+
if (alive !== true) { resolve({ ok: true, timedOut: false }); return }
|
|
556
|
+
if (Date.now() > deadline) { resolve({ ok: false, timedOut: true }); return }
|
|
557
|
+
setTimeout(tick, 100)
|
|
558
|
+
}
|
|
559
|
+
tick()
|
|
560
|
+
})
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Arguments for the successor CLI spawned by `POST /v1/restart`.
|
|
565
|
+
*
|
|
566
|
+
* Exported for the restart test: a successor without `--port` would bind the
|
|
567
|
+
* default port even when this daemon was started elsewhere, and the page polls
|
|
568
|
+
* the original origin forever (review A4-P2-6). `--wait-start` carries this
|
|
569
|
+
* process's identity so the successor does not wait on a reused pid (A4-P2-5).
|
|
570
|
+
*
|
|
571
|
+
* @param {{pid?: number, port?: number, startTime?: string}} [options] - predecessor identity.
|
|
572
|
+
* @returns {string[]} argv tail (`bin/risd.mjs serve …`).
|
|
573
|
+
*/
|
|
574
|
+
export function successorArgs({ pid = process.pid, port = 0, startTime = '' } = {}) {
|
|
575
|
+
const args = [RISD_CLI_PATH, 'serve', '--wait-pid', String(pid)]
|
|
576
|
+
// The actual bound port, not the requested one: `--port 0` asks the OS to pick.
|
|
577
|
+
if (Number.isInteger(port) && port > 0) args.push('--port', String(port))
|
|
578
|
+
if (typeof startTime === 'string' && /^\d+$/.test(startTime)) args.push('--wait-start', startTime)
|
|
579
|
+
return args
|
|
580
|
+
}
|
|
581
|
+
|
|
327
582
|
/**
|
|
328
583
|
* Spawn the successor that takes over after this process exits. Detached+unref'd
|
|
329
584
|
* so it outlives the HTTP server, and `--wait-pid` keeps it from racing us for the
|
|
330
|
-
* port.
|
|
331
|
-
*
|
|
585
|
+
* port.
|
|
586
|
+
*
|
|
587
|
+
* `restarting` is reset when the spawn itself fails or the child dies before it
|
|
588
|
+
* takes over (review A4-P2-7): otherwise every later POST would answer 200 and do
|
|
589
|
+
* nothing, and the only symptom would be the page's 30 s timeout.
|
|
590
|
+
*
|
|
591
|
+
* @param {number} [port] - port this daemon actually bound (A4-P2-6).
|
|
592
|
+
* @returns {import('node:child_process').ChildProcess|null} the child, or null.
|
|
332
593
|
*/
|
|
333
|
-
|
|
594
|
+
/** Test hook (see `__test`): how the successor is spawned. */
|
|
595
|
+
const restartHooks = { spawn }
|
|
596
|
+
|
|
597
|
+
function spawnRestartSuccessor(port = 0) {
|
|
598
|
+
let child = null
|
|
334
599
|
try {
|
|
335
|
-
|
|
600
|
+
child = restartHooks.spawn(process.execPath, successorArgs({ pid: process.pid, port, startTime: readStartTime(process.pid) }), {
|
|
336
601
|
detached: true,
|
|
337
602
|
stdio: 'ignore',
|
|
338
603
|
env: process.env,
|
|
339
604
|
cwd: process.cwd(),
|
|
340
605
|
})
|
|
341
606
|
child.unref()
|
|
342
|
-
} catch {
|
|
607
|
+
} catch (error) {
|
|
608
|
+
restarting = false
|
|
609
|
+
try { process.stderr.write(`[dsh-ris-ide] 重启失败:无法启动后继进程(${error?.message ?? error})\n`) } catch { /* ignore */ }
|
|
610
|
+
return null
|
|
611
|
+
}
|
|
612
|
+
child.once('error', (error) => {
|
|
613
|
+
restarting = false
|
|
614
|
+
try { process.stderr.write(`[dsh-ris-ide] 重启失败:后继进程出错(${error?.message ?? error})\n`) } catch { /* ignore */ }
|
|
615
|
+
})
|
|
616
|
+
child.once('exit', (code, signal) => {
|
|
617
|
+
restarting = false
|
|
618
|
+
if (signal === null && code !== 0) {
|
|
619
|
+
try { process.stderr.write(`[dsh-ris-ide] 重启后继进程提前退出(code ${code});请手动重启或重试\n`) } catch { /* ignore */ }
|
|
620
|
+
}
|
|
621
|
+
})
|
|
622
|
+
return child
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* Test seams for the restart path (same idea as redirector's `probeHooks`): the
|
|
627
|
+
* route itself cannot be exercised without spawning a real successor, so the spawn
|
|
628
|
+
* and the `restarting` flag are exposed here and never touched by production code.
|
|
629
|
+
*/
|
|
630
|
+
export const __test = {
|
|
631
|
+
restartHooks,
|
|
632
|
+
setRestarting(value) { restarting = value === true },
|
|
633
|
+
isRestarting() { return restarting === true },
|
|
634
|
+
spawnRestartSuccessor,
|
|
343
635
|
}
|
|
344
636
|
|
|
345
637
|
/**
|
|
@@ -368,19 +660,39 @@ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0
|
|
|
368
660
|
*/
|
|
369
661
|
async function teardownNetwork(cwd) {
|
|
370
662
|
try { await clearGitProxy() } catch { /* best effort */ }
|
|
371
|
-
|
|
663
|
+
// Only a bridge this proxy home recorded is ours to stop. Without a pid file the
|
|
664
|
+
// probe spawns PowerShell (seconds on WSL) and delays `risd stop` for an
|
|
665
|
+
// interception that cannot exist here (fixture daemons, plugin-only runs).
|
|
666
|
+
if (hasBridgePidFiles() === true) {
|
|
667
|
+
try { await serializeBridge(() => stopRedirector()) } catch { /* best effort */ }
|
|
668
|
+
// Nothing is intercepting anymore: drop the last start report so the card does
|
|
669
|
+
// not show a component that is gone (review A4-P2-8).
|
|
670
|
+
lastBridgeStart = null
|
|
671
|
+
}
|
|
372
672
|
if (cwd !== null) {
|
|
373
673
|
try { await stopProxy(cwd) } catch { /* best effort */ }
|
|
374
674
|
}
|
|
375
675
|
}
|
|
676
|
+
// Promise of the in-flight 「跟随 dsh」 start (null when idle). Declared here because
|
|
677
|
+
// scheduleTeardown reads it; the start half is defined further down, next to the
|
|
678
|
+
// engine helpers.
|
|
679
|
+
let followStarting = null
|
|
376
680
|
function scheduleTeardown() {
|
|
377
681
|
if (leases.count() > 0) return
|
|
378
|
-
|
|
682
|
+
// A start triggered by the lease that just left may still be in flight; its
|
|
683
|
+
// finally re-schedules teardown once engineCwd is known.
|
|
684
|
+
if (engineCwd === null && heartbeat === null && followStarting === null) return
|
|
379
685
|
if (teardownTimer !== null) return
|
|
380
686
|
teardownTimer = setTimeout(() => {
|
|
381
687
|
teardownTimer = null
|
|
382
688
|
void (async () => {
|
|
383
689
|
if (leases.count() > 0) return // someone came back
|
|
690
|
+
// Let a pending start land first: tearing down with engineCwd still null
|
|
691
|
+
// would skip stopProxy and leave an orphan engine nobody owns (m13960).
|
|
692
|
+
if (followStarting !== null) {
|
|
693
|
+
await followStarting.catch(() => {})
|
|
694
|
+
if (leases.count() > 0) return
|
|
695
|
+
}
|
|
384
696
|
// Per-resource policy: "follow dsh" stops it with the last window; the
|
|
385
697
|
// daemon-owned ones stay until the daemon itself stops (or forever).
|
|
386
698
|
if (lifecycle.debug.followDsh === true) await debug.stopAll().catch(() => {})
|
|
@@ -518,6 +830,51 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
518
830
|
engineOp = run.then(() => undefined, () => undefined)
|
|
519
831
|
return run
|
|
520
832
|
}
|
|
833
|
+
// 「代理引擎跟随 dsh」的启动半边(m13950):与拆除共用**租约**这一条链路——
|
|
834
|
+
// 拆除看 leases.count() 归零,启动看第一份租约到达,两边读同一个
|
|
835
|
+
// lifecycle.proxy.followDsh,所以不会出现「启动跟了、停止没跟」的错位。
|
|
836
|
+
// 自动启动永不 interactive:dsh 接入的副作用不许弹密码框(m13910),需要 root
|
|
837
|
+
// 的桥接只在页面组件卡里提示。失败被吞掉并留给页面,那里还有显式按钮。
|
|
838
|
+
function followStartForLease(cwd) {
|
|
839
|
+
if (lifecycle.proxy.followDsh !== true) return Promise.resolve({ action: 'skipped', reason: 'not-following-dsh' })
|
|
840
|
+
if (followStarting !== null) return Promise.resolve({ action: 'skipped', reason: 'starting' })
|
|
841
|
+
if (engineSummary().state === 'running') return Promise.resolve({ action: 'skipped', reason: 'running' })
|
|
842
|
+
// The in-flight promise stays reachable: teardown must be able to wait for a
|
|
843
|
+
// start that the departing lease itself kicked off (see scheduleTeardown).
|
|
844
|
+
const work = (async () => {
|
|
845
|
+
// The lease may have left between the signal and this line (window closed
|
|
846
|
+
// during the round-trip): do not spawn an engine for nobody.
|
|
847
|
+
if (leases.count() === 0) return { action: 'skipped', reason: 'no-lease' }
|
|
848
|
+
const where = typeof cwd === 'string' && isAbsolute(cwd) && existsSync(cwd) ? cwd : home
|
|
849
|
+
const status = await proxyStatus(where)
|
|
850
|
+
// No actionable row means the engine would listen for nobody: following dsh is
|
|
851
|
+
// a policy, not a reason to spawn a process.
|
|
852
|
+
if (buildProfile(status.config).rules.length === 0) return { action: 'skipped', reason: 'no-rules' }
|
|
853
|
+
if (leases.count() === 0) return { action: 'skipped', reason: 'no-lease' }
|
|
854
|
+
const result = await serializeEngine(async () => {
|
|
855
|
+
const engine = await startProxy(where)
|
|
856
|
+
const redirector = await serializeBridge(() => startRedirectors({ interactive: false }))
|
|
857
|
+
noteBridgeStart(redirector)
|
|
858
|
+
if (redirector.running === true || (Array.isArray(redirector.started) && redirector.started.length > 0)) {
|
|
859
|
+
bridgeReloadState = { at: Date.now(), ok: true, note: '' }
|
|
860
|
+
}
|
|
861
|
+
const git = await syncGitProxy({ cwd: where, enabled: true })
|
|
862
|
+
if (engine.ok === true) {
|
|
863
|
+
engineCwd = where
|
|
864
|
+
cancelIdleExit()
|
|
865
|
+
}
|
|
866
|
+
return Object.assign({}, engine, { redirector, git })
|
|
867
|
+
})
|
|
868
|
+
return { action: result.ok === true ? 'started' : 'failed', result }
|
|
869
|
+
})()
|
|
870
|
+
followStarting = work.finally(() => {
|
|
871
|
+
followStarting = null
|
|
872
|
+
// The lease that started this may already be gone: let the teardown path run
|
|
873
|
+
// now that engineCwd is known (it skips while a start is pending).
|
|
874
|
+
if (leases.count() === 0) scheduleTeardown()
|
|
875
|
+
})
|
|
876
|
+
return followStarting
|
|
877
|
+
}
|
|
521
878
|
// Program start/stop share one queue so two clicks cannot spawn the same row twice.
|
|
522
879
|
let programOp = Promise.resolve()
|
|
523
880
|
// Bridge (ProxyBridge) operations are serialized too (E8): a rule reload and a
|
|
@@ -625,13 +982,21 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
625
982
|
}
|
|
626
983
|
|
|
627
984
|
if (path === '/v1/dsh' && method === 'GET') {
|
|
628
|
-
//
|
|
629
|
-
// as an upserted list (origin + sessionId per
|
|
630
|
-
//
|
|
985
|
+
// What should the page's workspace panel list, and what is each one called?
|
|
986
|
+
// The plugin keeps dsh-window.json as an upserted list (origin + sessionId per
|
|
987
|
+
// workspace) AND, since m13800, the sidebar's workspace list with its titles
|
|
988
|
+
// (title is what a rename changes; the path never moves). Both halves are read
|
|
989
|
+
// here so the panel mirrors the dsh sidebar instead of guessing from folders.
|
|
631
990
|
let windows = []
|
|
991
|
+
let sidebar = []
|
|
992
|
+
let documentOrigin = ''
|
|
993
|
+
let documentAt = Number.NaN
|
|
632
994
|
try {
|
|
633
995
|
const parsed = JSON.parse(readFileSync(join(home, DSH_WINDOW_FILENAME), 'utf8'))
|
|
634
996
|
if (Array.isArray(parsed?.windows)) windows = parsed.windows
|
|
997
|
+
if (Array.isArray(parsed?.workspaces)) sidebar = parsed.workspaces
|
|
998
|
+
if (typeof parsed?.url === 'string') documentOrigin = parsed.url
|
|
999
|
+
documentAt = Date.parse(String(parsed?.at ?? ''))
|
|
635
1000
|
} catch { /* absent or rotated away: no dsh */ }
|
|
636
1001
|
const now = Date.now()
|
|
637
1002
|
let droppedAt = 0
|
|
@@ -640,7 +1005,7 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
640
1005
|
// The page hands this URL to window.open(); anything but a loopback
|
|
641
1006
|
// http(s) origin would let a crafted dsh-window.json point the IDE tab
|
|
642
1007
|
// somewhere else (review A-P2-10).
|
|
643
|
-
.filter((row) =>
|
|
1008
|
+
.filter((row) => isLoopbackOrigin(row.url))
|
|
644
1009
|
.map((row) => {
|
|
645
1010
|
const at = Date.parse(String(row.at ?? ''))
|
|
646
1011
|
// A timestamp far in the future made `now - at` clamp to 0, so the row
|
|
@@ -656,6 +1021,10 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
656
1021
|
return {
|
|
657
1022
|
cwd: typeof row.cwd === 'string' ? row.cwd : '',
|
|
658
1023
|
sessionId: typeof row.sessionId === 'string' ? row.sessionId : '',
|
|
1024
|
+
// The sidebar title the plugin resolved for this path (m13800). '' when
|
|
1025
|
+
// the host has no workspace registry (older dsh): the page then falls
|
|
1026
|
+
// back to the folder name it always used.
|
|
1027
|
+
title: typeof row.title === 'string' ? row.title : '',
|
|
659
1028
|
url: row.url,
|
|
660
1029
|
ageMs: Number.isFinite(at) && !future ? Math.max(0, now - at) : DSH_WINDOW_RETAIN_MS + 1,
|
|
661
1030
|
}
|
|
@@ -665,18 +1034,58 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
665
1034
|
// Live entries first, then most-recently-seen: the first row is the one an
|
|
666
1035
|
// iframe deep link opens by default.
|
|
667
1036
|
.sort((a, b) => (a.live === b.live ? a.ageMs - b.ageMs : a.live ? -1 : 1))
|
|
668
|
-
|
|
669
|
-
|
|
1037
|
+
const origin = isLoopbackOrigin(documentOrigin)
|
|
1038
|
+
? documentOrigin
|
|
1039
|
+
: (live.length > 0 ? live[0].url : '')
|
|
1040
|
+
// The sidebar snapshot is only as fresh as its writer: dsh writes it on every
|
|
1041
|
+
// request and every refresh tick, so a document older than the retain window
|
|
1042
|
+
// means dsh is gone and the list is stale. Rows of remembered windows are
|
|
1043
|
+
// then the only truth (and they age out on their own).
|
|
1044
|
+
const sidebarFresh = Number.isFinite(documentAt)
|
|
1045
|
+
&& documentAt <= now + 5 * 60_000
|
|
1046
|
+
&& now - documentAt <= DSH_WINDOW_RETAIN_MS
|
|
1047
|
+
let rows = []
|
|
1048
|
+
if (sidebarFresh && sidebar.length > 0 && origin !== '') {
|
|
1049
|
+
rows = dshSidebarRows(sidebar, live, origin)
|
|
1050
|
+
} else {
|
|
1051
|
+
rows.push(...live)
|
|
1052
|
+
}
|
|
1053
|
+
// Direct fallback (m00186): the shared document can be missing, unreadable or
|
|
1054
|
+
// last written by a different dsh instance while a host on this machine is
|
|
1055
|
+
// alive. Each running plugin advertises its origin under `instances/`, so ask
|
|
1056
|
+
// the hosts themselves instead of telling the user dsh is not running.
|
|
1057
|
+
let known = sidebar.length
|
|
1058
|
+
if (rows.length === 0) {
|
|
1059
|
+
for (const candidate of dshProbeCandidates(home, now, documentOrigin, live)) {
|
|
1060
|
+
const snapshot = await probeDshWorkspaces(candidate)
|
|
1061
|
+
if (snapshot === null) continue
|
|
1062
|
+
const probedOrigin = isLoopbackOrigin(snapshot?.url) ? snapshot.url : candidate
|
|
1063
|
+
const probedSidebar = Array.isArray(snapshot?.workspaces) ? snapshot.workspaces : []
|
|
1064
|
+
const probedRows = dshSidebarRows(probedSidebar, [], probedOrigin)
|
|
1065
|
+
if (probedRows.length === 0) continue
|
|
1066
|
+
rows = probedRows
|
|
1067
|
+
known = Math.max(known, probedSidebar.length)
|
|
1068
|
+
break
|
|
1069
|
+
}
|
|
670
1070
|
}
|
|
671
|
-
|
|
1071
|
+
if (rows.length === 0) {
|
|
1072
|
+
// "No dsh" and "dsh is there but nothing usable arrived" are different: the
|
|
1073
|
+
// page can only name a count in the second case (m00186).
|
|
1074
|
+
const reason = known > 0
|
|
1075
|
+
? `已发现 ${known} 个 dsh 工作区,但没有可用的 IDE 地址(dsh 可能刚启动,稍后会自动重试)`
|
|
1076
|
+
: 'dsh 未运行(没有记住的工作区窗口,也没有侧栏快照)'
|
|
1077
|
+
return json(res, 200, { ok: true, available: false, windows: [], dropped: droppedAt, knownWorkspaces: known, reason })
|
|
1078
|
+
}
|
|
1079
|
+
const newest = rows[0]
|
|
672
1080
|
return json(res, 200, {
|
|
673
1081
|
ok: true,
|
|
674
1082
|
available: true,
|
|
675
1083
|
url: newest.url,
|
|
676
1084
|
sessionId: newest.sessionId,
|
|
677
1085
|
cwd: newest.cwd,
|
|
678
|
-
windows:
|
|
1086
|
+
windows: rows,
|
|
679
1087
|
dropped: droppedAt,
|
|
1088
|
+
knownWorkspaces: rows.length,
|
|
680
1089
|
})
|
|
681
1090
|
}
|
|
682
1091
|
|
|
@@ -695,6 +1104,63 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
695
1104
|
return json(res, 200, proxyBridgeStatus())
|
|
696
1105
|
}
|
|
697
1106
|
|
|
1107
|
+
if (path === '/v1/proxybridge/health' && method === 'GET') {
|
|
1108
|
+
const summary = engineSummary()
|
|
1109
|
+
// Only a *known* stopped engine may skip the component check. `unknown` means
|
|
1110
|
+
// the pidfile could not be read — not that nothing is running (review A4-P2-9).
|
|
1111
|
+
const engineStopped = summary.state === 'stopped'
|
|
1112
|
+
const engineRunning = summary.state === 'running'
|
|
1113
|
+
const bridge = await redirectorStatusAsync()
|
|
1114
|
+
const interception = { linux: bridge.runningLocal === true, windows: bridge.runningWindows === true }
|
|
1115
|
+
// m11863: engine stopped + interception running is a misconfiguration, not a
|
|
1116
|
+
// health result — nothing would answer the redirected connections.
|
|
1117
|
+
const stray = { linux: engineStopped === true && interception.linux, windows: engineStopped === true && interception.windows }
|
|
1118
|
+
if (engineStopped === true) {
|
|
1119
|
+
// m11838: a stopped engine means nobody is using the component, so probing
|
|
1120
|
+
// binaries (and spawning PowerShell) would only produce red noise. This
|
|
1121
|
+
// route stays read-only: starting/stopping the component is the reconciler's
|
|
1122
|
+
// single decision (review A4-P2-7), so a health poll cannot race a teardown
|
|
1123
|
+
// or spin an elevation prompt of its own.
|
|
1124
|
+
return json(res, 200, { ok: null, checked: false, engineRunning: false, engineState: summary.state, interception, elevations: elevationState(), stray, lastStart: lastBridgeStart, commands: bridgeCommands(), degrade: bridgeDegrade(), at: new Date().toISOString() })
|
|
1125
|
+
}
|
|
1126
|
+
// Probe the copy Windows actually runs (%LOCALAPPDATA%), not the Linux cache:
|
|
1127
|
+
// Windows cannot launch an exe from the Linux filesystem (m11828).
|
|
1128
|
+
let windowsExe = ''
|
|
1129
|
+
let windowsApplicable = false
|
|
1130
|
+
let windowsPrepared = false
|
|
1131
|
+
try {
|
|
1132
|
+
if (process.platform === 'win32') {
|
|
1133
|
+
// Native Windows runs the bundle in place (review A4-P1-1): there is no
|
|
1134
|
+
// Linux cache to copy from and no materialisation step at all.
|
|
1135
|
+
const exe = join(bundleApi.installDir(home), 'windows', 'ProxyBridge_CLI.exe')
|
|
1136
|
+
windowsApplicable = true
|
|
1137
|
+
windowsPrepared = existsSync(exe)
|
|
1138
|
+
if (windowsPrepared === true) windowsExe = exe
|
|
1139
|
+
} else if (isWslHost() === true) {
|
|
1140
|
+
// WSL is the only non-Windows host that can run the Windows bridge; the
|
|
1141
|
+
// copy Windows actually executes lives under %LOCALAPPDATA% (m11828).
|
|
1142
|
+
const dir = windowsBundleDir()
|
|
1143
|
+
if (typeof dir === 'string' && dir !== '') {
|
|
1144
|
+
windowsApplicable = true
|
|
1145
|
+
windowsPrepared = existsSync(join(dir, 'ProxyBridge_CLI.exe'))
|
|
1146
|
+
if (windowsPrepared === true) windowsExe = posixToWindowsPath(join(dir, 'ProxyBridge_CLI.exe'))
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
} catch { /* the card then says "本机没有 Windows 侧" instead of a wrong failure */ }
|
|
1150
|
+
const health = await bridgeHealth.get({
|
|
1151
|
+
home,
|
|
1152
|
+
// `unknown` is not "not running": only claim an engine state we know
|
|
1153
|
+
// (review A4-P2-9).
|
|
1154
|
+
engineRunning: engineRunning === true,
|
|
1155
|
+
force: url.searchParams.get('force') === '1',
|
|
1156
|
+
windowsExe,
|
|
1157
|
+
windowsApplicable,
|
|
1158
|
+
windowsPrepared,
|
|
1159
|
+
linuxApplicable: process.platform !== 'win32',
|
|
1160
|
+
})
|
|
1161
|
+
return json(res, 200, Object.assign({}, health, { engineState: summary.state, interception, elevations: elevationState(), stray, lastStart: lastBridgeStart, commands: bridgeCommands(), degrade: bridgeDegrade() }))
|
|
1162
|
+
}
|
|
1163
|
+
|
|
698
1164
|
if (path === '/v1/proxybridge/download' && method === 'POST') {
|
|
699
1165
|
// Fetching/installing the component is user-visible work: keep the daemon
|
|
700
1166
|
// from idling out from under the page while it runs (review A3-P2-3).
|
|
@@ -893,11 +1359,17 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
893
1359
|
bridgeReloadState = { at: Date.now(), ok: false, note }
|
|
894
1360
|
}
|
|
895
1361
|
}
|
|
1362
|
+
// A save does not start anything (m13920): it only reloads an enforcement
|
|
1363
|
+
// that is already running, so the note must not promise a restart the daemon
|
|
1364
|
+
// will not perform.
|
|
1365
|
+
const bridgeWasRunning = redirectorStatusCached().running === true
|
|
896
1366
|
setImmediate(() => { switchEnforcement().catch(() => {}) })
|
|
897
1367
|
return json(res, 200, {
|
|
898
1368
|
ok: true,
|
|
899
1369
|
revision: risdConfigRevision(written),
|
|
900
|
-
reloadNote:
|
|
1370
|
+
reloadNote: bridgeWasRunning
|
|
1371
|
+
? '规则已保存;系统层拦截正在后台按新规则重启'
|
|
1372
|
+
: '规则已保存;引擎未启动,保存不会启动它',
|
|
901
1373
|
git,
|
|
902
1374
|
})
|
|
903
1375
|
}
|
|
@@ -910,11 +1382,20 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
910
1382
|
if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
|
|
911
1383
|
const action = typeof parsed.action === 'string' ? parsed.action : 'status'
|
|
912
1384
|
const gitHost = typeof parsed.gitHost === 'string' ? parsed.gitHost : undefined
|
|
1385
|
+
// Only a click may raise a system password dialog (review B-P0-2): the
|
|
1386
|
+
// auto-start that follows a save calls the same route, and an implicit
|
|
1387
|
+
// action must never pop one (m13910).
|
|
1388
|
+
const interactive = parsed.interactive === true
|
|
1389
|
+
// Enforcement came up (or was already up): the stale "could not reload"
|
|
1390
|
+
// note is history, and leaving it made the restart button outlive its cause.
|
|
1391
|
+
const clearBridgeNote = () => { bridgeReloadState = { at: Date.now(), ok: true, note: '' } }
|
|
913
1392
|
let result
|
|
914
1393
|
if (action === 'start') {
|
|
915
1394
|
result = await serializeEngine(async () => {
|
|
916
1395
|
const engine = await startProxy(cwd)
|
|
917
|
-
const redirector = await serializeBridge(() => startRedirectors())
|
|
1396
|
+
const redirector = await serializeBridge(() => startRedirectors({ interactive }))
|
|
1397
|
+
noteBridgeStart(redirector)
|
|
1398
|
+
if (redirector.running === true || (Array.isArray(redirector.started) && redirector.started.length > 0)) clearBridgeNote()
|
|
918
1399
|
const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
|
|
919
1400
|
if (engine.ok === true) {
|
|
920
1401
|
engineCwd = cwd
|
|
@@ -926,6 +1407,9 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
926
1407
|
result = await serializeEngine(async () => {
|
|
927
1408
|
const git = await syncGitProxy({ cwd, host: gitHost, enabled: false })
|
|
928
1409
|
const redirector = await serializeBridge(() => stopRedirector())
|
|
1410
|
+
// The card must not keep describing a component we just stopped
|
|
1411
|
+
// (review A4-P2-8).
|
|
1412
|
+
lastBridgeStart = null
|
|
929
1413
|
const stopped = await stopProxy(cwd)
|
|
930
1414
|
if (stopped.ok === true) {
|
|
931
1415
|
engineCwd = null
|
|
@@ -949,13 +1433,16 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
949
1433
|
result = await serializeBridge(() => syncRedirector(cwd, { start: action === 'redirector-start' }))
|
|
950
1434
|
} else if (action === 'redirector-stop') {
|
|
951
1435
|
result = await serializeBridge(() => stopRedirector())
|
|
1436
|
+
lastBridgeStart = null
|
|
952
1437
|
} else if (action === 'redirector-restart') {
|
|
953
1438
|
// Stop first so nothing keeps intercepting with the parsed-at-start profile,
|
|
954
1439
|
// then start again from the profile written by the save that requested this.
|
|
955
1440
|
result = await serializeBridge(async () => {
|
|
956
1441
|
const stopped = await stopRedirector()
|
|
957
1442
|
await new Promise((resolve) => setTimeout(resolve, 300))
|
|
958
|
-
const started = await startRedirectors()
|
|
1443
|
+
const started = await startRedirectors({ interactive })
|
|
1444
|
+
noteBridgeStart(started)
|
|
1445
|
+
if (started.running === true || (Array.isArray(started.started) && started.started.length > 0)) clearBridgeNote()
|
|
959
1446
|
return {
|
|
960
1447
|
stopped,
|
|
961
1448
|
started: started.started ?? [],
|
|
@@ -1151,6 +1638,12 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1151
1638
|
const sessionId = parsed.sessionId === undefined ? null : String(parsed.sessionId)
|
|
1152
1639
|
cancelIdleExit()
|
|
1153
1640
|
const lease = leases.acquire({ ownerPid, sessionId, cwd })
|
|
1641
|
+
// The start half of 「跟随 dsh」: the policy is read when the lease arrives,
|
|
1642
|
+
// the same signal the teardown watches. Off the response path (starting the
|
|
1643
|
+
// engine costs seconds), and never interactive.
|
|
1644
|
+
if (lifecycle.proxy.followDsh === true && engineSummary().state !== 'running') {
|
|
1645
|
+
setImmediate(() => { followStartForLease(lease.cwd).catch(() => {}) })
|
|
1646
|
+
}
|
|
1154
1647
|
return json(res, 200, { ok: true, lease })
|
|
1155
1648
|
}
|
|
1156
1649
|
|
|
@@ -1218,7 +1711,7 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1218
1711
|
json(res, 200, { ok: true, restarting: true, pid: process.pid })
|
|
1219
1712
|
if (!already) {
|
|
1220
1713
|
setImmediate(() => {
|
|
1221
|
-
spawnRestartSuccessor()
|
|
1714
|
+
spawnRestartSuccessor(actualPort)
|
|
1222
1715
|
if (onShutdown !== null) onShutdown(true)
|
|
1223
1716
|
})
|
|
1224
1717
|
}
|
|
@@ -1258,6 +1751,113 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1258
1751
|
server.keepAliveTimeout = 1000
|
|
1259
1752
|
|
|
1260
1753
|
let engineInherited = false
|
|
1754
|
+
// Component health probes spawn a process per side: cache the snapshot for 30 s
|
|
1755
|
+
// and let the card's「重新检查」force it (m11828).
|
|
1756
|
+
const bridgeHealth = createHealthCache()
|
|
1757
|
+
// Minimum gap between automatic start/stop attempts (m12046/m12053): a missing
|
|
1758
|
+
// elevation must not retry on every poll, and the supervisor is only a safety net.
|
|
1759
|
+
const BRIDGE_PULL_INTERVAL_MS = 60_000
|
|
1760
|
+
/** How often the supervisor re-checks the engine ⇔ component pairing (m12060). */
|
|
1761
|
+
const BRIDGE_RECONCILE_MS = 15_000
|
|
1762
|
+
let lastBridgePullAt = 0
|
|
1763
|
+
let lastBridgeStopAt = 0
|
|
1764
|
+
let reconciling = false
|
|
1765
|
+
// m12359: when a side cannot start (Linux needs root), the CLI prints the exact
|
|
1766
|
+
// command to paste. Remember the last attempt so the health card can show it.
|
|
1767
|
+
let lastBridgeStart = null
|
|
1768
|
+
/**
|
|
1769
|
+
* The exact command a user can paste to start a side by hand.
|
|
1770
|
+
*
|
|
1771
|
+
* The health card needs it even when this process never attempted a start (the
|
|
1772
|
+
* bridge may already be running on one side, so no attempt was made): without it
|
|
1773
|
+
* the panel just says 「需要提权」 and never tells the user what to run (m12359).
|
|
1774
|
+
* @returns {{linux?: string, windows?: string}} display commands, empty when unknown.
|
|
1775
|
+
*/
|
|
1776
|
+
/**
|
|
1777
|
+
* Whether the elevation terminal for each side is still open. The helper script
|
|
1778
|
+
* owns a state file for exactly that lifetime (m12923).
|
|
1779
|
+
* @returns {{linux: object, windows: object}} per-side state.
|
|
1780
|
+
*/
|
|
1781
|
+
function elevationState() {
|
|
1782
|
+
return {
|
|
1783
|
+
linux: readElevationState('local', { home }),
|
|
1784
|
+
windows: readElevationState('windows', { home }),
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
function bridgeCommands() {
|
|
1789
|
+
try {
|
|
1790
|
+
const base = bundledBundleDir()
|
|
1791
|
+
const profilePath = redirectorProfilePath()
|
|
1792
|
+
return {
|
|
1793
|
+
linux: redirectorCommand({ cliPath: join(base, 'linux', 'ProxyBridge'), profilePath }).display,
|
|
1794
|
+
}
|
|
1795
|
+
} catch { return {} }
|
|
1796
|
+
}
|
|
1797
|
+
/**
|
|
1798
|
+
* The degraded path used when the OS-level component cannot run (m12486).
|
|
1799
|
+
*
|
|
1800
|
+
* Without root the Linux side cannot intercept; launchers can still give a program
|
|
1801
|
+
* the local CONNECT listener through env vars and JVM args. Programs that cannot be
|
|
1802
|
+
* told a proxy address (JDBC drivers, Navicat…) only work through an interception
|
|
1803
|
+
* layer, so the same payload carries the command to start one.
|
|
1804
|
+
* @returns {{httpProxyUrl: string, jvmArgs: string[], env: Record<string,string>, note: string}} degraded plan.
|
|
1805
|
+
*/
|
|
1806
|
+
function bridgeDegrade() {
|
|
1807
|
+
let listenPort = 11081
|
|
1808
|
+
try {
|
|
1809
|
+
const stored = readProxyConfig(home)
|
|
1810
|
+
if (Number.isInteger(stored.listenPort) && stored.listenPort > 0) listenPort = stored.listenPort
|
|
1811
|
+
} catch { /* default */ }
|
|
1812
|
+
const url = `http://127.0.0.1:${listenPort}`
|
|
1813
|
+
let command = ''
|
|
1814
|
+
try {
|
|
1815
|
+
command = redirectorCommand({ cliPath: join(bundledBundleDir(), 'linux', 'ProxyBridge'), profilePath: redirectorProfilePath() }).display
|
|
1816
|
+
} catch { /* the card then only shows the degraded plan */ }
|
|
1817
|
+
// git is the third degraded path (m12567): the daemon writes the global
|
|
1818
|
+
// `http.<host>.proxy` entry itself, so git/maven/npm-style clients that honour it
|
|
1819
|
+
// keep working without the OS-level component.
|
|
1820
|
+
let socksUrl = ''
|
|
1821
|
+
try {
|
|
1822
|
+
const socks = readProxyConfig(home).socks
|
|
1823
|
+
if (socks.host !== '' && socks.port > 0) socksUrl = `socks5h://${socks.host}:${socks.port}`
|
|
1824
|
+
} catch { /* keep it empty */ }
|
|
1825
|
+
let git = null
|
|
1826
|
+
try {
|
|
1827
|
+
const state = readGitProxyState()
|
|
1828
|
+
if (state.host !== '' && state.value !== '') git = { host: state.host, key: state.key, value: state.value }
|
|
1829
|
+
} catch { /* no git proxy written yet */ }
|
|
1830
|
+
return {
|
|
1831
|
+
httpProxyUrl: url,
|
|
1832
|
+
command,
|
|
1833
|
+
jvmArgs: [
|
|
1834
|
+
'-Dhttp.proxyHost=127.0.0.1',
|
|
1835
|
+
`-Dhttp.proxyPort=${listenPort}`,
|
|
1836
|
+
'-Dhttps.proxyHost=127.0.0.1',
|
|
1837
|
+
`-Dhttps.proxyPort=${listenPort}`,
|
|
1838
|
+
'-Dhttp.nonProxyHosts=localhost|127.*|[::1]',
|
|
1839
|
+
],
|
|
1840
|
+
env: { ALL_PROXY: url, HTTP_PROXY: url, HTTPS_PROXY: url, NO_PROXY: 'localhost,127.0.0.1,::1' },
|
|
1841
|
+
socksUrl,
|
|
1842
|
+
git,
|
|
1843
|
+
note: '降级:JVM 程序用下面的 -D 参数、能读环境变量的程序用 ALL_PROXY;JDBC/Navicat 这类无法注入代理的程序只能靠系统层拦截',
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
/**
|
|
1847
|
+
* Remember one bridge start attempt for the health card.
|
|
1848
|
+
* @param {{started?: object[], skipped?: object[], running?: boolean}} started - `startRedirectors()` outcome.
|
|
1849
|
+
*/
|
|
1850
|
+
function noteBridgeStart(started) {
|
|
1851
|
+
if (!started || typeof started !== 'object') return
|
|
1852
|
+
lastBridgeStart = {
|
|
1853
|
+
at: new Date().toISOString(),
|
|
1854
|
+
started: Array.isArray(started.started) ? started.started.map((item) => ({ side: item.side, pid: item.pid })) : [],
|
|
1855
|
+
skipped: Array.isArray(started.skipped)
|
|
1856
|
+
? started.skipped.map((item) => ({ side: item.side, reason: item.reason, command: item.command }))
|
|
1857
|
+
: [],
|
|
1858
|
+
running: started.running === true,
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1261
1861
|
|
|
1262
1862
|
function engineSummary() {
|
|
1263
1863
|
// `owned` means "this daemon has started the engine during its lifetime"; a
|
|
@@ -1373,10 +1973,142 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1373
1973
|
// Run the startup reconcile through the engine queue: it touches the engine
|
|
1374
1974
|
// pidfile and a user's /v1/action may already be in flight. Own pid is passed so
|
|
1375
1975
|
// the reconcile can never delete the state file of this very daemon.
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1976
|
+
/**
|
|
1977
|
+
* True when some ProxyBridge side left a pid file in this proxy home: the only
|
|
1978
|
+
* situation where a stopped engine can still have a live component (m12053).
|
|
1979
|
+
* Pure filesystem checks — no probing.
|
|
1980
|
+
*/
|
|
1981
|
+
function hasBridgePidFiles() {
|
|
1982
|
+
try {
|
|
1983
|
+
const names = [REDIRECTOR_PID_FILENAME, REDIRECTOR_PID_FILENAMES.local, REDIRECTOR_PID_FILENAMES.windows]
|
|
1984
|
+
return names.some((name) => existsSync(join(redirectorHome(), name)))
|
|
1985
|
+
} catch {
|
|
1986
|
+
return false
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
/**
|
|
1991
|
+
* Component sides this host can actually run (review A4-P2-7).
|
|
1992
|
+
*
|
|
1993
|
+
* Native Windows runs only the Windows CLI, Linux only the Linux one, and WSL can
|
|
1994
|
+
* run both — the Windows side only when the bundle has a Windows-addressable
|
|
1995
|
+
* target (%LOCALAPPDATA%). Used to decide *which* side is missing instead of the
|
|
1996
|
+
* old "both sides down" test, which left a half-started bridge alone forever.
|
|
1997
|
+
*
|
|
1998
|
+
* @returns {Array<'local'|'windows'>} side names, in start order.
|
|
1999
|
+
*/
|
|
2000
|
+
function bridgeApplicableSides() {
|
|
2001
|
+
try {
|
|
2002
|
+
if (process.platform === 'win32') return ['windows']
|
|
2003
|
+
const sides = ['local']
|
|
2004
|
+
if (isWslHost() === true && String(windowsBundleDir() ?? '') !== '') sides.push('windows')
|
|
2005
|
+
return sides
|
|
2006
|
+
} catch {
|
|
2007
|
+
return ['local']
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
/**
|
|
2012
|
+
* Keep the engine and the system-layer component consistent (m12060).
|
|
2013
|
+
*
|
|
2014
|
+
* One place decides both directions, because the pairs that otherwise drift are
|
|
2015
|
+
* many: an inherited engine after a dsh crash, a CLI that died while the engine
|
|
2016
|
+
* kept running, a manual stop of either side, a crash of the engine itself. Start
|
|
2017
|
+
* and stop stay serialized through serializeBridge, and an elevation failure is
|
|
2018
|
+
* retried at most once per minute so a page left open cannot spin UAC prompts.
|
|
2019
|
+
*
|
|
2020
|
+
* @param {string} reason - where the reconcile came from (log/debug only).
|
|
2021
|
+
* @returns {Promise<void>} resolves when the attempt is over (best effort).
|
|
2022
|
+
*/
|
|
2023
|
+
async function reconcileEngineBridge(reason) {
|
|
2024
|
+
if (reconciling === true) return
|
|
2025
|
+
if (stopping === true) return
|
|
2026
|
+
reconciling = true
|
|
2027
|
+
try {
|
|
2028
|
+
const engine = engineSummary()
|
|
2029
|
+
// `unknown` means the pidfile could not be read — not that nothing is running
|
|
2030
|
+
// (review A4-P2-9): doing nothing is the only safe answer.
|
|
2031
|
+
if (engine.state === 'unknown') return
|
|
2032
|
+
const engineRunning = engine.state === 'running'
|
|
2033
|
+
const engineStopped = engine.state === 'stopped'
|
|
2034
|
+
// Cheap gate first: probing the bridge (WSL: PowerShell, ~3 s) must not run on
|
|
2035
|
+
// every startup/poll when there is nothing to reconcile. A pid file is the
|
|
2036
|
+
// evidence that a component may be left behind after a crash (m12046/m12053).
|
|
2037
|
+
if (engineStopped === true && hasBridgePidFiles() !== true) return
|
|
2038
|
+
// Async probe: a spawnSync here would block the whole daemon (and every request
|
|
2039
|
+
// queued behind it) for the duration of the Windows PowerShell probe.
|
|
2040
|
+
const bridge = await redirectorStatusAsync()
|
|
2041
|
+
// Stopping may have begun while the probe ran: do not start/stop a bridge the
|
|
2042
|
+
// teardown is about to handle.
|
|
2043
|
+
if (stopping === true) return
|
|
2044
|
+
if (engineRunning === true) {
|
|
2045
|
+
// Only the sides this host can run matter; a half-started bridge (one side
|
|
2046
|
+
// up, one skipped) must still be completed (review A4-P2-7).
|
|
2047
|
+
const missing = bridgeApplicableSides().filter((side) => (side === 'windows' ? bridge.runningWindows !== true : bridge.runningLocal !== true))
|
|
2048
|
+
if (missing.length === 0) return
|
|
2049
|
+
if (Date.now() - lastBridgePullAt < BRIDGE_PULL_INTERVAL_MS) return
|
|
2050
|
+
lastBridgePullAt = Date.now()
|
|
2051
|
+
// Never prompt for elevation from a background pass: the page owns that.
|
|
2052
|
+
const started = await serializeBridge(() => startRedirectors({ sides: missing, interactive: false }))
|
|
2053
|
+
noteBridgeStart(started)
|
|
2054
|
+
const failed = (Array.isArray(started?.skipped) ? started.skipped : []).filter((item) => missing.includes(item.side))
|
|
2055
|
+
if (failed.length > 0) {
|
|
2056
|
+
const why = failed.map((item) => `${item.side}:${item.reason}`).join(';')
|
|
2057
|
+
process.stdout.write(`[dsh-ris-ide] 代理引擎已运行但系统层拦截未启动(${reason}):${why}\n`)
|
|
2058
|
+
}
|
|
2059
|
+
} else if (engineStopped === true && bridge.running === true) {
|
|
2060
|
+
if (Date.now() - lastBridgeStopAt < BRIDGE_PULL_INTERVAL_MS) return
|
|
2061
|
+
lastBridgeStopAt = Date.now()
|
|
2062
|
+
process.stdout.write(`[dsh-ris-ide] 代理引擎未运行:停止系统层拦截(${reason}),避免把连接转发到已关闭的端口\n`)
|
|
2063
|
+
await serializeBridge(() => stopRedirector())
|
|
2064
|
+
lastBridgeStart = null
|
|
2065
|
+
}
|
|
2066
|
+
} catch { /* elevation missing: the page shows the reason; the timer retries later */ } finally {
|
|
2067
|
+
reconciling = false
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
const bridgeSupervisor = setInterval(() => { void reconcileEngineBridge('timer') }, BRIDGE_RECONCILE_MS)
|
|
2071
|
+
bridgeSupervisor.unref?.()
|
|
2072
|
+
|
|
2073
|
+
void serializeEngine(async () => {
|
|
2074
|
+
await reconcileStartupLeftovers({
|
|
2075
|
+
ownPid: process.pid,
|
|
2076
|
+
log: (message) => { try { process.stdout.write(`${message}\n`) } catch { /* ignore */ } },
|
|
2077
|
+
})
|
|
2078
|
+
// m12046/m12053/m12060: one invariant, enforced from one place — the engine and
|
|
2079
|
+
// the component run together. Startup, health polling and the supervisor all call
|
|
2080
|
+
// this, so "engine up ⇒ component up" and "engine down ⇒ component down" cannot
|
|
2081
|
+
// drift apart (an inherited engine, a crashed CLI, a manual stop all converge).
|
|
2082
|
+
// Deliberately not awaited: probing the bridge costs seconds on WSL (PowerShell)
|
|
2083
|
+
// and `/ready` must not wait for a component that is usually absent. The
|
|
2084
|
+
// supervisor re-checks in 15 s, so a missed first pass self-heals.
|
|
2085
|
+
setImmediate(() => { void reconcileEngineBridge('startup') })
|
|
2086
|
+
|
|
2087
|
+
// Invariant (m11863): the component must not keep intercepting once the proxy
|
|
2088
|
+
// engine is gone — every redirected connection would be sent to a dead listener
|
|
2089
|
+
// and fail in a way that looks like the network broke. The engine can be absent
|
|
2090
|
+
// at startup (previous dsh stopped it, plugin fallback never ran); the bridge
|
|
2091
|
+
// may still be alive from an earlier session, so reap it here.
|
|
2092
|
+
// Only a bridge this proxy home recorded is ours to reap: a machine-wide CLI with
|
|
2093
|
+
// another profile (or a fixture daemon with an empty home) is not. And never block
|
|
2094
|
+
// `/ready` on the probe — on WSL it spawns PowerShell.
|
|
2095
|
+
// Serialized with every other bridge mutation so a user's start/stop cannot be
|
|
2096
|
+
// interleaved with this reap, and guarded by `stopping` so a shutdown that began
|
|
2097
|
+
// meanwhile is not undone by a late stop (review A4-P2-7 / startup-reap).
|
|
2098
|
+
setImmediate(() => {
|
|
2099
|
+
void serializeBridge(async () => {
|
|
2100
|
+
if (stopping === true) return
|
|
2101
|
+
if (proxyPid() !== null) return
|
|
2102
|
+
if (hasBridgePidFiles() !== true) return
|
|
2103
|
+
try {
|
|
2104
|
+
if ((await redirectorStatusAsync()).running !== true) return
|
|
2105
|
+
process.stdout.write('[dsh-ris-ide] 代理引擎未运行:停止系统层拦截,避免把连接转发到已关闭的端口\n')
|
|
2106
|
+
await stopRedirector()
|
|
2107
|
+
lastBridgeStart = null
|
|
2108
|
+
} catch { /* best effort: the next stop click retries with elevation */ }
|
|
2109
|
+
})
|
|
2110
|
+
})
|
|
2111
|
+
}).catch(() => {})
|
|
1380
2112
|
|
|
1381
2113
|
let stopping = false
|
|
1382
2114
|
/**
|
|
@@ -1389,6 +2121,7 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1389
2121
|
stopping = true
|
|
1390
2122
|
const handoff = options?.handoff === true
|
|
1391
2123
|
cancelIdleExit()
|
|
2124
|
+
clearInterval(bridgeSupervisor)
|
|
1392
2125
|
if (heartbeat !== null) {
|
|
1393
2126
|
clearInterval(heartbeat)
|
|
1394
2127
|
heartbeat = null
|
|
@@ -1453,6 +2186,9 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1453
2186
|
new Promise((resolve) => { const timer = setTimeout(resolve, teardownTimeoutMs); timer.unref?.() }),
|
|
1454
2187
|
])
|
|
1455
2188
|
engineCwd = null
|
|
2189
|
+
// Nothing is supervised anymore; the card must not keep a stale start report
|
|
2190
|
+
// (review A4-P2-8). This is also the fallback when teardown was skipped.
|
|
2191
|
+
lastBridgeStart = null
|
|
1456
2192
|
server.closeIdleConnections?.()
|
|
1457
2193
|
await new Promise((resolve) => {
|
|
1458
2194
|
const timer = setTimeout(() => {
|