dsh-ris-ide 1.7.3 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +21 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +284 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +609 -1178
  6. package/lib/index.js +1124 -55
  7. package/lib/janitor.js +106 -15
  8. package/lib/proxy.js +86 -7
  9. package/lib/proxybridge-bundle.js +798 -0
  10. package/lib/proxybridge-health.js +206 -0
  11. package/lib/redirector.js +1615 -115
  12. package/lib/risd/build.js +91 -0
  13. package/lib/risd/debug.js +374 -0
  14. package/lib/risd/git.js +207 -0
  15. package/lib/risd/leases.js +124 -0
  16. package/lib/risd/lifecycle.js +148 -0
  17. package/lib/risd/log.js +59 -0
  18. package/lib/risd/ping.js +94 -0
  19. package/lib/risd/programs.js +348 -0
  20. package/lib/risd/server.js +1919 -0
  21. package/lib/risd/state.js +137 -0
  22. package/lib/risd/ui.js +1989 -0
  23. package/lib/risd/view.js +79 -0
  24. package/lib/risd-client.js +282 -0
  25. package/lib/standalone/window.html +14 -16
  26. package/lib/startup.js +114 -0
  27. package/package.json +4 -1
  28. package/test/client-build.test.mjs +113 -0
  29. package/test/client-viewer.test.mjs +279 -227
  30. package/test/dsh-origin.test.mjs +140 -0
  31. package/test/dsh-window-refresh.test.mjs +100 -0
  32. package/test/harness.test.mjs +9 -0
  33. package/test/host-noloop.test.mjs +74 -0
  34. package/test/host-tail.test.mjs +21 -4
  35. package/test/host-window.test.mjs +4 -4
  36. package/test/janitor.test.mjs +29 -1
  37. package/test/lifecycle.test.mjs +26 -5
  38. package/test/merge-owners.test.mjs +155 -0
  39. package/test/proxy-restart.test.mjs +39 -0
  40. package/test/proxy-window.test.mjs +45 -0
  41. package/test/proxy.test.mjs +41 -0
  42. package/test/proxybridge-bundle.test.mjs +687 -0
  43. package/test/proxybridge-health.test.mjs +116 -0
  44. package/test/redirector-bundle.test.mjs +391 -0
  45. package/test/redirector.test.mjs +413 -10
  46. package/test/risd-api.test.mjs +514 -0
  47. package/test/risd-bridge-degrade.test.mjs +101 -0
  48. package/test/risd-build.test.mjs +20 -0
  49. package/test/risd-cli-home.test.mjs +50 -0
  50. package/test/risd-client.test.mjs +130 -0
  51. package/test/risd-debug.test.mjs +261 -0
  52. package/test/risd-election.test.mjs +104 -0
  53. package/test/risd-engine.test.mjs +132 -0
  54. package/test/risd-entry.test.mjs +118 -0
  55. package/test/risd-git.test.mjs +109 -0
  56. package/test/risd-handoff.test.mjs +116 -0
  57. package/test/risd-heal.test.mjs +50 -0
  58. package/test/risd-helpers.mjs +108 -0
  59. package/test/risd-host-p2.test.mjs +147 -0
  60. package/test/risd-janitor-guard.test.mjs +46 -0
  61. package/test/risd-lease.test.mjs +83 -0
  62. package/test/risd-lifecycle.test.mjs +210 -0
  63. package/test/risd-log-follow.test.mjs +227 -0
  64. package/test/risd-mode.test.mjs +161 -0
  65. package/test/risd-ping.test.mjs +99 -0
  66. package/test/risd-programs.test.mjs +169 -0
  67. package/test/risd-restart.test.mjs +104 -0
  68. package/test/risd-review-p2.test.mjs +217 -0
  69. package/test/risd-shutdown.test.mjs +97 -0
  70. package/test/risd-teardown.test.mjs +87 -0
  71. package/test/risd-tools.test.mjs +211 -0
  72. package/test/risd-ui.test.mjs +607 -0
  73. package/test/risd-write.test.mjs +170 -0
  74. package/test/startup-reconcile.test.mjs +100 -0
  75. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `risd serve` without `--home` must use the machine home, not `<cwd>/undefined`.
