dsh-ris-ide 1.7.2 → 1.8.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.
- package/README.md +43 -4
- package/bin/check-listing.mjs +247 -0
- package/bin/proxy-janitor.mjs +183 -0
- package/bin/risd.mjs +287 -0
- package/bin/run-with-log.ps1 +43 -5
- package/lib/client-codemirror.js +92 -66
- package/lib/client.js +774 -89
- package/lib/index.js +2256 -21
- package/lib/janitor.js +377 -0
- package/lib/proxy.js +1577 -0
- package/lib/proxybridge-bundle.js +798 -0
- package/lib/redirector.js +2558 -0
- package/lib/risd/build.js +91 -0
- package/lib/risd/debug.js +374 -0
- package/lib/risd/git.js +207 -0
- package/lib/risd/leases.js +124 -0
- package/lib/risd/lifecycle.js +148 -0
- package/lib/risd/log.js +59 -0
- package/lib/risd/ping.js +94 -0
- package/lib/risd/programs.js +348 -0
- package/lib/risd/server.js +1478 -0
- package/lib/risd/state.js +137 -0
- package/lib/risd/ui.js +1705 -0
- package/lib/risd/view.js +79 -0
- package/lib/risd-client.js +282 -0
- package/lib/standalone/window.html +14 -16
- package/lib/startup.js +114 -0
- package/package.json +7 -2
- package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
- package/test/client-build.test.mjs +113 -0
- package/test/client-viewer.test.mjs +314 -20
- package/test/companion.test.mjs +65 -0
- package/test/dsh-origin.test.mjs +140 -0
- package/test/dsh-window-refresh.test.mjs +100 -0
- package/test/harness.test.mjs +9 -0
- package/test/host-noloop.test.mjs +74 -0
- package/test/host-tail.test.mjs +54 -5
- package/test/host-window.test.mjs +4 -4
- package/test/inherit-engine.test.mjs +175 -0
- package/test/install-phase.test.mjs +36 -0
- package/test/janitor.test.mjs +172 -0
- package/test/lifecycle.test.mjs +109 -0
- package/test/merge-owners.test.mjs +155 -0
- package/test/proxy-restart.test.mjs +37 -0
- package/test/proxy-route.test.mjs +599 -0
- package/test/proxy-window.test.mjs +45 -0
- package/test/proxy.test.mjs +914 -0
- package/test/proxybridge-bundle.test.mjs +687 -0
- package/test/redirector-bundle.test.mjs +391 -0
- package/test/redirector.test.mjs +571 -0
- package/test/risd-api.test.mjs +470 -0
- package/test/risd-bridge-degrade.test.mjs +101 -0
- package/test/risd-build.test.mjs +20 -0
- package/test/risd-cli-home.test.mjs +50 -0
- package/test/risd-client.test.mjs +130 -0
- package/test/risd-debug.test.mjs +261 -0
- package/test/risd-election.test.mjs +104 -0
- package/test/risd-engine.test.mjs +132 -0
- package/test/risd-entry.test.mjs +118 -0
- package/test/risd-git.test.mjs +109 -0
- package/test/risd-handoff.test.mjs +116 -0
- package/test/risd-heal.test.mjs +50 -0
- package/test/risd-helpers.mjs +108 -0
- package/test/risd-host-p2.test.mjs +147 -0
- package/test/risd-janitor-guard.test.mjs +46 -0
- package/test/risd-lease.test.mjs +83 -0
- package/test/risd-lifecycle.test.mjs +210 -0
- package/test/risd-log-follow.test.mjs +227 -0
- package/test/risd-mode.test.mjs +161 -0
- package/test/risd-ping.test.mjs +99 -0
- package/test/risd-programs.test.mjs +169 -0
- package/test/risd-review-p2.test.mjs +217 -0
- package/test/risd-shutdown.test.mjs +97 -0
- package/test/risd-teardown.test.mjs +87 -0
- package/test/risd-tools.test.mjs +211 -0
- package/test/risd-ui.test.mjs +445 -0
- package/test/risd-write.test.mjs +170 -0
- package/test/startup-reconcile.test.mjs +100 -0
- package/test/windows.test.mjs +37 -2
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which maintenance-page code a risd process is RUNNING, versus what is on disk now.
|
|
3
|
+
*
|
|
4
|
+
* Why this exists: `/ui` is generated by the daemon from modules that Node imported
|
|
5
|
+
* once at startup, so editing `ui.js` (or any daemon module) and reloading the page
|
|
6
|
+
* does NOT show the new code — the process still runs the old module. The browser
|
|
7
|
+
* cache is already handled (`cache-control: no-store`, the page embeds everything),
|
|
8
|
+
* so the only stale layer is the daemon's own module graph. This stamp names both
|
|
9
|
+
* layers: `loaded` is taken at startup, `disk` is recomputed per request. The page
|
|
10
|
+
* reloads itself when `loaded` changes (a restarted daemon = new page code) and
|
|
11
|
+
* shows a 「重启 daemon 生效」 hint while the two disagree (edited but not reloaded).
|
|
12
|
+
*
|
|
13
|
+
* The stamp is filesystem metadata only (size + mtime), never file contents: fifteen
|
|
14
|
+
* `statSync` calls per health poll are free, hashing fifteen sources is not. A
|
|
15
|
+
* same-size edit made within the same mtime tick could in theory hide a change, which
|
|
16
|
+
* is the same assumption the dsh host's own client-module revision makes.
|
|
17
|
+
*
|
|
18
|
+
* @module dsh-risd/build
|
|
19
|
+
*/
|
|
20
|
+
import { createHash } from 'node:crypto'
|
|
21
|
+
import { statSync } from 'node:fs'
|
|
22
|
+
import { fileURLToPath } from 'node:url'
|
|
23
|
+
|
|
24
|
+
/** Daemon modules whose code the maintenance page renders: a change means restart. */
|
|
25
|
+
export const UI_SOURCE_FILES = [
|
|
26
|
+
'server.js',
|
|
27
|
+
'ui.js',
|
|
28
|
+
'ping.js',
|
|
29
|
+
'lifecycle.js',
|
|
30
|
+
'programs.js',
|
|
31
|
+
'debug.js',
|
|
32
|
+
'view.js',
|
|
33
|
+
'state.js',
|
|
34
|
+
'log.js',
|
|
35
|
+
'leases.js',
|
|
36
|
+
'git.js',
|
|
37
|
+
'../proxy.js',
|
|
38
|
+
'../proxybridge-bundle.js',
|
|
39
|
+
'../janitor.js',
|
|
40
|
+
'../redirector.js',
|
|
41
|
+
'../startup.js',
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
const HERE = fileURLToPath(new URL('.', import.meta.url))
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* `/v1/health` reports `disk` on every poll, and the page polls it every few
|
|
48
|
+
* seconds. Sixteen `statSync` calls per poll are cheap but pointless: the daemon
|
|
49
|
+
* code cannot change under a running process (a change only takes effect after a
|
|
50
|
+
* restart), so a short cache is invisible to the page (allowed to lag up to 5 s).
|
|
51
|
+
*/
|
|
52
|
+
export const BUILD_STAMP_TTL_MS = 5000
|
|
53
|
+
|
|
54
|
+
let cachedStamp = { value: '', at: 0 }
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Identify the daemon code currently on disk.
|
|
58
|
+
*
|
|
59
|
+
* @returns {string} 12 hex chars; stable while the files are, changes with any edit.
|
|
60
|
+
*/
|
|
61
|
+
export function buildStamp() {
|
|
62
|
+
const now = Date.now()
|
|
63
|
+
if (cachedStamp.value !== '' && now - cachedStamp.at < BUILD_STAMP_TTL_MS) return cachedStamp.value
|
|
64
|
+
const hash = createHash('sha1')
|
|
65
|
+
for (const name of UI_SOURCE_FILES) {
|
|
66
|
+
hash.update(name)
|
|
67
|
+
hash.update('\0')
|
|
68
|
+
try {
|
|
69
|
+
const stat = statSync(new URL(name, new URL('.', import.meta.url)))
|
|
70
|
+
hash.update(String(stat.size))
|
|
71
|
+
hash.update(':')
|
|
72
|
+
hash.update(String(stat.mtimeMs))
|
|
73
|
+
} catch {
|
|
74
|
+
// A file that is not there (a trimmed install) must not make the stamp throw;
|
|
75
|
+
// the name alone still participates, so adding it later changes the stamp.
|
|
76
|
+
hash.update('absent')
|
|
77
|
+
}
|
|
78
|
+
hash.update('\n')
|
|
79
|
+
}
|
|
80
|
+
const value = hash.digest('hex').slice(0, 12)
|
|
81
|
+
cachedStamp = { value, at: now }
|
|
82
|
+
return value
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Drop the cache (tests that copy the daemon modules and mutate their mtimes). */
|
|
86
|
+
export const __test = {
|
|
87
|
+
resetBuildStampCache() { cachedStamp = { value: '', at: 0 } },
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The directory the daemon modules live in (exposed for tests that touch a copy). */
|
|
91
|
+
export const UI_SOURCE_DIR = HERE
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
// JDWP debug sessions owned by the daemon (Phase 2-lite P3).
|
|
2
|
+
//
|
|
3
|
+
// Why the daemon and not the plugin: a JDWP session is a single socket to one JVM —
|
|
4
|
+
// two dsh windows cannot both attach, and a plugin restart (page reload, dsh restart)
|
|
5
|
+
// must not drop a paused service. So the session lives next to the supervisor:
|
|
6
|
+
// start-with-JDWP, breakpoints, threads/frames/variables, stepping are daemon state.
|
|
7
|
+
//
|
|
8
|
+
// What is deliberately NOT here: the panel UI (stepping buttons, gutter dots) stays
|
|
9
|
+
// in the plugin, which reads this state. Breakpoints survive a daemon restart by
|
|
10
|
+
// being written to `risd-debug.json` and restored as *pending* breakpoints (they are
|
|
11
|
+
// installed once the JVM connects again, exactly like a gutter click on a stopped
|
|
12
|
+
// program). An attached socket cannot survive, and is not pretended to.
|
|
13
|
+
//
|
|
14
|
+
// Ownership: the daemon may host sessions for several dsh windows, so the first
|
|
15
|
+
// window to `start` a program owns it. Reads are shared; mutating actions from any
|
|
16
|
+
// other window get `debug-owned` (409) instead of silently stepping someone else's
|
|
17
|
+
// paused thread.
|
|
18
|
+
import { mkdirSync, readFileSync, writeFileSync, rmSync, renameSync } from 'node:fs'
|
|
19
|
+
import { join } from 'node:path'
|
|
20
|
+
import {
|
|
21
|
+
SUSPEND_POLICIES,
|
|
22
|
+
allocateDebugPort,
|
|
23
|
+
createDebugSessions,
|
|
24
|
+
DebugError,
|
|
25
|
+
waitForJdwpListening,
|
|
26
|
+
} from '../debug/engine.js'
|
|
27
|
+
import { findProgram, listPrograms, logsDirFor } from './programs.js'
|
|
28
|
+
import { startProgram, stopLogPath } from '../index.js'
|
|
29
|
+
import { pidAlive } from '../proxy.js'
|
|
30
|
+
|
|
31
|
+
/** File holding breakpoints across daemon restarts. */
|
|
32
|
+
export const DEBUG_STATE_FILENAME = 'risd-debug.json'
|
|
33
|
+
/** How long a JDWP attach may wait for the JVM's "Listening for transport" line. */
|
|
34
|
+
export const DEBUG_ATTACH_TIMEOUT_MS = 90_000
|
|
35
|
+
|
|
36
|
+
const DEFAULT_OWNER = ''
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Keep only the fields we wrote ourselves: a hand-edited or half-written file must
|
|
40
|
+
* never inject a bogus port/pid into the page.
|
|
41
|
+
* @param value - candidate `session` value from risd-debug.json.
|
|
42
|
+
* @returns `{ logPath, port, pid, startedAt }` or null.
|
|
43
|
+
*/
|
|
44
|
+
function normalizeSession(value) {
|
|
45
|
+
if (value === null || typeof value !== 'object') return null
|
|
46
|
+
const logPath = typeof value.logPath === 'string' ? value.logPath : ''
|
|
47
|
+
const port = Number(value.port)
|
|
48
|
+
const pid = Number(value.pid)
|
|
49
|
+
const startedAt = typeof value.startedAt === 'string' ? value.startedAt : ''
|
|
50
|
+
if (logPath === '' || !Number.isInteger(port) || port <= 0) return null
|
|
51
|
+
return { logPath, port, pid: Number.isInteger(pid) && pid > 0 ? pid : 0, startedAt }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Read the persisted breakpoint sets and known JDWP addresses.
|
|
56
|
+
* @param home - risd home directory.
|
|
57
|
+
* @returns `{ version, breakpoints, sessions }` (empty on a missing/corrupt file).
|
|
58
|
+
*/
|
|
59
|
+
export function readDebugState(home) {
|
|
60
|
+
try {
|
|
61
|
+
const parsed = JSON.parse(readFileSync(join(home, DEBUG_STATE_FILENAME), 'utf8'))
|
|
62
|
+
if (parsed === null || typeof parsed !== 'object' || parsed.version !== 1) {
|
|
63
|
+
return { version: 1, breakpoints: {}, sessions: [] }
|
|
64
|
+
}
|
|
65
|
+
const breakpoints = parsed.breakpoints !== null && typeof parsed.breakpoints === 'object' ? parsed.breakpoints : {}
|
|
66
|
+
// `session` (single) is the first release of this field; accept it so an
|
|
67
|
+
// upgraded daemon does not forget an address written by an older one.
|
|
68
|
+
const raw = Array.isArray(parsed.sessions) ? parsed.sessions : (parsed.session !== undefined ? [parsed.session] : [])
|
|
69
|
+
const sessions = raw.map(normalizeSession).filter((entry) => entry !== null)
|
|
70
|
+
return { version: 1, breakpoints, sessions }
|
|
71
|
+
} catch {
|
|
72
|
+
return { version: 1, breakpoints: {}, sessions: [] }
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Atomically write the persisted breakpoint sets (0600 in a 0700 home). */
|
|
77
|
+
export function writeDebugState(home, state) {
|
|
78
|
+
try {
|
|
79
|
+
mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
80
|
+
const target = join(home, DEBUG_STATE_FILENAME)
|
|
81
|
+
const tmp = `${target}.${process.pid}.tmp`
|
|
82
|
+
writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
83
|
+
renameSync(tmp, target)
|
|
84
|
+
} catch {
|
|
85
|
+
// Debugging must keep working even when the home is read-only.
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Forget every persisted breakpoint (used by `clear` when no session exists). */
|
|
90
|
+
export function removeDebugState(home) {
|
|
91
|
+
try {
|
|
92
|
+
rmSync(join(home, DEBUG_STATE_FILENAME), { force: true })
|
|
93
|
+
} catch {
|
|
94
|
+
// best effort
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function policyOf(value) {
|
|
99
|
+
return SUSPEND_POLICIES.has(value) ? value : 'thread'
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Create the daemon-side debug owner.
|
|
104
|
+
* @param options - `{ home, clientFactory?, startProgram?, stopProgram?, waitListening?, attachTimeoutMs? }`
|
|
105
|
+
* (tests inject a fake JDWP client and fake start/stop so no JVM is needed).
|
|
106
|
+
* @returns the state used by the HTTP layer and the plugin.
|
|
107
|
+
*/
|
|
108
|
+
export function createDebugEngine(options = {}) {
|
|
109
|
+
const home = options.home
|
|
110
|
+
const sessions = createDebugSessions({ clientFactory: options.clientFactory })
|
|
111
|
+
const startProgramImpl = options.startProgram ?? startProgram
|
|
112
|
+
const stopProgramImpl = options.stopProgram ?? stopLogPath
|
|
113
|
+
const waitListening = options.waitListening ?? waitForJdwpListening
|
|
114
|
+
const attachTimeoutMs = Number.isFinite(options.attachTimeoutMs) ? options.attachTimeoutMs : DEBUG_ATTACH_TIMEOUT_MS
|
|
115
|
+
/** logPath → sessionId of the window that started the session. */
|
|
116
|
+
const owners = new Map()
|
|
117
|
+
/** logPaths whose breakpoint set must be persisted. */
|
|
118
|
+
const known = new Set()
|
|
119
|
+
/** logPath → {cwd,id,name,kind} of the program behind a session (for the page). */
|
|
120
|
+
const programIndex = new Map()
|
|
121
|
+
|
|
122
|
+
// Restore: everything we knew becomes a *pending* breakpoint, which is installed
|
|
123
|
+
// by the next `start` (same path as a gutter click on a stopped program).
|
|
124
|
+
const restored = readDebugState(home)
|
|
125
|
+
for (const [logPath, list] of Object.entries(restored.breakpoints)) {
|
|
126
|
+
if (!Array.isArray(list)) continue
|
|
127
|
+
for (const entry of list) {
|
|
128
|
+
if (entry === null || typeof entry !== 'object') continue
|
|
129
|
+
const line = Number(entry.line)
|
|
130
|
+
if (typeof entry.className !== 'string' || !Number.isInteger(line) || line <= 0) continue
|
|
131
|
+
sessions.addBreakpoint(logPath, entry.className, line, policyOf(entry.suspendPolicy)).catch(() => {})
|
|
132
|
+
known.add(logPath)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// A JDWP socket dies with the daemon but the JVM it attached to does not, so a
|
|
137
|
+
// SIGKILLed daemon leaves a JVM listening on a random port that nothing knows
|
|
138
|
+
// about. Record the session's address/pid and let a new daemon report it as
|
|
139
|
+
// stale instead of forgetting it (review B-P2-13).
|
|
140
|
+
const sessionRecords = new Map()
|
|
141
|
+
for (const record of restored.sessions) {
|
|
142
|
+
if (record.pid > 0 && pidAlive(record.pid) !== true) continue
|
|
143
|
+
sessionRecords.set(record.logPath, record)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Persist every known program's breakpoints (pending ones included). */
|
|
147
|
+
function persist() {
|
|
148
|
+
const breakpoints = {}
|
|
149
|
+
for (const logPath of known) {
|
|
150
|
+
const list = sessions.listBreakpoints(logPath) ?? []
|
|
151
|
+
if (list.length === 0) continue
|
|
152
|
+
breakpoints[logPath] = list.map((entry) => ({
|
|
153
|
+
className: entry.className,
|
|
154
|
+
line: entry.line,
|
|
155
|
+
suspendPolicy: policyOf(entry.suspendPolicy),
|
|
156
|
+
}))
|
|
157
|
+
}
|
|
158
|
+
const state = { version: 1, breakpoints }
|
|
159
|
+
if (sessionRecords.size > 0) state.sessions = [...sessionRecords.values()]
|
|
160
|
+
writeDebugState(home, state)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** One program row from the daemon's own list (404 when unknown). */
|
|
164
|
+
async function programOf(cwd, id, dir) {
|
|
165
|
+
const listed = await listPrograms(cwd, { dir })
|
|
166
|
+
const program = findProgram(listed.programs, String(id ?? ''))
|
|
167
|
+
if (program === null || program === undefined) throw new DebugError('unknown-program', `未知程序:${id}`)
|
|
168
|
+
return Object.assign({}, program, { _logsDir: listed.dir })
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** A program necessarily has a log path (that is the pidfile/session key). */
|
|
172
|
+
function logPathOf(program) {
|
|
173
|
+
if (typeof program.logPath !== 'string' || program.logPath === '') {
|
|
174
|
+
throw new DebugError('no-jdwp', `程序 ${program.id} 没有日志路径,无法作为调试会话的键`)
|
|
175
|
+
}
|
|
176
|
+
return program.logPath
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Read actions allowed from any window; mutating actions only from the owner. */
|
|
180
|
+
function assertOwner(logPath, sessionId) {
|
|
181
|
+
const owner = owners.get(logPath)
|
|
182
|
+
if (owner === undefined || owner === DEFAULT_OWNER) return
|
|
183
|
+
if (String(sessionId ?? '') !== owner) {
|
|
184
|
+
throw new DebugError('debug-owned', `这个程序的调试会话由另一个窗口占用(${owner});请在那里操作或先停止调试`)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function statusOf(program) {
|
|
189
|
+
const logPath = logPathOf(program)
|
|
190
|
+
const status = sessions.status(logPath)
|
|
191
|
+
return Object.assign({ ok: true, program: { id: program.id, name: program.name, kind: program.kind, logPath }, owner: owners.get(logPath) ?? null }, status)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async function start(cwd, id, dir, body) {
|
|
195
|
+
const program = await programOf(cwd, id, dir)
|
|
196
|
+
if (program.kind !== 'spring') {
|
|
197
|
+
throw new DebugError('not-startable', '只有 Spring(Java) 程序支持调试(前端程序没有 JVM)')
|
|
198
|
+
}
|
|
199
|
+
const custom = typeof program.startCommand === 'string' ? program.startCommand : ''
|
|
200
|
+
if (custom.trim() !== '' && !custom.includes('${JDWP_ARGS}')) {
|
|
201
|
+
throw new DebugError(
|
|
202
|
+
'not-startable',
|
|
203
|
+
'该程序配置了自定义 startCommand,调试需要 JDWP 参数:请在 java 后面加 ${JDWP_ARGS}(调试时替换成 -agentlib:jdwp=…,普通启动时替换为空)',
|
|
204
|
+
)
|
|
205
|
+
}
|
|
206
|
+
const logPath = logPathOf(program)
|
|
207
|
+
assertOwner(logPath, body.sessionId)
|
|
208
|
+
const port = await allocateDebugPort()
|
|
209
|
+
if (program.running !== null && program.running !== undefined && program.running.alive === true) {
|
|
210
|
+
await stopProgramImpl(logPath, program.stopGraceMs)
|
|
211
|
+
}
|
|
212
|
+
await sessions.detach(logPath).catch(() => {})
|
|
213
|
+
const suspendAtStartup = body.suspend === true || (body.suspend !== false && sessions.pendingCount(logPath) > 0)
|
|
214
|
+
const started = await startProgramImpl(cwd, program._logsDir ?? logsDirFor(cwd, dir), Object.assign({}, program, { running: null }), {
|
|
215
|
+
debug: { port, suspend: suspendAtStartup },
|
|
216
|
+
})
|
|
217
|
+
try {
|
|
218
|
+
await waitListening(logPath, port, attachTimeoutMs)
|
|
219
|
+
const snapshot = await sessions.attach(started.program ?? program, port)
|
|
220
|
+
if (suspendAtStartup && Number(snapshot.installedPending || 0) === 0) {
|
|
221
|
+
await sessions.resume(logPath).catch(() => {})
|
|
222
|
+
}
|
|
223
|
+
owners.set(logPath, String(body.sessionId ?? ''))
|
|
224
|
+
programIndex.set(logPath, { cwd, id: program.id, name: program.name, kind: program.kind })
|
|
225
|
+
known.add(logPath)
|
|
226
|
+
sessionRecords.set(logPath, {
|
|
227
|
+
logPath,
|
|
228
|
+
port,
|
|
229
|
+
pid: Number(started?.program?.running?.pid ?? started?.pid ?? 0) || 0,
|
|
230
|
+
startedAt: new Date().toISOString(),
|
|
231
|
+
})
|
|
232
|
+
persist()
|
|
233
|
+
return Object.assign({ ok: true, port, suspendAtStartup }, snapshot)
|
|
234
|
+
} catch (error) {
|
|
235
|
+
// A failed attach used to leave a JVM frozen on the JDWP port: nobody was
|
|
236
|
+
// attached to resume it and no session knew about it (review B-P1-2).
|
|
237
|
+
await sessions.detach(logPath).catch(() => {})
|
|
238
|
+
await stopProgramImpl(logPath, program.stopGraceMs).catch(() => {})
|
|
239
|
+
owners.delete(logPath)
|
|
240
|
+
programIndex.delete(logPath)
|
|
241
|
+
sessionRecords.delete(logPath)
|
|
242
|
+
persist()
|
|
243
|
+
throw new DebugError('debug-failed', `服务已以调试模式启动(JDWP 127.0.0.1:${port}),但 attach 失败:${error?.message ?? error}`)
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function stop(cwd, id, dir) {
|
|
248
|
+
const program = await programOf(cwd, id, dir)
|
|
249
|
+
const logPath = logPathOf(program)
|
|
250
|
+
await sessions.detach(logPath).catch(() => {})
|
|
251
|
+
const stopped = await stopProgramImpl(logPath, program.stopGraceMs)
|
|
252
|
+
owners.delete(logPath)
|
|
253
|
+
programIndex.delete(logPath)
|
|
254
|
+
sessionRecords.delete(logPath)
|
|
255
|
+
persist()
|
|
256
|
+
return { ok: true, detached: true, stopped }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* One mutating/reading action from the plugin.
|
|
261
|
+
* @param body - `{ cwd, id, dir, action, sessionId, ...actionArgs }`
|
|
262
|
+
* @returns JSON-safe outcome.
|
|
263
|
+
*/
|
|
264
|
+
async function run(body) {
|
|
265
|
+
const cwd = body.cwd
|
|
266
|
+
const dir = typeof body.dir === 'string' ? body.dir : ''
|
|
267
|
+
const action = String(body.action ?? '')
|
|
268
|
+
// Session-wide actions do not name a program (the maintenance page lists them).
|
|
269
|
+
if (action === 'sessions') {
|
|
270
|
+
// A JVM left behind by a dead daemon has no session, but it still owns its
|
|
271
|
+
// port: report it so the page can offer to stop it (review B-P2-13).
|
|
272
|
+
let pruned = false
|
|
273
|
+
for (const [logPath, record] of sessionRecords) {
|
|
274
|
+
if (record.pid > 0 && pidAlive(record.pid) !== true) {
|
|
275
|
+
sessionRecords.delete(logPath)
|
|
276
|
+
pruned = true
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (pruned) persist()
|
|
280
|
+
// The page lists every session and needs to stop the JVM behind it, so carry
|
|
281
|
+
// the program identity (cwd/id) that only the start call knows.
|
|
282
|
+
const list = sessions.listSessions().map((row) => Object.assign({}, row, programIndex.get(row.logPath) ?? {}))
|
|
283
|
+
const attached = new Set(list.map((row) => row.logPath))
|
|
284
|
+
const stale = [...sessionRecords.values()].filter((record) => !attached.has(record.logPath))
|
|
285
|
+
return { ok: true, sessions: list, stale }
|
|
286
|
+
}
|
|
287
|
+
if (action === 'forget') {
|
|
288
|
+
// Drop the persisted breakpoint set of a session that no longer exists
|
|
289
|
+
// (a JVM left by a dead daemon). Review D3: the page must be able to clear it.
|
|
290
|
+
const logPath = String(body.logPath ?? '')
|
|
291
|
+
if (logPath === '') throw new DebugError('bad-argument', 'logPath is required')
|
|
292
|
+
owners.delete(logPath)
|
|
293
|
+
// Drop both halves of a stale record: the dead-JVM address AND the breakpoint
|
|
294
|
+
// set it kept alive, otherwise "clear" left the row's purpose on disk.
|
|
295
|
+
const hadRecord = sessionRecords.delete(logPath)
|
|
296
|
+
known.delete(logPath)
|
|
297
|
+
await sessions.clearBreakpoints(logPath).catch(() => {})
|
|
298
|
+
persist()
|
|
299
|
+
return { ok: true, forgotten: true, logPath, hadRecord }
|
|
300
|
+
}
|
|
301
|
+
if (action === 'detach') {
|
|
302
|
+
const logPath = String(body.logPath ?? '')
|
|
303
|
+
if (logPath === '') throw new DebugError('bad-argument', 'logPath is required')
|
|
304
|
+
await sessions.detach(logPath).catch(() => {})
|
|
305
|
+
owners.delete(logPath)
|
|
306
|
+
return { ok: true, detached: true, logPath }
|
|
307
|
+
}
|
|
308
|
+
if (action === 'start') return start(cwd, body.id, dir, body)
|
|
309
|
+
const program = await programOf(cwd, body.id, dir)
|
|
310
|
+
const logPath = logPathOf(program)
|
|
311
|
+
const mutating = new Set([
|
|
312
|
+
'stop', 'breakpoint-add', 'breakpoint-remove', 'breakpoint-clear',
|
|
313
|
+
'step', 'resume', 'pause',
|
|
314
|
+
])
|
|
315
|
+
if (mutating.has(action)) assertOwner(logPath, body.sessionId)
|
|
316
|
+
switch (action) {
|
|
317
|
+
case 'stop': return stop(cwd, body.id, dir)
|
|
318
|
+
case 'status': return statusOf(program)
|
|
319
|
+
case 'events': return Object.assign({ ok: true }, sessions.poll(logPath, Number(body.since ?? 0) || 0))
|
|
320
|
+
case 'breakpoints': return { ok: true, breakpoints: sessions.listBreakpoints(logPath) }
|
|
321
|
+
case 'breakpoint-add': {
|
|
322
|
+
const added = await sessions.addBreakpoint(logPath, String(body.className ?? ''), Number(body.line), policyOf(body.suspendPolicy))
|
|
323
|
+
known.add(logPath)
|
|
324
|
+
persist()
|
|
325
|
+
return Object.assign({ ok: true }, added)
|
|
326
|
+
}
|
|
327
|
+
case 'breakpoint-remove': {
|
|
328
|
+
const removed = await sessions.removeBreakpoint(logPath, body.requestId, body.className, Number(body.line))
|
|
329
|
+
known.add(logPath)
|
|
330
|
+
persist()
|
|
331
|
+
return Object.assign({ ok: true }, removed)
|
|
332
|
+
}
|
|
333
|
+
case 'breakpoint-clear': {
|
|
334
|
+
const cleared = await sessions.clearBreakpoints(logPath)
|
|
335
|
+
known.add(logPath)
|
|
336
|
+
persist()
|
|
337
|
+
return Object.assign({ ok: true }, cleared)
|
|
338
|
+
}
|
|
339
|
+
case 'threads': return { ok: true, threads: await sessions.threads(logPath) }
|
|
340
|
+
case 'stack': return { ok: true, frames: await sessions.stack(logPath, body.threadId, Number(body.start ?? 0), Number(body.max ?? 50)) }
|
|
341
|
+
case 'variables': return { ok: true, variables: await sessions.variables(logPath, body.threadId, Number(body.frameIndex ?? 0)) }
|
|
342
|
+
case 'expand': return { ok: true, object: await sessions.expand(logPath, body.objectId) }
|
|
343
|
+
case 'step': return Object.assign({ ok: true }, await sessions.step(logPath, String(body.kind ?? 'over'), body.threadId))
|
|
344
|
+
case 'resume': return Object.assign({ ok: true }, await sessions.resume(logPath, body.threadId))
|
|
345
|
+
case 'pause': return Object.assign({ ok: true }, await sessions.pause(logPath))
|
|
346
|
+
default:
|
|
347
|
+
throw new DebugError('bad-argument', `unknown debug action "${action}"`)
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Detach everything (daemon shutdown); breakpoints stay persisted. */
|
|
352
|
+
async function stopAll() {
|
|
353
|
+
await sessions.detachAll().catch(() => {})
|
|
354
|
+
// Owner ids belong to dsh windows that are gone; keeping them made every new
|
|
355
|
+
// window fail mutating actions with 409 debug-owned forever (review B-P1-1).
|
|
356
|
+
owners.clear()
|
|
357
|
+
programIndex.clear()
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Forget which dsh window owns a session; used when the last daemon lease ends. */
|
|
361
|
+
function releaseOwners() {
|
|
362
|
+
owners.clear()
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
return {
|
|
366
|
+
run,
|
|
367
|
+
statusOf,
|
|
368
|
+
programOf,
|
|
369
|
+
stopAll,
|
|
370
|
+
releaseOwners,
|
|
371
|
+
get size() { return sessions.size },
|
|
372
|
+
get persistedPath() { return join(home, DEBUG_STATE_FILENAME) },
|
|
373
|
+
}
|
|
374
|
+
}
|
package/lib/risd/git.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* risd — the scoped `git config --global` entry (Phase 1b P5).
|
|
3
|
+
*
|
|
4
|
+
* The plugin used to own this: `syncGitProxy` decided which remote host the tunnel
|
|
5
|
+
* is for and wrote a single `http.https://<host>/.proxy = socks5h://…` key (plus
|
|
6
|
+
* the Windows-side git config, which cannot resolve internal hosts). Ownership
|
|
7
|
+
* moves here together with the bridge, for the same reason: the git entry is a
|
|
8
|
+
* machine-level side effect, and whoever owns the engine must be able to undo it
|
|
9
|
+
* when the last lease goes away.
|
|
10
|
+
*
|
|
11
|
+
* Kept byte-compatible with the plugin's implementation (same file, same shape,
|
|
12
|
+
* same precedence) so a machine that switches between `daemonMode=off` and `auto`
|
|
13
|
+
* does not end up with two different entries.
|
|
14
|
+
*
|
|
15
|
+
* @module dsh-risd/git
|
|
16
|
+
*/
|
|
17
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
18
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
19
|
+
import { dirname, join } from 'node:path'
|
|
20
|
+
import { gitProxyPlan, proxyHomeDir, readProxyConfig, runWindowsGitConfig } from '../proxy.js'
|
|
21
|
+
import { programKey } from '../proxy.js'
|
|
22
|
+
|
|
23
|
+
export const GIT_PROXY_STATE_FILENAME = 'git-proxy.json'
|
|
24
|
+
|
|
25
|
+
export function gitProxyStatePath() {
|
|
26
|
+
return join(proxyHomeDir(), GIT_PROXY_STATE_FILENAME)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function readGitProxyState() {
|
|
30
|
+
try {
|
|
31
|
+
const raw = JSON.parse(readFileSync(gitProxyStatePath(), 'utf8'))
|
|
32
|
+
return {
|
|
33
|
+
key: typeof raw?.key === 'string' ? raw.key : '',
|
|
34
|
+
host: typeof raw?.host === 'string' ? raw.host : '',
|
|
35
|
+
// What we actually wrote. Recorded so teardown can tell OUR entry from one a
|
|
36
|
+
// human (or another tool) has since replaced (E7: clear by ownership).
|
|
37
|
+
value: typeof raw?.value === 'string' ? raw.value : '',
|
|
38
|
+
}
|
|
39
|
+
} catch {
|
|
40
|
+
return { key: '', host: '' }
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function writeGitProxyState(state) {
|
|
45
|
+
const path = gitProxyStatePath()
|
|
46
|
+
if (state === null) {
|
|
47
|
+
try { rmSync(path, { force: true }) } catch { /* nothing to clear */ }
|
|
48
|
+
return
|
|
49
|
+
}
|
|
50
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
51
|
+
writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 })
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Run `git config --global …`; never throws, always resolves. */
|
|
55
|
+
export function runGitConfig(args) {
|
|
56
|
+
return new Promise((resolve) => {
|
|
57
|
+
let child
|
|
58
|
+
try {
|
|
59
|
+
child = spawn('git', ['config', '--global', ...args], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
60
|
+
} catch (error) {
|
|
61
|
+
resolve({ ok: false, error: String(error?.message ?? error) })
|
|
62
|
+
return
|
|
63
|
+
}
|
|
64
|
+
let stderr = ''
|
|
65
|
+
child.stderr?.on('data', (chunk) => { stderr += String(chunk) })
|
|
66
|
+
child.on('error', (error) => resolve({ ok: false, error: String(error?.message ?? error) }))
|
|
67
|
+
child.on('close', (code) => resolve(code === 0 ? { ok: true } : { ok: false, error: stderr.trim() || `git config exited ${code}` }))
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Current `git config --global --get <key>` value, or '' when unset. */
|
|
72
|
+
function gitConfigValue(key) {
|
|
73
|
+
if (key === '') return ''
|
|
74
|
+
const out = spawnSync('git', ['config', '--global', '--get', key], {
|
|
75
|
+
encoding: 'utf8', windowsHide: true, timeout: 4000,
|
|
76
|
+
})
|
|
77
|
+
if (out.status !== 0 || typeof out.stdout !== 'string') return ''
|
|
78
|
+
return out.stdout.trim()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function gitOriginHost(cwd) {
|
|
82
|
+
const out = spawnSync('git', ['-C', cwd, 'config', '--get', 'remote.origin.url'], {
|
|
83
|
+
encoding: 'utf8', windowsHide: true, timeout: 4000,
|
|
84
|
+
})
|
|
85
|
+
if (out.status !== 0 || typeof out.stdout !== 'string') return ''
|
|
86
|
+
try { return new URL(out.stdout.trim()).host } catch { return '' }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function gitRuleHost(cwd) {
|
|
90
|
+
const rules = readProxyConfig(cwd).rules
|
|
91
|
+
for (const rule of rules) {
|
|
92
|
+
if (rule.enabled !== true) continue
|
|
93
|
+
if (programKey(rule.program) !== 'git') continue
|
|
94
|
+
const first = String(rule.hosts ?? '').split(',')[0].trim()
|
|
95
|
+
if (first !== '') return first
|
|
96
|
+
}
|
|
97
|
+
return ''
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Write or clear the git entry. Precedence is the plugin's, deliberately: explicit
|
|
102
|
+
* host → the table's own git rule → the host we wrote last time → repo origin.
|
|
103
|
+
* A mirror is not a target, so origin comes last.
|
|
104
|
+
*/
|
|
105
|
+
export async function syncGitProxy({ cwd, host, enabled }) {
|
|
106
|
+
const previous = readGitProxyState()
|
|
107
|
+
if (enabled !== true) {
|
|
108
|
+
// E7: only undo an entry we wrote. `clearGitProxy()` compares the CURRENT
|
|
109
|
+
// value with the recorded one, so a proxy the user set by hand survives.
|
|
110
|
+
const key = previous.key
|
|
111
|
+
if (key === '') return { ok: true, key: '' }
|
|
112
|
+
const cleared = await clearGitProxy()
|
|
113
|
+
return {
|
|
114
|
+
ok: true,
|
|
115
|
+
key,
|
|
116
|
+
cleared: cleared.cleared === true || cleared.skipped === 'already-gone',
|
|
117
|
+
windowsCleared: cleared.windowsCleared === true,
|
|
118
|
+
...(cleared.skipped === undefined ? {} : { skipped: cleared.skipped }),
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const target = (typeof host === 'string' && host !== '')
|
|
122
|
+
? host
|
|
123
|
+
: (gitRuleHost(cwd) || (previous.host !== '' ? previous.host : gitOriginHost(cwd)))
|
|
124
|
+
if (target === '') return { ok: false, error: '没有 git 规则也没有 origin,无法确定代理作用域', key: '' }
|
|
125
|
+
if (previous.key !== '' && previous.host !== '' && previous.host !== target) {
|
|
126
|
+
// Same ownership check on the switch path: never unset a value somebody else
|
|
127
|
+
// put in place (review B-P0-1).
|
|
128
|
+
await clearGitProxy()
|
|
129
|
+
}
|
|
130
|
+
const plan = gitProxyPlan(readProxyConfig(cwd), { host: target, enabled: true })
|
|
131
|
+
if (plan.value === '') return { ok: false, error: '没有可用的 SOCKS 地址', key: plan.key }
|
|
132
|
+
const written = await runGitConfig([plan.key, plan.value])
|
|
133
|
+
if (written.ok !== true) return { ok: false, error: written.error, key: plan.key }
|
|
134
|
+
const windows = runWindowsGitConfig([plan.key, plan.value])
|
|
135
|
+
writeGitProxyState({ key: plan.key, host: target, value: plan.value, windows: windows.ok === true })
|
|
136
|
+
return { ok: true, key: plan.key, host: target, windows }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Host of the first enabled `git` rule in a table (pure: no disk read).
|
|
141
|
+
* @param {object} config - engine config.
|
|
142
|
+
* @returns {string} host pattern, or '' when the table declares no git tunnel.
|
|
143
|
+
*/
|
|
144
|
+
export function enabledGitRuleHost(config) {
|
|
145
|
+
const rules = Array.isArray(config?.rules) ? config.rules : []
|
|
146
|
+
for (const rule of rules) {
|
|
147
|
+
if (rule?.enabled !== true) continue
|
|
148
|
+
if (programKey(rule.program) !== 'git') continue
|
|
149
|
+
const first = String(rule.hosts ?? '').split(',')[0].trim()
|
|
150
|
+
if (first !== '') return first
|
|
151
|
+
}
|
|
152
|
+
return ''
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Re-align the scoped git entry with the table that was just saved.
|
|
157
|
+
*
|
|
158
|
+
* The save path used to write `proxy.json` and reload the bridge only, leaving the
|
|
159
|
+
* `git config --global` entry of the PREVIOUS host in place: editing/deleting the
|
|
160
|
+
* git rule kept every terminal pointed at a dead tunnel ("旧代理无法取消"). The
|
|
161
|
+
* table is the source of truth, so:
|
|
162
|
+
* - a git rule still exists → syncGitProxy() switches to it (it unsets the old
|
|
163
|
+
* host-scoped key first, and only when the recorded value is still ours);
|
|
164
|
+
* - no git rule survives → clear whatever we wrote before.
|
|
165
|
+
*
|
|
166
|
+
* @param {{cwd: string, host?: string}} options - workspace and an optional explicit host.
|
|
167
|
+
* @returns {Promise<{ok: boolean, host?: string, changed: boolean, cleared?: object, error?: string}>} outcome.
|
|
168
|
+
*/
|
|
169
|
+
export async function reconcileGitProxy({ cwd, host = '' } = {}) {
|
|
170
|
+
const target = (typeof host === 'string' && host !== '') ? host : enabledGitRuleHost(readProxyConfig(cwd))
|
|
171
|
+
if (target === '') {
|
|
172
|
+
const previous = readGitProxyState()
|
|
173
|
+
if (previous.key === '') return { ok: true, changed: false }
|
|
174
|
+
const cleared = await clearGitProxy()
|
|
175
|
+
return { ok: true, changed: true, cleared }
|
|
176
|
+
}
|
|
177
|
+
const applied = await syncGitProxy({ cwd, host: target, enabled: true })
|
|
178
|
+
return {
|
|
179
|
+
ok: applied.ok === true,
|
|
180
|
+
host: target,
|
|
181
|
+
changed: true,
|
|
182
|
+
...(applied.ok === true ? {} : { error: applied.error }),
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Undo whatever we wrote, on both sides. Used by teardown; never throws.
|
|
188
|
+
*
|
|
189
|
+
* E7 (ownership): the entry is only unset when it is still OURS — the recorded
|
|
190
|
+
* value, or (for state written before `value` was recorded) a `socks5h://` value,
|
|
191
|
+
* which is the shape this module always writes. A key that somebody replaced with
|
|
192
|
+
* their own proxy must survive our teardown; only our stale bookkeeping is dropped.
|
|
193
|
+
*/
|
|
194
|
+
export async function clearGitProxy() {
|
|
195
|
+
const previous = readGitProxyState()
|
|
196
|
+
if (previous.key === '') return { ok: true, key: '', skipped: 'nothing-recorded' }
|
|
197
|
+
const current = gitConfigValue(previous.key)
|
|
198
|
+
const ours = current !== '' && (previous.value !== '' ? current === previous.value : current.startsWith('socks5h://'))
|
|
199
|
+
if (ours !== true) {
|
|
200
|
+
writeGitProxyState(null)
|
|
201
|
+
return { ok: true, key: previous.key, skipped: current === '' ? 'already-gone' : 'foreign-value', current }
|
|
202
|
+
}
|
|
203
|
+
const cleared = await runGitConfig(['--unset', previous.key])
|
|
204
|
+
const windowsCleared = runWindowsGitConfig(['--unset', previous.key])
|
|
205
|
+
writeGitProxyState(null)
|
|
206
|
+
return { ok: true, key: previous.key, cleared: cleared.ok === true, windowsCleared: windowsCleared.ok === true }
|
|
207
|
+
}
|