dsh-ris-ide 1.7.3 → 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 +19 -7
- package/bin/proxy-janitor.mjs +106 -11
- package/bin/risd.mjs +287 -0
- package/bin/run-with-log.ps1 +43 -5
- package/lib/client.js +515 -1152
- package/lib/index.js +1124 -55
- package/lib/janitor.js +106 -15
- package/lib/proxy.js +86 -7
- package/lib/proxybridge-bundle.js +798 -0
- package/lib/redirector.js +484 -35
- 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 +4 -1
- package/test/client-build.test.mjs +113 -0
- package/test/client-viewer.test.mjs +166 -200
- 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 +21 -4
- package/test/host-window.test.mjs +4 -4
- package/test/janitor.test.mjs +29 -1
- package/test/lifecycle.test.mjs +26 -5
- package/test/merge-owners.test.mjs +155 -0
- package/test/proxy-restart.test.mjs +37 -0
- package/test/proxy-window.test.mjs +45 -0
- package/test/proxy.test.mjs +41 -0
- package/test/proxybridge-bundle.test.mjs +687 -0
- package/test/redirector-bundle.test.mjs +391 -0
- package/test/redirector.test.mjs +59 -9
- 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,118 @@
|
|
|
1
|
+
// Entry points into the daemon page and the `risd` CLI name.
|
|
2
|
+
//
|
|
3
|
+
// Why: the daemon page embeds the IDE and can switch workspace, so it replaced
|
|
4
|
+
// both "open the IDE window" buttons. The page is served by the daemon, whose
|
|
5
|
+
// origin the client cannot guess — the host view has to report it. And the CLI is
|
|
6
|
+
// `risd <cmd>` (the package exposes bin.risd), not `node bin/risd.mjs`.
|
|
7
|
+
import assert from 'node:assert/strict'
|
|
8
|
+
import { readFileSync } from 'node:fs'
|
|
9
|
+
import test from 'node:test'
|
|
10
|
+
|
|
11
|
+
const client = readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
|
|
12
|
+
const host = readFileSync(new URL('../lib/index.js', import.meta.url), 'utf8')
|
|
13
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
|
|
14
|
+
const bin = readFileSync(new URL('../bin/risd.mjs', import.meta.url), 'utf8')
|
|
15
|
+
|
|
16
|
+
test('both IDE entry points open the risd page, with the window as fallback', () => {
|
|
17
|
+
assert.match(client, /async function openRisdPage\(scope, fallback\)/, 'one shared opener')
|
|
18
|
+
// Header ⧉ and the sidebar console ⧉ both go through it.
|
|
19
|
+
assert.equal((client.match(/await openRisdPage\(/g) ?? []).length, 2, 'two entry points')
|
|
20
|
+
// The page lives on the daemon origin and is reused by tab name.
|
|
21
|
+
assert.match(client, /window\.open\(target, 'dsh-risd-ui'\)/)
|
|
22
|
+
// The entry point preselects the workspace but does not switch the tab anymore
|
|
23
|
+
// (m11345): the maintenance page keeps whatever tab the user was on.
|
|
24
|
+
assert.match(client, /\?cwd=' \+ encodeURIComponent\(cwd\) : ''/)
|
|
25
|
+
assert.doesNotMatch(client, /'tab=ide' \+/)
|
|
26
|
+
assert.match(client, /target = risd\.url \+ '\/ui' \+ query/)
|
|
27
|
+
// Without a daemon (daemonMode=off) the old standalone window still works.
|
|
28
|
+
assert.ok((client.match(/openStandaloneWindow\(/g) ?? []).length >= 2, 'fallbacks stay in place')
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
test('the host view reports the daemon page address', () => {
|
|
32
|
+
// proxyView (daemonMode=off ⇒ available:false) and mergeRisdView both carry it.
|
|
33
|
+
assert.equal((host.match(/risd: risdBridge !== null && risdBridge\.state !== null/g) ?? []).length, 2)
|
|
34
|
+
assert.match(host, /url: risdBridge\.state\.url, port: risdBridge\.state\.port/)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
test('neither console carries a proxy button any more', () => {
|
|
38
|
+
assert.doesNotMatch(client, /consoleConfigActions\.push\(button\('🌐'/, 'console 🌐 removed')
|
|
39
|
+
// The sidebar's compact bar lost its 🌐 too: rules live on the risd page.
|
|
40
|
+
assert.doesNotMatch(client, /data-action': 'compact-proxy'/)
|
|
41
|
+
assert.doesNotMatch(client, /compactProxyOpen/)
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
test('the CLI is `risd`, exposed through package.json', () => {
|
|
45
|
+
assert.deepEqual(pkg.bin, { risd: 'bin/risd.mjs' })
|
|
46
|
+
assert.match(bin, /^#!\/usr\/bin\/env node/)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
test('clicking ⧉ starts a stopped daemon instead of falling back to the old window', () => {
|
|
50
|
+
// The client asks the host to spawn it when the proxy view says unavailable…
|
|
51
|
+
assert.match(client, /routeUrl\('dsh-ris-ide\/risd\/ensure'\)\.href, \{ method: 'POST' \}/)
|
|
52
|
+
// The cold path: an empty prefetch hands over to `ensure`, and its answer is cached.
|
|
53
|
+
assert.match(client, /if \(risd === null\) \{[\s\S]{0,400}routeUrl\('dsh-ris-ide\/risd\/ensure'\)\.href, \{ method: 'POST' \}/)
|
|
54
|
+
assert.match(client, /risd = rememberRisdAddress\(risdAddressOf\(body\)\)/)
|
|
55
|
+
// …and the host exposes a loopback-only POST that calls ensureRisd.
|
|
56
|
+
assert.match(host, /pathname === RISD_ENSURE_PATH/)
|
|
57
|
+
assert.match(host, /if \(method !== 'POST'\) \{\s+writeJson\(res, 405/)
|
|
58
|
+
assert.match(host, /async function serveRisdEnsure\(ctx, req, res, options\)/)
|
|
59
|
+
assert.match(host, /ensureRisd\(\{ home: proxyHomeDir\(\) \}\)/)
|
|
60
|
+
assert.match(host, /url: `http:\/\/127\.0\.0\.1:\$\{state\.port\}`/)
|
|
61
|
+
// Once spawned the page lands on the IDE tab, same as a normal click.
|
|
62
|
+
assert.match(client, /\?cwd=' \+ encodeURIComponent\(cwd\) : ''/)
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
test('an agent can start the daemon from what the errors say', () => {
|
|
66
|
+
// CLI: `risd status|health` on a stopped daemon prints the command that starts it.
|
|
67
|
+
assert.match(bin, /hint: run `risd serve` to start it \(clicking ⧉ in dsh also starts it\)/)
|
|
68
|
+
// Tools: a tool call re-spawns the daemon once before falling back to local.
|
|
69
|
+
assert.match(host, /const healDaemon = async \(\) => \{/)
|
|
70
|
+
assert.match(host, /const ensured = await ensureRisd\(\{ home: proxyHomeDir\(\) \}\)\.catch/)
|
|
71
|
+
assert.match(host, /noteRisdHealFailure\(ensured\.reason/)
|
|
72
|
+
assert.match(host, /if \(risdHealBlocked\(now\)\) return null/, 'a tripped breaker stops the heal')
|
|
73
|
+
assert.match(host, /const healed = await healDaemon\(\)/) // C-P2-2: the result is also warned about
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
test('off mode refuses to raise a daemon, so the two owners never overlap', async () => {
|
|
77
|
+
// C2-P0-1: a daemon unconditionally arms the heartbeat and its own janitor, and
|
|
78
|
+
// the janitor REPLACES a watcher owned by another pid. Starting one from off mode
|
|
79
|
+
// silently removed the plugin's crash cleanup and a daemon crash tore down the
|
|
80
|
+
// engine the plugin was still using. The route answers "unavailable" and the
|
|
81
|
+
// client falls back to the standalone window.
|
|
82
|
+
assert.match(host, /if \(options\.daemonMode !== 'auto'\) \{\n[\s\S]{0,300}daemonMode=off:IDE 请用独立窗口/)
|
|
83
|
+
assert.doesNotMatch(host, /显式请求启动了 risd/)
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
test('a hot reload from off to auto drops the legacy exit hook and janitor', async () => {
|
|
87
|
+
// Review C-P1-6: the exit hook, heartbeat and janitor installed by an earlier
|
|
88
|
+
// apply stay in the process across a profile hot reload; in auto mode the daemon
|
|
89
|
+
// owns all three and two owners would fight over the engine.
|
|
90
|
+
assert.match(host, /function releaseLegacyLifecycle\(\) \{/)
|
|
91
|
+
assert.match(host, /if \(options\.daemonMode === 'auto'\) \{\n\s+\/\/ Switching off→auto[\s\S]{0,300}releaseLegacyLifecycle\(\)/)
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
test('an api-version mismatch is a "restart dsh" answer, not a failed start (C-P2-1)', () => {
|
|
95
|
+
// The daemon's own 409 code: the same mismatched binary stays running, so retrying
|
|
96
|
+
// the spawn would only burn the heal breaker (and the page would say "版本与插件不一致"
|
|
97
|
+
// only after three tool calls stopped working).
|
|
98
|
+
assert.match(host, /const mismatch = ensured\.reason === 'api-mismatch'/)
|
|
99
|
+
assert.match(host, /if \(ensured\.reason === 'api-mismatch'\) \{\n\s+warnDaemonMismatch\(\)/)
|
|
100
|
+
assert.match(host, /code === 'api-mismatch'[\s\S]{0,200}risd-upgrade-required/)
|
|
101
|
+
// The forward path maps it to design §7.1's 503 instead of reusing the 409 branch.
|
|
102
|
+
assert.match(host, /new TailError\('risd-upgrade-required'[\s\S]{0,120}503\)/)
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
test('tools probe a half-dead daemon and say when they fell back to local (C-P2-2)', () => {
|
|
106
|
+
// A daemon that died between two tool calls used to look healthy forever: every
|
|
107
|
+
// call then paid a 2 s timeout and ran locally without a word.
|
|
108
|
+
assert.match(host, /const health = await risdHealth\(bridge\.state\)\.catch\(\(\) => null\)/)
|
|
109
|
+
assert.match(host, /if \(Date\.now\(\) - \(bridge\.lastProbeAt \?\? 0\) < 5000\) return bridge\.state/)
|
|
110
|
+
assert.match(host, /if \(healed === null\) warnDaemonFallback\(\)/)
|
|
111
|
+
assert.match(host, /不在 daemon 的托管范围内(停 daemon 不会停它)/)
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
test('a transport failure on a proxy action says "retry", not "500" (C-P2-8)', () => {
|
|
115
|
+
assert.match(host, /if \(call\.status === 0 \|\| call\.body === null\) \{/)
|
|
116
|
+
assert.match(host, /new TailError\('risd-unavailable'[\s\S]{0,200}503\)/)
|
|
117
|
+
assert.match(host, /void risdBridgeState\(cwd\)\.catch\(\(\) => \{\}\)/)
|
|
118
|
+
})
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* risd — the scoped git entry follows the rule table on every save.
|
|
3
|
+
*
|
|
4
|
+
* Saving rules used to reload only the bridge/profile; the `git config --global`
|
|
5
|
+
* entry of the previous host survived, so repointing or deleting the git rule left
|
|
6
|
+
* every terminal pointed at a dead tunnel ("旧代理无法取消"). reconcileGitProxy()
|
|
7
|
+
* is what the save path now calls before the new table takes effect.
|
|
8
|
+
*
|
|
9
|
+
* The tests use a throwaway HOME/DSH_RIS_IDE_PROXY_HOME and point GIT_CONFIG_GLOBAL
|
|
10
|
+
* at a temp file, so the machine's own git config is never touched.
|
|
11
|
+
*/
|
|
12
|
+
import test from 'node:test'
|
|
13
|
+
import assert from 'node:assert/strict'
|
|
14
|
+
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
15
|
+
import { tmpdir } from 'node:os'
|
|
16
|
+
import { join } from 'node:path'
|
|
17
|
+
import { spawnSync } from 'node:child_process'
|
|
18
|
+
|
|
19
|
+
const home = mkdtempSync(join(tmpdir(), 'risd-git-home-'))
|
|
20
|
+
const workspace = mkdtempSync(join(tmpdir(), 'risd-git-ws-'))
|
|
21
|
+
const globalConfig = join(home, 'gitconfig')
|
|
22
|
+
writeFileSync(globalConfig, '')
|
|
23
|
+
process.env.DSH_RIS_IDE_PROXY_HOME = home
|
|
24
|
+
process.env.GIT_CONFIG_GLOBAL = globalConfig
|
|
25
|
+
|
|
26
|
+
const git = await import('../lib/risd/git.js')
|
|
27
|
+
const proxy = await import('../lib/proxy.js')
|
|
28
|
+
|
|
29
|
+
const SOCKS = { host: '127.0.0.1', port: 1080 }
|
|
30
|
+
|
|
31
|
+
/** Write a table whose only rule (when host !== '') tunnels git to that host. */
|
|
32
|
+
function writeTable(host) {
|
|
33
|
+
const rules = host === ''
|
|
34
|
+
? []
|
|
35
|
+
: [{ id: 'yds-git', program: 'git', hosts: host, ports: '*', enabled: true, source: 'yds', workspace }]
|
|
36
|
+
proxy.writeProxyConfig(workspace, { socks: SOCKS, listenPort: 0, rules })
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** @returns {string} the scoped key a host's proxy would live under. */
|
|
40
|
+
function keyFor(host) {
|
|
41
|
+
return `http.https://${host}/.proxy`
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** @returns {string} current global value of a key ('' when unset). */
|
|
45
|
+
function readKey(key) {
|
|
46
|
+
const out = spawnSync('git', ['config', '--global', '--get', key], { encoding: 'utf8', windowsHide: true })
|
|
47
|
+
return String(out.stdout ?? '').trim()
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
test.after(() => {
|
|
51
|
+
rmSync(home, { recursive: true, force: true })
|
|
52
|
+
rmSync(workspace, { recursive: true, force: true })
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test('a saved table keeps the git entry on the current host', async () => {
|
|
56
|
+
writeTable('git-a.example')
|
|
57
|
+
const first = await git.reconcileGitProxy({ cwd: workspace })
|
|
58
|
+
assert.equal(first.ok, true)
|
|
59
|
+
assert.equal(first.host, 'git-a.example')
|
|
60
|
+
assert.equal(readKey(keyFor('git-a.example')), `socks5h://${SOCKS.host}:${SOCKS.port}`)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
test('repointing the git rule unsets the old host and writes the new one', async () => {
|
|
64
|
+
writeTable('git-b.example')
|
|
65
|
+
const second = await git.reconcileGitProxy({ cwd: workspace })
|
|
66
|
+
assert.equal(second.ok, true)
|
|
67
|
+
assert.equal(second.host, 'git-b.example')
|
|
68
|
+
assert.equal(readKey(keyFor('git-a.example')), '', 'the previous host key must be gone')
|
|
69
|
+
assert.equal(readKey(keyFor('git-b.example')), `socks5h://${SOCKS.host}:${SOCKS.port}`)
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
test('deleting the git rule clears the entry instead of leaving a dead tunnel', async () => {
|
|
73
|
+
writeTable('')
|
|
74
|
+
const cleared = await git.reconcileGitProxy({ cwd: workspace })
|
|
75
|
+
assert.equal(cleared.ok, true)
|
|
76
|
+
assert.equal(cleared.changed, true)
|
|
77
|
+
assert.equal(readKey(keyFor('git-b.example')), '')
|
|
78
|
+
assert.equal(existsSync(git.gitProxyStatePath()), false, 'bookkeeping must not outlive the entry')
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
test('a value somebody else replaced is left alone (E7 ownership)', async () => {
|
|
82
|
+
writeTable('git-c.example')
|
|
83
|
+
await git.reconcileGitProxy({ cwd: workspace })
|
|
84
|
+
assert.equal(readKey(keyFor('git-c.example')), `socks5h://${SOCKS.host}:${SOCKS.port}`)
|
|
85
|
+
spawnSync('git', ['config', '--global', keyFor('git-c.example'), 'http://their-proxy:3128'], { encoding: 'utf8' })
|
|
86
|
+
writeTable('')
|
|
87
|
+
const cleared = await git.reconcileGitProxy({ cwd: workspace })
|
|
88
|
+
assert.equal(cleared.ok, true)
|
|
89
|
+
assert.equal(cleared.cleared?.skipped, 'foreign-value')
|
|
90
|
+
assert.equal(readKey(keyFor('git-c.example')), 'http://their-proxy:3128', 'their value must survive')
|
|
91
|
+
assert.equal(existsSync(git.gitProxyStatePath()), false, 'our bookkeeping is dropped')
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
test('disabling the proxy also leaves a foreign git value alone', async () => {
|
|
95
|
+
// Review B-P0-1: only clearGitProxy() had the ownership check; the disable and
|
|
96
|
+
// host-switch paths unset the key directly, so a user's own scoped proxy was
|
|
97
|
+
// deleted whenever the plugin stopped the tunnel.
|
|
98
|
+
const host = 'git-d.example'
|
|
99
|
+
const key = keyFor(host)
|
|
100
|
+
writeTable(host)
|
|
101
|
+
const applied = await git.syncGitProxy({ cwd: workspace, host, enabled: true })
|
|
102
|
+
assert.equal(applied.ok, true)
|
|
103
|
+
spawnSync('git', ['config', '--global', key, 'http://their-proxy:3128'], { encoding: 'utf8', windowsHide: true })
|
|
104
|
+
const off = await git.syncGitProxy({ cwd: workspace, host, enabled: false })
|
|
105
|
+
assert.equal(off.ok, true)
|
|
106
|
+
assert.equal(off.skipped, 'foreign-value')
|
|
107
|
+
assert.equal(readKey(key), 'http://their-proxy:3128', 'their value must survive a disable')
|
|
108
|
+
assert.equal(existsSync(git.gitProxyStatePath()), false)
|
|
109
|
+
})
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /v1/shutdown {handoff:true} + daemon restart (Phase 1b P6).
|
|
3
|
+
*
|
|
4
|
+
* The point of a handoff: the successor daemon must ADOPT the engine the predecessor
|
|
5
|
+
* started — same pid, same port, no restart — instead of reporting owned:false and
|
|
6
|
+
* leaving the network to the previous owner's teardown. It also must not drop the
|
|
7
|
+
* state note before the successor could read it.
|
|
8
|
+
*/
|
|
9
|
+
import assert from 'node:assert/strict'
|
|
10
|
+
import test from 'node:test'
|
|
11
|
+
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { tmpdir } from 'node:os'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
import { RISD_API_VERSION, readRisdState } from '../lib/risd/state.js'
|
|
15
|
+
import { makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
|
|
16
|
+
|
|
17
|
+
function pickPort() {
|
|
18
|
+
return 20000 + Math.floor(Math.random() * 20000)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function writeEngineFixture(home, port) {
|
|
22
|
+
writeFileSync(join(home, 'proxy.json'), JSON.stringify({
|
|
23
|
+
socks: { host: '127.0.0.1', port: 1, dbPort: 0, redisPort: 0 },
|
|
24
|
+
listenPort: port,
|
|
25
|
+
rules: [{
|
|
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
|
+
}, null, 2))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function headers(state) {
|
|
39
|
+
return { authorization: `Bearer ${state.token}`, 'x-risd-api-version': String(RISD_API_VERSION), 'content-type': 'application/json' }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function post(state, path, body) {
|
|
43
|
+
const response = await fetch(`${state.url}${path}`, { method: 'POST', headers: headers(state), body: JSON.stringify(body) })
|
|
44
|
+
return { status: response.status, payload: await response.json().catch(() => ({})) }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function get(state, path) {
|
|
48
|
+
const response = await fetch(`${state.url}${path}`, { headers: headers(state) })
|
|
49
|
+
return { status: response.status, payload: await response.json().catch(() => ({})) }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function waitFor(fn, timeoutMs = 15000) {
|
|
53
|
+
const deadline = Date.now() + timeoutMs
|
|
54
|
+
while (Date.now() < deadline) {
|
|
55
|
+
if (await fn()) return true
|
|
56
|
+
await sleep(100)
|
|
57
|
+
}
|
|
58
|
+
return false
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function pidAlive(pid) {
|
|
62
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
63
|
+
try {
|
|
64
|
+
process.kill(pid, 0)
|
|
65
|
+
return true
|
|
66
|
+
} catch {
|
|
67
|
+
return false
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
test('a handoff shutdown keeps the engine for the next daemon (same pid)', async (t) => {
|
|
72
|
+
const home = makeHome('risd-handoff-')
|
|
73
|
+
const cwd = mkdtempSync(join(tmpdir(), 'risd-handoff-ws-'))
|
|
74
|
+
t.after(() => removeHome(home))
|
|
75
|
+
t.after(() => rmSync(cwd, { recursive: true, force: true }))
|
|
76
|
+
writeEngineFixture(home, pickPort())
|
|
77
|
+
|
|
78
|
+
const first = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
|
|
79
|
+
const enginePid = await (async () => {
|
|
80
|
+
const started = await post(first.state, '/v1/engine', { action: 'start', cwd })
|
|
81
|
+
assert.equal(started.status, 200, JSON.stringify(started.payload))
|
|
82
|
+
assert.equal(started.payload.ok, true)
|
|
83
|
+
const health = await get(first.state, '/v1/engine?cwd=' + encodeURIComponent(cwd))
|
|
84
|
+
assert.equal(health.payload.engine.owned, true)
|
|
85
|
+
return health.payload.engine.pid
|
|
86
|
+
})()
|
|
87
|
+
assert.equal(pidAlive(enginePid), true, 'the engine is a live child process')
|
|
88
|
+
|
|
89
|
+
// Hand over instead of shutting down: the daemon exits, the network stays.
|
|
90
|
+
const draining = await post(first.state, '/v1/shutdown', { handoff: true })
|
|
91
|
+
assert.equal(draining.status, 200)
|
|
92
|
+
assert.equal(draining.payload.handoff, true)
|
|
93
|
+
assert.equal(await first.stop(), 0, 'the predecessor exits cleanly')
|
|
94
|
+
assert.equal(existsSync(join(home, 'risd.json')), true, 'the state note survives a handoff')
|
|
95
|
+
const noted = JSON.parse((await import('node:fs')).readFileSync(join(home, 'risd.json'), 'utf8'))
|
|
96
|
+
assert.equal(noted.handoff?.enginePid, enginePid, 'the note names the engine to adopt')
|
|
97
|
+
assert.equal(noted.handoff?.cwd, cwd)
|
|
98
|
+
assert.equal(pidAlive(enginePid), true, 'nothing tore the engine down')
|
|
99
|
+
|
|
100
|
+
// The successor takes the same port and adopts instead of restarting.
|
|
101
|
+
const second = await startRisdProcess({ home, port: noted.port, env: { DSH_RIS_IDE_PROXY_HOME: home } })
|
|
102
|
+
try {
|
|
103
|
+
const health = await get(second.state, '/v1/health')
|
|
104
|
+
assert.equal(health.payload.engine.owned, true, 'the successor owns the engine')
|
|
105
|
+
assert.equal(health.payload.engine.inherited, true, 'and says it adopted a handed-off engine (review C-P2-10)')
|
|
106
|
+
assert.equal(health.payload.engine.pid, enginePid, 'same pid: nothing was restarted')
|
|
107
|
+
const status = await get(second.state, '/v1/status?cwd=' + encodeURIComponent(cwd))
|
|
108
|
+
assert.equal(status.status, 200)
|
|
109
|
+
} finally {
|
|
110
|
+
await post(second.state, '/v1/engine', { action: 'stop', cwd }).catch(() => {})
|
|
111
|
+
await second.stop()
|
|
112
|
+
await waitFor(() => pidAlive(enginePid) !== true, 12000)
|
|
113
|
+
}
|
|
114
|
+
assert.equal(pidAlive(enginePid), false, 'the successor still owns the teardown')
|
|
115
|
+
assert.equal(readRisdState(home), null, 'a normal shutdown removes the state note')
|
|
116
|
+
})
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Automatic daemon starts must not loop: a risd that cannot boot (broken home,
|
|
2
|
+
// stolen port, bad Node install) would otherwise be re-spawned on every click or
|
|
3
|
+
// tool call, each attempt paying the full health-probe timeout.
|
|
4
|
+
import assert from 'node:assert/strict'
|
|
5
|
+
import test from 'node:test'
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
noteRisdHealFailure,
|
|
9
|
+
noteRisdHealSuccess,
|
|
10
|
+
risdHealBlocked,
|
|
11
|
+
risdHealReason,
|
|
12
|
+
} from '../lib/index.js'
|
|
13
|
+
|
|
14
|
+
test('three failures inside the window pause automatic starts', () => {
|
|
15
|
+
const t0 = 1_000_000
|
|
16
|
+
noteRisdHealSuccess()
|
|
17
|
+
noteRisdHealFailure('port busy', t0)
|
|
18
|
+
noteRisdHealFailure('port busy', t0 + 1000)
|
|
19
|
+
assert.equal(risdHealBlocked(t0 + 2000), false, 'two failures are not enough')
|
|
20
|
+
noteRisdHealFailure('port busy', t0 + 2000)
|
|
21
|
+
assert.equal(risdHealBlocked(t0 + 2001), true, 'the third trips the breaker')
|
|
22
|
+
const reason = risdHealReason(t0 + 2001)
|
|
23
|
+
assert.match(reason, /连续 3 次自动启动 risd 失败/)
|
|
24
|
+
assert.match(reason, /port busy/)
|
|
25
|
+
assert.match(reason, /risd serve/)
|
|
26
|
+
// Still blocked shortly before the cooldown ends, free again after it.
|
|
27
|
+
assert.equal(risdHealBlocked(t0 + 2000 + 5 * 60_000 - 10), true)
|
|
28
|
+
assert.equal(risdHealBlocked(t0 + 2000 + 5 * 60_000 + 10), false)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
test('a success clears the breaker', () => {
|
|
32
|
+
const t0 = 2_000_000
|
|
33
|
+
noteRisdHealSuccess()
|
|
34
|
+
noteRisdHealFailure('boom', t0)
|
|
35
|
+
noteRisdHealFailure('boom', t0 + 10)
|
|
36
|
+
noteRisdHealFailure('boom', t0 + 20)
|
|
37
|
+
assert.equal(risdHealBlocked(t0 + 30), true)
|
|
38
|
+
noteRisdHealSuccess()
|
|
39
|
+
assert.equal(risdHealBlocked(t0 + 40), false)
|
|
40
|
+
assert.equal(risdHealReason(t0 + 40), '')
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
test('failures spread across the window do not trip it', () => {
|
|
44
|
+
const t0 = 3_000_000
|
|
45
|
+
noteRisdHealSuccess()
|
|
46
|
+
noteRisdHealFailure('x', t0)
|
|
47
|
+
noteRisdHealFailure('x', t0 + 3 * 60_000)
|
|
48
|
+
noteRisdHealFailure('x', t0 + 6 * 60_000)
|
|
49
|
+
assert.equal(risdHealBlocked(t0 + 6 * 60_000 + 1), false)
|
|
50
|
+
})
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helpers for the risd tests (not a test file: the npm glob only picks
|
|
3
|
+
* up `test/*.test.mjs`).
|
|
4
|
+
*
|
|
5
|
+
* Every test gets its own `DSH_RIS_IDE_PROXY_HOME`-style home under the OS temp
|
|
6
|
+
* dir, so the machine-level `~/.dsh-ris-ide` is never read or written.
|
|
7
|
+
*/
|
|
8
|
+
import { mkdtempSync, rmSync } from 'node:fs'
|
|
9
|
+
import { tmpdir } from 'node:os'
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
import { spawn } from 'node:child_process'
|
|
12
|
+
import { fileURLToPath } from 'node:url'
|
|
13
|
+
import { readRisdState } from '../lib/risd/state.js'
|
|
14
|
+
|
|
15
|
+
export const RISD_BIN = fileURLToPath(new URL('../bin/risd.mjs', import.meta.url))
|
|
16
|
+
|
|
17
|
+
export function makeHome(prefix = 'risd-test-') {
|
|
18
|
+
return mkdtempSync(join(tmpdir(), prefix))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function removeHome(home) {
|
|
22
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
23
|
+
try {
|
|
24
|
+
rmSync(home, { recursive: true, force: true })
|
|
25
|
+
return
|
|
26
|
+
} catch {
|
|
27
|
+
/* daemon may still be closing its log/handles */
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function sleep(ms) {
|
|
33
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function health(port) {
|
|
37
|
+
try {
|
|
38
|
+
const response = await fetch(`http://127.0.0.1:${port}/v1/health`, { signal: AbortSignal.timeout(500) })
|
|
39
|
+
return response.ok ? await response.json() : null
|
|
40
|
+
} catch {
|
|
41
|
+
return null
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Spawn `risd serve` and wait until its state file exists and health answers.
|
|
47
|
+
* @returns `{ child, home, state, lines, stop }` — `lines` is the collected stderr.
|
|
48
|
+
*/
|
|
49
|
+
export async function startRisdProcess({ home = makeHome(), port = 0, env = {} } = {}) {
|
|
50
|
+
// The daemon applies the machine-level git proxy through `git config --global`,
|
|
51
|
+
// which honours HOME/GIT_CONFIG_GLOBAL. Point both at the throwaway home unless
|
|
52
|
+
// the caller says otherwise: a `/v1/action start` fixture with a git rule must
|
|
53
|
+
// never edit the real ~/.gitconfig (found after a full-suite run wrote a
|
|
54
|
+
// `git.example.com` entry into the developer's config).
|
|
55
|
+
const isolated = {
|
|
56
|
+
HOME: home,
|
|
57
|
+
USERPROFILE: home,
|
|
58
|
+
GIT_CONFIG_GLOBAL: join(home, '.gitconfig'),
|
|
59
|
+
}
|
|
60
|
+
const child = spawn(process.execPath, [RISD_BIN, 'serve', '--home', home, '--port', String(port)], {
|
|
61
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
62
|
+
env: { ...process.env, ...isolated, ...env },
|
|
63
|
+
})
|
|
64
|
+
const lines = []
|
|
65
|
+
child.stdout.on('data', (chunk) => lines.push(String(chunk)))
|
|
66
|
+
child.stderr.on('data', (chunk) => lines.push(String(chunk)))
|
|
67
|
+
const deadline = Date.now() + 10_000
|
|
68
|
+
while (Date.now() < deadline) {
|
|
69
|
+
const state = readRisdState(home)
|
|
70
|
+
if (state !== null) {
|
|
71
|
+
const probe = await health(state.port)
|
|
72
|
+
if (probe?.ok === true) {
|
|
73
|
+
return { child, home, state, lines, stop: () => stopRisdProcess(child) }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (child.exitCode !== null) break
|
|
77
|
+
await sleep(60)
|
|
78
|
+
}
|
|
79
|
+
child.kill('SIGKILL')
|
|
80
|
+
throw new Error(`risd did not become ready; stderr:\n${lines.join('')}`)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Ask the child to exit, then hard-kill if it did not. */
|
|
84
|
+
export async function stopRisdProcess(child) {
|
|
85
|
+
if (child.exitCode !== null) return child.exitCode
|
|
86
|
+
child.kill('SIGTERM')
|
|
87
|
+
const deadline = Date.now() + 4000
|
|
88
|
+
while (Date.now() < deadline) {
|
|
89
|
+
if (child.exitCode !== null) return child.exitCode
|
|
90
|
+
await sleep(40)
|
|
91
|
+
}
|
|
92
|
+
child.kill('SIGKILL')
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Run the CLI once and capture `{ code, out, err }`. */
|
|
97
|
+
export function runRisdCli(args, { env = {} } = {}) {
|
|
98
|
+
return new Promise((resolve) => {
|
|
99
|
+
const child = spawn(process.execPath, [RISD_BIN, ...args], { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...env } })
|
|
100
|
+
let out = ''
|
|
101
|
+
let err = ''
|
|
102
|
+
child.stdout.on('data', (chunk) => (out += String(chunk)))
|
|
103
|
+
child.stderr.on('data', (chunk) => (err += String(chunk)))
|
|
104
|
+
child.on('close', (code) => resolve({ code, out, err }))
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export { health }
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin-side (lib/index.js) regressions for the P2 findings of the C report:
|
|
3
|
+
* how the host forwards proxy writes/actions when the daemon answers with an API
|
|
4
|
+
* version mismatch, a stale table, or not at all.
|
|
5
|
+
*
|
|
6
|
+
* Why a separate file: these are HTTP-shape tests against `serveProxy` /
|
|
7
|
+
* `serveProxyAction` with a fake daemon, so they need lib/index.js loaded with a
|
|
8
|
+
* temporary proxy home instead of the page strings risd-ui.test.mjs asserts on.
|
|
9
|
+
*/
|
|
10
|
+
import assert from 'node:assert/strict'
|
|
11
|
+
import { createServer } from 'node:http'
|
|
12
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
13
|
+
import { tmpdir } from 'node:os'
|
|
14
|
+
import { join } from 'node:path'
|
|
15
|
+
import { Readable } from 'node:stream'
|
|
16
|
+
import test from 'node:test'
|
|
17
|
+
|
|
18
|
+
const home = mkdtempSync(join(tmpdir(), 'risd-host-p2-'))
|
|
19
|
+
const workspace = mkdtempSync(join(tmpdir(), 'risd-host-p2-ws-'))
|
|
20
|
+
process.env.DSH_RIS_IDE_PROXY_HOME = home
|
|
21
|
+
|
|
22
|
+
const { __test } = await import('../lib/index.js')
|
|
23
|
+
const { RISD_API_VERSION } = await import('../lib/risd/state.js')
|
|
24
|
+
|
|
25
|
+
function fakeRes() {
|
|
26
|
+
return {
|
|
27
|
+
status: 0,
|
|
28
|
+
chunks: [],
|
|
29
|
+
writeHead(status) { this.status = status },
|
|
30
|
+
write(chunk) { this.chunks.push(String(chunk)); return true },
|
|
31
|
+
end(chunk) { if (chunk !== undefined) this.chunks.push(String(chunk)) },
|
|
32
|
+
json() { return JSON.parse(this.chunks.join('')) },
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function fakeReq(method, url, body) {
|
|
37
|
+
const chunks = body === undefined ? [] : [Buffer.from(JSON.stringify(body))]
|
|
38
|
+
const req = Readable.from(chunks)
|
|
39
|
+
req.method = method
|
|
40
|
+
req.url = url
|
|
41
|
+
req.headers = { host: '127.0.0.1:3080', 'content-type': 'application/json' }
|
|
42
|
+
return req
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A fake daemon that answers /v1/health and hands every other request to `reply`. */
|
|
46
|
+
async function fakeDaemon(reply) {
|
|
47
|
+
const server = createServer((req, res) => {
|
|
48
|
+
if (req.url === '/v1/health') {
|
|
49
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
50
|
+
res.end(JSON.stringify({ ok: true, apiVersion: RISD_API_VERSION, pid: 4242, port: server.address().port, version: '1.8.0' }))
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
let raw = ''
|
|
54
|
+
req.on('data', (chunk) => { raw += chunk })
|
|
55
|
+
req.on('end', () => {
|
|
56
|
+
const body = raw === '' ? null : JSON.parse(raw)
|
|
57
|
+
const answer = reply(req, body)
|
|
58
|
+
res.writeHead(answer.status, { 'content-type': 'application/json' })
|
|
59
|
+
res.end(JSON.stringify(answer.body))
|
|
60
|
+
})
|
|
61
|
+
})
|
|
62
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
|
63
|
+
return server
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function stopServer(server) {
|
|
67
|
+
server.closeAllConnections?.()
|
|
68
|
+
await new Promise((resolve) => server.close(resolve))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function setBridge(url, port) {
|
|
72
|
+
__test.setRisdBridge({
|
|
73
|
+
mode: 'auto',
|
|
74
|
+
state: { url, token: 'token-x', apiVersion: RISD_API_VERSION, port },
|
|
75
|
+
leaseId: 'lease-x',
|
|
76
|
+
pending: null,
|
|
77
|
+
warnedAt: 0,
|
|
78
|
+
degraded: false,
|
|
79
|
+
lastProbeAt: Date.now(),
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const ctx = { sessions: { get: () => ({ header: { cwd: workspace } }) } }
|
|
84
|
+
const writeBody = {
|
|
85
|
+
sessionId: 's1',
|
|
86
|
+
revision: '',
|
|
87
|
+
config: { socks: { host: 'proxy.example.com', port: 10080 }, listenPort: 11081, rules: [] },
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
test.after(() => {
|
|
91
|
+
__test.setRisdBridge(null)
|
|
92
|
+
rmSync(home, { recursive: true, force: true })
|
|
93
|
+
rmSync(workspace, { recursive: true, force: true })
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
test('a daemon API mismatch is not reported as "someone else changed the rules" (C-P2-1)', async () => {
|
|
97
|
+
// Before: every 409 was passed through as a table conflict, so the dialog told the
|
|
98
|
+
// user to reload and retried a write the daemon can never accept until dsh is
|
|
99
|
+
// restarted; design §7.1 wants a 503 risd-upgrade-required here.
|
|
100
|
+
const server = await fakeDaemon(() => ({
|
|
101
|
+
status: 409,
|
|
102
|
+
body: { ok: false, code: 'api-mismatch', message: 'plugin apiVersion 1 ≠ daemon apiVersion 2' },
|
|
103
|
+
}))
|
|
104
|
+
const port = server.address().port
|
|
105
|
+
setBridge(`http://127.0.0.1:${port}`, port)
|
|
106
|
+
const res = fakeRes()
|
|
107
|
+
await __test.serveProxy(ctx, fakeReq('POST', '/dsh-ris-ide/proxy', writeBody), res)
|
|
108
|
+
assert.equal(res.status, 503)
|
|
109
|
+
const body = res.json()
|
|
110
|
+
assert.equal(body.ok, false)
|
|
111
|
+
assert.equal(body.code, 'risd-upgrade-required')
|
|
112
|
+
assert.match(String(body.message), /重启 dsh/)
|
|
113
|
+
await stopServer(server)
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
test('a genuinely stale table still answers 409 with conflict and the current view (C-P2-1)', async () => {
|
|
117
|
+
const server = await fakeDaemon(() => ({
|
|
118
|
+
status: 409,
|
|
119
|
+
body: { ok: false, conflict: true, code: 'conflict', message: '规则表已在别处被修改,本次改动未写入', revision: 'deadbeef' },
|
|
120
|
+
}))
|
|
121
|
+
const port = server.address().port
|
|
122
|
+
setBridge(`http://127.0.0.1:${port}`, port)
|
|
123
|
+
const res = fakeRes()
|
|
124
|
+
await __test.serveProxy(ctx, fakeReq('POST', '/dsh-ris-ide/proxy', writeBody), res)
|
|
125
|
+
assert.equal(res.status, 409)
|
|
126
|
+
const body = res.json()
|
|
127
|
+
assert.equal(body.conflict, true)
|
|
128
|
+
assert.equal(body.code, 'conflict')
|
|
129
|
+
assert.equal(body.revision, 'deadbeef')
|
|
130
|
+
assert.equal(body.message, '规则表已在别处被修改,本次改动未写入', 'the daemon message must pass through verbatim')
|
|
131
|
+
assert.equal(body.view.ok, true, 'the dialog needs the current view to reload')
|
|
132
|
+
await stopServer(server)
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
test('an unreachable daemon refuses a proxy action with a retry hint instead of a bare 502 (C-P2-8)', async () => {
|
|
136
|
+
// The panel lost its proxy buttons, so "stop engine" only exists on this page:
|
|
137
|
+
// a timeout there must not read as "the action failed inside the daemon".
|
|
138
|
+
setBridge('http://127.0.0.1:9', 9)
|
|
139
|
+
writeFileSync(join(home, 'proxy.json'), `${JSON.stringify({ socks: { host: 'proxy.example.com', port: 10080 }, listenPort: 11081, rules: [], shadows: [] }, null, 2)}\n`, { mode: 0o600 })
|
|
140
|
+
const res = fakeRes()
|
|
141
|
+
await __test.serveProxyAction(ctx, fakeReq('POST', '/dsh-ris-ide/proxy/action', { sessionId: 's1', cwd: workspace, action: 'stop' }), res)
|
|
142
|
+
assert.equal(res.status, 503)
|
|
143
|
+
const body = res.json()
|
|
144
|
+
assert.equal(body.ok, false)
|
|
145
|
+
assert.equal(body.code, 'risd-unavailable')
|
|
146
|
+
assert.match(String(body.message), /未执行/)
|
|
147
|
+
})
|