3
+ *
4
+ * Node coerces an assignment of `undefined` to `process.env.X` into the STRING
5
+ * "undefined"; the CLI used to do that before resolving the default, so every
6
+ * machine-level file (risd.json, token, heartbeat, git state) landed under
7
+ * `<cwd>/undefined/`. The plugin then never found the daemon, the port stayed
8
+ * taken by a ghost and `risd stop` could not reach it (review A-P0-1).
9
+ */
10
+ import assert from 'node:assert/strict'
11
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
12
+ import { tmpdir } from 'node:os'
13
+ import { join } from 'node:path'
14
+ import { spawn } from 'node:child_process'
15
+ import test from 'node:test'
16
+ import { readRisdState } from '../lib/risd/state.js'
17
+
18
+ const CLI = new URL('../bin/risd.mjs', import.meta.url).pathname
19
+
20
+ test('a CLI run without --home resolves the machine home from the environment', async (t) => {
21
+ const home = mkdtempSync(join(tmpdir(), 'risd-cli-home-'))
22
+ const cwd = mkdtempSync(join(tmpdir(), 'risd-cli-cwd-'))
23
+ const child = spawn(process.execPath, [CLI, 'serve'], {
24
+ cwd,
25
+ env: Object.assign({}, process.env, { DSH_RIS_IDE_PROXY_HOME: home, DSH_RISD_PORT: '0' }),
26
+ stdio: ['ignore', 'pipe', 'pipe'],
27
+ })
28
+ t.after(() => {
29
+ child.kill('SIGTERM')
30
+ rmSync(home, { recursive: true, force: true })
31
+ rmSync(cwd, { recursive: true, force: true })
32
+ })
33
+ let stderr = ''
34
+ child.stderr.setEncoding('utf8')
35
+ child.stderr.on('data', (chunk) => { stderr += chunk })
36
+ const started = await new Promise((resolve) => {
37
+ const timer = setInterval(() => {
38
+ const state = readRisdState(home)
39
+ if (state !== null) { clearInterval(timer); resolve(state) }
40
+ }, 100)
41
+ timer.unref()
42
+ child.once('exit', () => { clearInterval(timer); resolve(null) })
43
+ setTimeout(() => { clearInterval(timer); resolve(null) }, 8000).unref()
44
+ })
45
+ assert.notEqual(started, null, `risd serve did not start: ${stderr}`)
46
+ assert.equal(started.home, home)
47
+ // The regression: the state was written under the cwd because the env var
48
+ // became the literal string "undefined".
49
+ assert.equal(existsSync(join(cwd, 'undefined')), false)
50
+ })
@@ -0,0 +1,130 @@
1
+ /**
2
+ * risd-client: discovery, spawn, wait, lease and view — the plugin side.
3
+ *
4
+ * The daemon these tests spawn is real (same `bin/risd.mjs` the plugin forks),
5
+ * because the interesting failures are process-level: a spawn race, a stale
6
+ * state file, a daemon that answers a different apiVersion.
7
+ */
8
+ import assert from 'node:assert/strict'
9
+ import test from 'node:test'
10
+ import { createServer } from 'node:http'
11
+ import { writeFileSync } from 'node:fs'
12
+ import { RISD_API_VERSION, risdStatePath } from '../lib/risd/state.js'
13
+ import { acquireLease, ensureRisd, getProxyView, probeRisd, releaseLease, shutdownRisd } from '../lib/risd-client.js'
14
+ import { makeHome, removeHome, sleep } from './risd-helpers.mjs'
15
+
16
+ function isolate(t, home) {
17
+ const savedPort = process.env.DSH_RISD_PORT
18
+ const savedHome = process.env.DSH_RIS_IDE_PROXY_HOME
19
+ process.env.DSH_RISD_PORT = '0'
20
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
21
+ t.after(() => {
22
+ if (savedPort === undefined) delete process.env.DSH_RISD_PORT
23
+ else process.env.DSH_RISD_PORT = savedPort
24
+ if (savedHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
25
+ else process.env.DSH_RIS_IDE_PROXY_HOME = savedHome
26
+ })
27
+ }
28
+
29
+ async function waitForExit(home, timeoutMs = 5000) {
30
+ const { readRisdState } = await import('../lib/risd/state.js')
31
+ const deadline = Date.now() + timeoutMs
32
+ while (Date.now() < deadline) {
33
+ if (readRisdState(home) === null) return true
34
+ await sleep(50)
35
+ }
36
+ return false
37
+ }
38
+
39
+ test('ensureRisd spawns once, then reuses the running daemon', async (t) => {
40
+ const home = makeHome('risd-client-')
41
+ isolate(t, home)
42
+ const first = await ensureRisd({ home })
43
+ t.after(async () => {
44
+ const state = await import('../lib/risd/state.js')
45
+ const current = state.readRisdState(home)
46
+ if (current !== null) await shutdownRisd(current)
47
+ removeHome(home)
48
+ })
49
+ assert.equal(first.ok, true, first.reason)
50
+ assert.equal(first.spawned, true)
51
+ assert.equal(first.state.apiVersion, RISD_API_VERSION)
52
+
53
+ const second = await ensureRisd({ home })
54
+ assert.equal(second.ok, true)
55
+ assert.equal(second.spawned, false)
56
+ assert.equal(second.state.pid, first.state.pid)
57
+
58
+ const view = await getProxyView(first.state, '/tmp/ws')
59
+ assert.equal(view.ok, true)
60
+ assert.equal(view.workspace, '/tmp/ws')
61
+
62
+ const lease = await acquireLease(first.state, { ownerPid: process.pid, sessionId: 's', cwd: '/tmp/ws' })
63
+ assert.equal(lease.ok, true)
64
+ assert.equal(lease.body.lease.ownerPid, process.pid)
65
+ const released = await releaseLease(first.state, lease.body.lease.id)
66
+ assert.equal(released.ok, true)
67
+ assert.equal(released.body.released, true)
68
+
69
+ const shutdown = await shutdownRisd(first.state)
70
+ assert.equal(shutdown.ok, true)
71
+ assert.equal(await waitForExit(home), true, 'the daemon must remove risd.json on shutdown')
72
+ })
73
+
74
+ test('concurrent ensureRisd calls agree on one daemon', async (t) => {
75
+ const home = makeHome('risd-client-race-')
76
+ isolate(t, home)
77
+ // ONE hook: stop the daemon BEFORE deleting its home, otherwise the state file
78
+ // is gone by the time we look and the detached daemon survives the test run.
79
+ t.after(async () => {
80
+ const { readRisdState } = await import('../lib/risd/state.js')
81
+ const current = readRisdState(home)
82
+ if (current !== null) await shutdownRisd(current)
83
+ removeHome(home)
84
+ })
85
+
86
+ const [a, b] = await Promise.all([ensureRisd({ home }), ensureRisd({ home })])
87
+ assert.equal(a.ok, true, a.reason)
88
+ assert.equal(b.ok, true, b.reason)
89
+ assert.equal(a.state.pid, b.state.pid, 'both callers must see the same daemon')
90
+ assert.equal([a.spawned, b.spawned].filter(Boolean).length <= 1, true)
91
+ })
92
+
93
+ test('a stale state file is reported as unreachable, not trusted', async (t) => {
94
+ const home = makeHome('risd-client-stale-')
95
+ t.after(() => removeHome(home))
96
+ writeFileSync(
97
+ risdStatePath(home),
98
+ JSON.stringify({ apiVersion: 1, version: '0.0.0', pid: 999999, port: 9, token: 'x', home, startedAt: new Date().toISOString(), url: 'http://127.0.0.1:9' }),
99
+ )
100
+ const probe = await probeRisd({ home })
101
+ assert.equal(probe.usable, false)
102
+ assert.equal(probe.reason, 'unreachable')
103
+ })
104
+
105
+ test('a daemon speaking another apiVersion is reported as api-mismatch', async (t) => {
106
+ const home = makeHome('risd-client-mismatch-')
107
+ t.after(() => removeHome(home))
108
+ const foreign = createServer((req, res) => {
109
+ res.writeHead(200, { 'content-type': 'application/json' })
110
+ res.end(JSON.stringify({ ok: true, apiVersion: 2, pid: process.pid }))
111
+ })
112
+ await new Promise((resolve) => foreign.listen(0, '127.0.0.1', resolve))
113
+ t.after(() => foreign.close())
114
+ writeFileSync(
115
+ risdStatePath(home),
116
+ JSON.stringify({ apiVersion: 2, version: '9.0.0', pid: process.pid, port: foreign.address().port, token: 'x', home, startedAt: new Date().toISOString(), url: `http://127.0.0.1:${foreign.address().port}` }),
117
+ )
118
+ const probe = await probeRisd({ home })
119
+ assert.equal(probe.usable, false)
120
+ assert.equal(probe.reason, 'api-mismatch')
121
+
122
+ const ensured = await ensureRisd({ home })
123
+ assert.equal(ensured.ok, false)
124
+ assert.equal(ensured.reason, 'api-mismatch')
125
+ })
126
+
127
+ test('releaseLease tolerates a missing id (exit path safety)', async () => {
128
+ const result = await releaseLease({ url: 'http://127.0.0.1:9', token: 'x' }, undefined)
129
+ assert.equal(result.ok, true)
130
+ })
@@ -0,0 +1,261 @@
1
+ // Daemon-side JDWP ownership (P3): one window owns a program's session, and the
2
+ // breakpoint set survives a daemon restart as pending breakpoints (an attached
3
+ // socket cannot survive, and is not pretended to).
4
+ //
5
+ // No JVM here: the engine takes a fake JDWP client and fake start/stop hooks, so the
6
+ // test is about ownership + persistence rather than the protocol.
7
+ import assert from 'node:assert/strict'
8
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
9
+ import { tmpdir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { after, before, test } from 'node:test'
12
+ import { createDebugEngine } from '../lib/risd/debug.js'
13
+
14
+ let home
15
+ let workspace
16
+
17
+ /** The smallest fake client the session registry drives. */
18
+ function fakeClient(calls = []) {
19
+ const record = (name) => (...args) => { calls.push([name, ...args]) }
20
+ return {
21
+ isConnected: true,
22
+ vmSuspended: true,
23
+ allSuspendedThreadIds: [11n],
24
+ currentThreadId: 11n,
25
+ on() {},
26
+ connect: record('connect'),
27
+ disconnect: record('disconnect'),
28
+ getBreakpoints: () => [],
29
+ setBreakpoint: async (className, line, policy) => { calls.push(['setBreakpoint', className, line, policy]); return { requestId: 2, className, line } },
30
+ removeBreakpoint: record('removeBreakpoint'),
31
+ clearAllBreakpoints: record('clearAllBreakpoints'),
32
+ getAllThreads: async () => [{ threadId: 11n, name: 'main' }],
33
+ getFrames: async (threadId, start, max) => [{ frameId: 5n, location: { classID: 1n, methodID: 2n, index: 3n }, methodName: 'm', lineNumber: 9 }],
34
+ getFrameVariables: async () => [{ name: 'i', value: 10, signature: 'I', slot: 1, tag: 2 }],
35
+ getObjectDetails: async () => ({ kind: 'object', className: 'a.B', signature: 'La/B;', fields: [] }),
36
+ stepOver: record('stepOver'),
37
+ stepInto: record('stepInto'),
38
+ stepOut: record('stepOut'),
39
+ resumeVM: record('resumeVM'),
40
+ resumeThread: record('resumeThread'),
41
+ suspendVM: record('suspendVM'),
42
+ }
43
+ }
44
+
45
+ function engineOptions(overrides = {}) {
46
+ return Object.assign({
47
+ home,
48
+ clientFactory: () => fakeClient(),
49
+ startProgram: async (cwd, logsDir, program) => ({ program, port: 5005 }),
50
+ stopProgram: async () => ({ stopped: true }),
51
+ waitListening: async () => true,
52
+ attachTimeoutMs: 200,
53
+ }, overrides)
54
+ }
55
+
56
+ before(() => {
57
+ home = mkdtempSync(join(tmpdir(), 'risd-debug-home-'))
58
+ workspace = mkdtempSync(join(tmpdir(), 'risd-debug-ws-'))
59
+ mkdirSync(join(workspace, '.dsh-ris-ide'), { recursive: true })
60
+ writeFileSync(join(workspace, '.dsh-ris-ide', 'config.json'), `${JSON.stringify({
61
+ version: 1,
62
+ defaults: {},
63
+ programs: [
64
+ {
65
+ id: 'svc', name: 'svc', kind: 'spring', dir: workspace, relDir: '.', project: '',
66
+ logName: 'svc', logPath: join(workspace, 'logs', 'svc.log'),
67
+ startCommand: 'java ${JDWP_ARGS} -cp target/classes cn.com.ris.App',
68
+ },
69
+ {
70
+ id: 'web', name: 'web', kind: 'frontend', dir: workspace, relDir: '.', project: '',
71
+ logName: 'web', logPath: join(workspace, 'logs', 'web.log'),
72
+ },
73
+ ],
74
+ }, null, 2)}\n`)
75
+ mkdirSync(join(workspace, 'logs'), { recursive: true })
76
+ writeFileSync(join(workspace, 'logs', 'svc.log'), 'Listening for transport dt_socket at address: 5005\n')
77
+ })
78
+
79
+ after(() => {
80
+ rmSync(home, { recursive: true, force: true })
81
+ rmSync(workspace, { recursive: true, force: true })
82
+ })
83
+
84
+ test('the window that starts a session owns it; another window cannot step it', async () => {
85
+ const engine = createDebugEngine(engineOptions())
86
+ const started = await engine.run({ action: 'start', cwd: workspace, id: 'svc', sessionId: 'window-a' })
87
+ assert.equal(started.attached, true)
88
+ assert.ok(Number.isInteger(started.port) && started.port > 1024, `unexpected jdwp port ${started.port}`)
89
+ assert.equal((await engine.run({ action: 'status', cwd: workspace, id: 'svc' })).owner, 'window-a')
90
+
91
+ await assert.rejects(
92
+ () => engine.run({ action: 'step', cwd: workspace, id: 'svc', kind: 'over', sessionId: 'window-b' }),
93
+ (error) => error.code === 'debug-owned',
94
+ )
95
+ // reads are shared: the other window may still look at threads
96
+ assert.equal((await engine.run({ action: 'threads', cwd: workspace, id: 'svc', sessionId: 'window-b' })).threads.length, 1)
97
+ // the owner can step
98
+ assert.equal((await engine.run({ action: 'step', cwd: workspace, id: 'svc', kind: 'over', sessionId: 'window-a' })).stepped, 'over')
99
+ })
100
+
101
+ test('a breakpoint survives the daemon as a pending breakpoint', async () => {
102
+ const engine = createDebugEngine(engineOptions())
103
+ await engine.run({ action: 'breakpoint-add', cwd: workspace, id: 'svc', className: 'cn.com.ris.App', line: 12, sessionId: 'window-a' })
104
+ const saved = JSON.parse(readFileSync(join(home, 'risd-debug.json'), 'utf8'))
105
+ const entries = Object.values(saved.breakpoints).flat()
106
+ assert.equal(entries.length, 1)
107
+ assert.equal(entries[0].className, 'cn.com.ris.App')
108
+ assert.equal(entries[0].line, 12)
109
+
110
+ // A fresh daemon (new engine over the same home) restores it without a JVM.
111
+ const restarted = createDebugEngine(engineOptions())
112
+ const status = await restarted.run({ action: 'status', cwd: workspace, id: 'svc' })
113
+ assert.equal(status.attached, false)
114
+ assert.equal(status.breakpoints.length, 1)
115
+ assert.equal(status.breakpoints[0].pending, true)
116
+ assert.equal(status.breakpoints[0].className, 'cn.com.ris.App')
117
+ })
118
+
119
+ test('detach ends the session without stopping the program', async () => {
120
+ const calls = []
121
+ let stopped = false
122
+ const engine = createDebugEngine(engineOptions({
123
+ clientFactory: () => fakeClient(calls),
124
+ stopProgram: async () => { stopped = true; return { stopped: true } },
125
+ }))
126
+ await engine.run({ action: 'start', cwd: workspace, id: 'svc', sessionId: 'window-a' })
127
+ const detached = await engine.run({ action: 'detach', logPath: join(workspace, 'logs', 'svc.log') })
128
+ assert.equal(detached.detached, true)
129
+ assert.equal(stopped, false, 'detach must not stop the JVM')
130
+ assert.equal(await engine.size, 0)
131
+ })
132
+
133
+ test('debug start refuses non-Java rows and custom commands without the JDWP placeholder', async () => {
134
+ const engine = createDebugEngine(engineOptions())
135
+ await assert.rejects(
136
+ () => engine.run({ action: 'start', cwd: workspace, id: 'web', sessionId: 'window-a' }),
137
+ (error) => error.code === 'not-startable',
138
+ )
139
+ // custom without ${JDWP_ARGS}: rewrite the fixture config and retry
140
+ writeFileSync(join(workspace, '.dsh-ris-ide', 'config.json'), `${JSON.stringify({
141
+ version: 1,
142
+ defaults: {},
143
+ programs: [{
144
+ id: 'svc2', name: 'svc2', kind: 'spring', dir: workspace, relDir: '.', project: '',
145
+ logName: 'svc2', logPath: join(workspace, 'logs', 'svc2.log'), startCommand: 'java -cp target/classes cn.com.ris.App',
146
+ }],
147
+ }, null, 2)}\n`)
148
+ await assert.rejects(
149
+ () => engine.run({ action: 'start', cwd: workspace, id: 'svc2', sessionId: 'window-a' }),
150
+ (error) => error.code === 'not-startable',
151
+ )
152
+ })
153
+
154
+ function restoreFixture() {
155
+ writeFileSync(join(workspace, '.dsh-ris-ide', 'config.json'), `${JSON.stringify({
156
+ version: 1,
157
+ defaults: {},
158
+ programs: [{
159
+ id: 'svc', name: 'svc', kind: 'spring', dir: workspace, relDir: '.', project: '',
160
+ logName: 'svc', logPath: join(workspace, 'logs', 'svc.log'),
161
+ startCommand: 'java ${JDWP_ARGS} -cp target/classes cn.com.ris.App',
162
+ }],
163
+ }, null, 2)}\n`)
164
+ }
165
+
166
+ test('a failed attach does not leave a frozen JVM behind', async () => {
167
+ restoreFixture()
168
+ // Review B-P1-2: the JVM was started with suspend=y, attach then failed, and
169
+ // nobody was left to resume or stop it — a frozen process on a bare JDWP port.
170
+ const stopped = []
171
+ const engine = createDebugEngine(engineOptions({
172
+ clientFactory: () => { throw new Error('connect refused') },
173
+ stopProgram: async (logPath) => { stopped.push(logPath); return { stopped: true } },
174
+ }))
175
+ await assert.rejects(
176
+ () => engine.run({ action: 'start', cwd: workspace, id: 'svc', sessionId: 'window-a' }),
177
+ (error) => error.code === 'debug-failed',
178
+ )
179
+ assert.deepEqual(stopped, [join(workspace, 'logs', 'svc.log')], 'the half-started program is stopped again')
180
+ })
181
+
182
+ test('dropping owners lets the next window drive the session', async () => {
183
+ restoreFixture()
184
+ // Review B-P1-1: owner ids belonged to dsh windows that no longer exist, so a
185
+ // fresh window was locked out with 409 debug-owned until the daemon restarted.
186
+ const engine = createDebugEngine(engineOptions())
187
+ await engine.run({ action: 'start', cwd: workspace, id: 'svc', sessionId: 'window-a' })
188
+ engine.releaseOwners()
189
+ const stepped = await engine.run({ action: 'step', cwd: workspace, id: 'svc', kind: 'over', sessionId: 'window-b' })
190
+ assert.equal(stepped.stepped, 'over')
191
+ })
192
+
193
+ test('a JVM left behind by a dead daemon is reported as stale (B-P2-13)', async () => {
194
+ restoreFixture()
195
+ const logPath = join(workspace, 'logs', 'svc.log')
196
+ const engine = createDebugEngine(engineOptions({
197
+ // A real start reports the JVM pid; without it the record cannot be pruned.
198
+ startProgram: async (cwd, logsDir, program) => ({
199
+ program: Object.assign({}, program, { running: { pid: process.pid, alive: true } }),
200
+ port: 5005,
201
+ }),
202
+ }))
203
+ const started = await engine.run({ action: 'start', cwd: workspace, id: 'svc', sessionId: 'window-a' })
204
+ const saved = JSON.parse(readFileSync(join(home, 'risd-debug.json'), 'utf8'))
205
+ assert.equal(saved.sessions.length, 1)
206
+ assert.equal(saved.sessions[0].logPath, logPath)
207
+ assert.equal(saved.sessions[0].port, started.port)
208
+ assert.equal(saved.sessions[0].pid, process.pid)
209
+
210
+ // The daemon was SIGKILLed: the socket is gone but the JVM still listens on the
211
+ // random JDWP port. A new daemon must report it instead of forgetting it.
212
+ const restarted = createDebugEngine(engineOptions())
213
+ const sessions = await restarted.run({ action: 'sessions' })
214
+ assert.equal(sessions.sessions.length, 0)
215
+ assert.equal(sessions.stale.length, 1)
216
+ assert.equal(sessions.stale[0].port, started.port)
217
+ assert.equal(sessions.stale[0].pid, process.pid)
218
+ assert.equal(sessions.stale[0].logPath, logPath)
219
+
220
+ // Stopping the program clears the record on disk as well.
221
+ await restarted.run({ action: 'stop', cwd: workspace, id: 'svc', sessionId: 'window-a' })
222
+ const third = createDebugEngine(engineOptions())
223
+ assert.deepEqual((await third.run({ action: 'sessions' })).stale, [])
224
+ })
225
+
226
+ test('a stale record whose JVM is gone is dropped, not shown (B-P2-13)', async () => {
227
+ writeFileSync(join(home, 'risd-debug.json'), `${JSON.stringify({
228
+ version: 1,
229
+ breakpoints: {},
230
+ session: { logPath: join(workspace, 'logs', 'svc.log'), port: 4999, pid: 999999, startedAt: new Date().toISOString() },
231
+ }, null, 2)}\n`)
232
+ const engine = createDebugEngine(engineOptions())
233
+ assert.deepEqual((await engine.run({ action: 'sessions' })).stale, [])
234
+ })
235
+
236
+ test('a session kept only on disk is listed as stale and can be forgotten (D3)', async () => {
237
+ restoreFixture()
238
+ const logPath = join(workspace, 'logs', 'svc.log')
239
+ const engine = createDebugEngine(engineOptions({
240
+ startProgram: async (cwd, logsDir, program) => ({
241
+ program: Object.assign({}, program, { running: { pid: process.pid, alive: true } }),
242
+ port: 5005,
243
+ }),
244
+ }))
245
+ await engine.run({ action: 'start', cwd: workspace, id: 'svc', sessionId: 'window-a' })
246
+ await engine.run({ action: 'breakpoint-add', cwd: workspace, id: 'svc', className: 'cn.com.ris.App', line: 12, sessionId: 'window-a' })
247
+
248
+ // New daemon: the socket is gone (the "JVM" pid here is this test process, alive),
249
+ // so the record is stale and the page can offer to clear it.
250
+ const restarted = createDebugEngine(engineOptions())
251
+ const listed = await restarted.run({ action: 'sessions' })
252
+ assert.equal(listed.sessions.length, 0)
253
+ assert.equal(listed.stale.length, 1)
254
+ assert.equal(listed.stale[0].logPath, logPath)
255
+ const forgotten = await restarted.run({ action: 'forget', logPath })
256
+ assert.equal(forgotten.forgotten, true)
257
+ assert.equal((await restarted.run({ action: 'sessions' })).stale.length, 0)
258
+ const saved = JSON.parse(readFileSync(join(home, 'risd-debug.json'), 'utf8'))
259
+ assert.deepEqual(saved.breakpoints, {})
260
+ assert.equal(saved.sessions, undefined)
261
+ })
@@ -0,0 +1,104 @@
1
+ /**
2
+ * risd election: one daemon per machine.
3
+ *
4
+ * The three outcomes a spawner must be able to tell apart are:
5
+ * - another risd already owns the port -> harmless, exit 0, do NOT touch its state;
6
+ * - a daemon speaking another `/v1` version owns it -> upgrade required, exit 3;
7
+ * - something that is not risd owns it -> actionable diagnosis, exit 4.
8
+ *
9
+ * Killing by pid is never part of any of them, so the tests also assert that a
10
+ * losing spawner leaves the winner's token untouched.
11
+ */
12
+ import assert from 'node:assert/strict'
13
+ import test from 'node:test'
14
+ import { readFileSync } from 'node:fs'
15
+ import { createServer } from 'node:http'
16
+ import { readRisdState, risdStatePath } from '../lib/risd/state.js'
17
+ import { makeHome, removeHome, runRisdCli, startRisdProcess } from './risd-helpers.mjs'
18
+
19
+ test('a second daemon reports already-running and leaves the state alone', async (t) => {
20
+ const home = makeHome()
21
+ t.after(() => removeHome(home))
22
+ const first = await startRisdProcess({ home })
23
+ t.after(() => first.stop())
24
+ const token = readRisdState(home).token
25
+
26
+ const second = await runRisdCli(['serve', '--home', home, '--port', String(first.state.port)])
27
+ assert.equal(second.code, 0, second.err)
28
+ assert.match(second.err, /already running/)
29
+ assert.equal(readRisdState(home).token, token, 'the loser must not overwrite the winner state')
30
+ assert.equal(readRisdState(home).pid, first.state.pid)
31
+ })
32
+
33
+ test('a foreign listener on another apiVersion yields exit 3', async (t) => {
34
+ const home = makeHome()
35
+ t.after(() => removeHome(home))
36
+ const foreign = createServer((req, res) => {
37
+ if (req.url === '/v1/health') {
38
+ res.writeHead(200, { 'content-type': 'application/json' })
39
+ res.end(JSON.stringify({ ok: true, apiVersion: 2, pid: process.pid }))
40
+ return
41
+ }
42
+ res.writeHead(404)
43
+ res.end()
44
+ })
45
+ await new Promise((resolve) => foreign.listen(0, '127.0.0.1', resolve))
46
+ t.after(() => foreign.close())
47
+ const port = foreign.address().port
48
+
49
+ const result = await runRisdCli(['serve', '--home', home, '--port', String(port)])
50
+ assert.equal(result.code, 3, result.err)
51
+ assert.match(result.err, /upgrade required/)
52
+ })
53
+
54
+ test('a legacy /v1 daemon (no apiVersion) yields exit 3 as well', async (t) => {
55
+ const home = makeHome()
56
+ t.after(() => removeHome(home))
57
+ const foreign = createServer((req, res) => {
58
+ res.writeHead(200, { 'content-type': 'application/json' })
59
+ res.end(JSON.stringify({ ok: true, pid: process.pid }))
60
+ })
61
+ await new Promise((resolve) => foreign.listen(0, '127.0.0.1', resolve))
62
+ t.after(() => foreign.close())
63
+
64
+ const result = await runRisdCli(['serve', '--home', home, '--port', String(foreign.address().port)])
65
+ assert.equal(result.code, 3, result.err)
66
+ })
67
+
68
+ test('a port occupied by something that is not risd yields exit 4 and a diagnosis', async (t) => {
69
+ const home = makeHome()
70
+ t.after(() => removeHome(home))
71
+ const foreign = createServer((req, res) => {
72
+ res.writeHead(404, { 'content-type': 'text/plain' })
73
+ res.end('not here')
74
+ })
75
+ await new Promise((resolve) => foreign.listen(0, '127.0.0.1', resolve))
76
+ t.after(() => foreign.close())
77
+
78
+ const result = await runRisdCli(['serve', '--home', home, '--port', String(foreign.address().port)])
79
+ assert.equal(result.code, 4, result.err)
80
+ assert.match(result.err, /occupied/)
81
+ assert.match(result.err, /--port/)
82
+ })
83
+
84
+ test('serve writes state 0600 in a 0700 home and removes it on shutdown', async (t) => {
85
+ const home = makeHome()
86
+ t.after(() => removeHome(home))
87
+ const daemon = await startRisdProcess({ home })
88
+ const path = risdStatePath(home)
89
+ const state = readRisdState(home)
90
+ assert.match(state.token, /^[0-9a-f]{64}$/)
91
+ assert.equal(state.apiVersion, 1)
92
+ assert.equal(state.pid, daemon.state.pid)
93
+ assert.ok(state.port > 0)
94
+
95
+ const { statSync } = await import('node:fs')
96
+ assert.equal(statSync(path).mode & 0o777, 0o600)
97
+ assert.equal(statSync(home).mode & 0o777, 0o700)
98
+
99
+ const stopped = await runRisdCli(['stop', '--home', home])
100
+ assert.equal(stopped.code, 0, stopped.err)
101
+ assert.equal(readRisdState(home), null)
102
+ assert.throws(() => readFileSync(path, 'utf8'))
103
+ void daemon
104
+ })
@@ -0,0 +1,132 @@
1
+ /**
2
+ * /v1/engine: the daemon starts and stops the proxy engine (Phase 1b P1).
3
+ *
4
+ * Phase 1a only read the pidfile; this pins the ownership hand-off: the daemon
5
+ * performs the real start/stop, serializes concurrent presses, and reports the
6
+ * same pid the pidfile/`/v1/health` see.
7
+ */
8
+ import assert from 'node:assert/strict'
9
+ import test from 'node:test'
10
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
13
+ import { RISD_API_VERSION, risdStatePath } from '../lib/risd/state.js'
14
+ import { makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
15
+
16
+ function pickPort() {
17
+ return 20000 + Math.floor(Math.random() * 20000)
18
+ }
19
+
20
+ function writeEngineFixture(home, port) {
21
+ const config = {
22
+ socks: { host: '127.0.0.1', port: 1, dbPort: 0, redisPort: 0 },
23
+ listenPort: port,
24
+ rules: [
25
+ {
26
+ id: 'rule-1',
27
+ program: 'java',
28
+ hosts: ['127.0.0.1'],
29
+ ports: ['443'],
30
+ enabled: true,
31
+ shadow: false,
32
+ source: 'user',
33
+ workspace: home,
34
+ },
35
+ ],
36
+ }
37
+ writeFileSync(join(home, 'proxy.json'), JSON.stringify(config, null, 2))
38
+ }
39
+
40
+ function headers(state) {
41
+ return { authorization: `Bearer ${state.token}`, 'x-risd-api-version': String(RISD_API_VERSION), 'content-type': 'application/json' }
42
+ }
43
+
44
+ async function waitFor(fn, timeoutMs = 8000) {
45
+ const deadline = Date.now() + timeoutMs
46
+ while (Date.now() < deadline) {
47
+ if (await fn()) return true
48
+ await sleep(120)
49
+ }
50
+ return false
51
+ }
52
+
53
+ test('the daemon starts/stops the engine and reports one pid everywhere', async (t) => {
54
+ const home = makeHome('risd-engine-')
55
+ const cwd = mkdtempSync(join(tmpdir(), 'risd-engine-ws-'))
56
+ writeEngineFixture(home, pickPort())
57
+ const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
58
+ t.after(async () => {
59
+ await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: headers(daemon.state), body: JSON.stringify({ action: 'stop', cwd }) }).catch(() => {})
60
+ await daemon.stop()
61
+ removeHome(home)
62
+ rmSync(cwd, { recursive: true, force: true })
63
+ })
64
+
65
+ const started = await fetch(`${daemon.state.url}/v1/engine`, {
66
+ method: 'POST',
67
+ headers: headers(daemon.state),
68
+ body: JSON.stringify({ action: 'start', cwd }),
69
+ })
70
+ const startBody = await started.json()
71
+ assert.equal(started.status, 200)
72
+ assert.equal(startBody.ok, true, JSON.stringify(startBody))
73
+ assert.equal(startBody.result.ok, true, JSON.stringify(startBody.result))
74
+ const pid = startBody.result.pid
75
+ assert.equal(Number.isInteger(pid) && pid > 0, true)
76
+ assert.equal(existsSync(join(home, 'proxy.pid')), true, 'the daemon must own the pidfile')
77
+
78
+ const read = await (await fetch(`${daemon.state.url}/v1/engine?cwd=${encodeURIComponent(cwd)}`, { headers: headers(daemon.state) })).json()
79
+ assert.equal(read.engine.owned, true)
80
+ assert.equal(read.engine.running, true)
81
+ assert.equal(read.engine.pid, pid)
82
+
83
+ const health = await (await fetch(`${daemon.state.url}/v1/health`)).json()
84
+ assert.equal(health.engine.pid, pid, '/v1/health and /v1/engine must agree')
85
+ assert.equal(health.engine.owned, true)
86
+
87
+ const stopped = await (await fetch(`${daemon.state.url}/v1/engine`, {
88
+ method: 'POST',
89
+ headers: headers(daemon.state),
90
+ body: JSON.stringify({ action: 'stop', cwd }),
91
+ })).json()
92
+ assert.equal(stopped.ok, true)
93
+ assert.equal(stopped.result.stopped, true)
94
+ assert.equal(await waitFor(() => !existsSync(join(home, 'proxy.pid'))), true)
95
+
96
+ const after = await (await fetch(`${daemon.state.url}/v1/engine?cwd=${encodeURIComponent(cwd)}`, { headers: headers(daemon.state) })).json()
97
+ assert.equal(after.engine.running, false)
98
+ assert.equal(after.engine.owned, false)
99
+ })
100
+
101
+ test('engine requests are validated and serialized', async (t) => {
102
+ const home = makeHome('risd-engine-')
103
+ const cwd = mkdtempSync(join(tmpdir(), 'risd-engine-ws-'))
104
+ writeEngineFixture(home, pickPort())
105
+ const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
106
+ t.after(async () => {
107
+ await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: headers(daemon.state), body: JSON.stringify({ action: 'stop', cwd }) }).catch(() => {})
108
+ await daemon.stop()
109
+ removeHome(home)
110
+ rmSync(cwd, { recursive: true, force: true })
111
+ })
112
+
113
+ const bad = await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: headers(daemon.state), body: JSON.stringify({ action: 'restart', cwd }) })
114
+ assert.equal(bad.status, 400)
115
+ const relative = await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: headers(daemon.state), body: JSON.stringify({ action: 'start', cwd: 'relative/path' }) })
116
+ assert.equal(relative.status, 400)
117
+ const noAuth = await fetch(`${daemon.state.url}/v1/engine?cwd=/tmp/ws`)
118
+ assert.equal(noAuth.status, 401)
119
+
120
+ // Two concurrent presses: both answer, one engine, no duplicate listeners.
121
+ const [a, b] = await Promise.all(['start', 'start'].map((action) => fetch(`${daemon.state.url}/v1/engine`, {
122
+ method: 'POST',
123
+ headers: headers(daemon.state),
124
+ body: JSON.stringify({ action, cwd }),
125
+ }).then((res) => res.json())))
126
+ assert.equal(a.ok && b.ok, true)
127
+ const first = a.result.pid || b.result.pid
128
+ assert.equal(Number.isInteger(first) && first > 0, true)
129
+ const status = await (await fetch(`${daemon.state.url}/v1/status?cwd=${encodeURIComponent(cwd)}`, { headers: headers(daemon.state) })).json()
130
+ assert.equal(status.running, true)
131
+ assert.equal(status.pid, first)
132
+ })