instance.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import { afterEach, beforeEach, describe, expect, it } from 'vitest'
  2. import { readFileSync } from 'node:fs'
  3. import { mkdtemp, mkdir, readFile, rm, writeFile, realpath } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { pathToFileURL, fileURLToPath } from 'node:url'
  7. import { Context } from '@deepseek-ai/cordis'
  8. import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
  9. import { LspInstance, readHostSource } from '@deepseek-ai/dsh-lsp-stdio'
  10. import { encodeMessage } from '@deepseek-ai/dsh-lsp-stdio'
  11. import type { ConnectionWriter } from '@deepseek-ai/dsh-lsp-stdio/src/connection.ts'
  12. import type { InstanceSpec } from '@deepseek-ai/dsh-lsp-stdio/src/instance.ts'
  13. import type { LspProviderQuery, LspQueryResult } from '@deepseek-ai/dsh-lsp'
  14. import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess'
  15. import { spawnSubprocess } from '@deepseek-ai/dsh-subprocess-local/src/spawn.ts'
  16. const fixtureServer = fileURLToPath(new URL('./fixture-server.ts', import.meta.url))
  17. let root: string
  18. let ws: string
  19. let ctx: Context
  20. let fs: LocalFileSystem
  21. let live: LspInstance[] = []
  22. beforeEach(async () => {
  23. root = await realpath(await mkdtemp(join(tmpdir(), 'lsp-inst-')))
  24. ws = join(root, 'ws')
  25. await mkdir(ws)
  26. await writeFile(join(ws, 'a.ts'), 'const x = 1\n')
  27. ctx = new Context()
  28. await ctx.plugin(LocalFileSystem, { cwd: root })
  29. fs = ctx.fs as LocalFileSystem
  30. })
  31. afterEach(async () => {
  32. for (const instance of live) await instance.dispose()
  33. live = []
  34. await ctx.fiber.dispose()
  35. await rm(root, { recursive: true, force: true })
  36. })
  37. function makeInstance(
  38. env: Record<string, string> = {},
  39. overrides: Partial<InstanceSpec> = {},
  40. writer?: ConnectionWriter,
  41. ): LspInstance {
  42. const instance = new LspInstance({
  43. command: process.execPath,
  44. args: [fixtureServer],
  45. cwd: ws,
  46. workspaceUri: pathToFileURL(ws).href,
  47. env: { ...scrubbedParentEnv(), ...env },
  48. configuration: { setting: 42 },
  49. initializationOptions: { init: true },
  50. maxMessageBytes: 16_000_000,
  51. maxStderrBytes: 100_000,
  52. shutdownTimeoutMs: 200,
  53. killGraceMs: 200,
  54. ...overrides,
  55. }, spawnSubprocess, writer)
  56. live.push(instance)
  57. return instance
  58. }
  59. function query(operation: LspProviderQuery['operation'] = 'goToDefinition'): LspProviderQuery {
  60. return { operation, filePath: 'a.ts', position: { line: 0, character: 6 }, workspaceRoot: ws, languageId: 'typescript' }
  61. }
  62. /** Run a query against an instance, reading the source first the way the provider does. */
  63. async function run(instance: LspInstance, operation: LspProviderQuery['operation'] = 'goToDefinition', signal?: AbortSignal): Promise<LspQueryResult> {
  64. const workspace = {
  65. target: await fs.resolve(ws),
  66. canonicalPath: ws,
  67. fileUrl: pathToFileURL(ws).href,
  68. }
  69. const source = await readHostSource(fs, 'a.ts', workspace, 4_000_000)
  70. return instance.query(query(operation), source, signal)
  71. }
  72. /** Build an instance whose "server" is an inline node script (for teardown-escalation control). */
  73. function scriptInstance(script: string, overrides: Partial<InstanceSpec> = {}): LspInstance {
  74. const instance = new LspInstance({
  75. command: process.execPath,
  76. args: ['-e', script],
  77. cwd: ws,
  78. workspaceUri: pathToFileURL(ws).href,
  79. env: scrubbedParentEnv(),
  80. configuration: null,
  81. initializationOptions: null,
  82. maxMessageBytes: 16_000_000,
  83. maxStderrBytes: 100_000,
  84. shutdownTimeoutMs: 150,
  85. killGraceMs: 150,
  86. ...overrides,
  87. }, spawnSubprocess)
  88. live.push(instance)
  89. return instance
  90. }
  91. /** An inline server that answers initialize + definition and echoes a location. */
  92. const RESPONDING_SERVER =
  93. 'let b=Buffer.alloc(0);'
  94. + 'const fr=(o)=>{const x=Buffer.from(JSON.stringify({jsonrpc:"2.0",...o}));return Buffer.concat([Buffer.from(`Content-Length: ${x.length}\\r\\n\\r\\n`),x]);};'
  95. + 'process.stdin.on("data",c=>{b=Buffer.concat([b,c]);for(;;){const s=b.indexOf("\\r\\n\\r\\n");if(s<0)break;const len=Number(/(\\d+)/.exec(b.toString("ascii",0,s))[1]);if(b.length<s+4+len)break;const m=JSON.parse(b.toString("utf8",s+4,s+4+len));b=b.subarray(s+4+len);'
  96. + 'if(m.method==="initialize")process.stdout.write(fr({id:m.id,result:{capabilities:{positionEncoding:"utf-16",textDocumentSync:1,definitionProvider:true}}}));'
  97. + 'else if(m.method==="textDocument/definition")process.stdout.write(fr({id:m.id,result:null}));'
  98. + '}});'
  99. const locJson = () => JSON.stringify({ uri: pathToFileURL(join(ws, 'a.ts')).href, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 3 } } })
  100. describe('LspInstance server-request handling', () => {
  101. it('answers workspace/configuration with the static config per item', async () => {
  102. const instance = makeInstance({ LSP_FAKE_ON_OPEN: 'configuration', LSP_FAKE_DEF: locJson() })
  103. // The query drives didOpen, which makes the fake emit workspace/configuration; a healthy answer
  104. // keeps the query working.
  105. await expect(run(instance, 'goToDefinition')).resolves.toMatchObject({ kind: 'locations' })
  106. })
  107. it('accepts a lifecycle client/registerCapability request', async () => {
  108. const instance = makeInstance({ LSP_FAKE_ON_OPEN: 'lifecycle', LSP_FAKE_DEF: 'null' })
  109. await expect(run(instance, 'goToDefinition')).resolves.toEqual({ kind: 'locations', locations: [], resolvedWorkspaceUri: pathToFileURL(ws).href })
  110. })
  111. it('rejects a workspace/applyEdit request but keeps serving', async () => {
  112. const instance = makeInstance({ LSP_FAKE_ON_OPEN: 'applyEdit', LSP_FAKE_DEF: 'null' })
  113. await expect(run(instance, 'goToDefinition')).resolves.toEqual({ kind: 'locations', locations: [], resolvedWorkspaceUri: pathToFileURL(ws).href })
  114. })
  115. it('rejects an unknown server request but keeps serving', async () => {
  116. const instance = makeInstance({ LSP_FAKE_ON_OPEN: 'unknown', LSP_FAKE_DEF: 'null' })
  117. await expect(run(instance, 'goToDefinition')).resolves.toEqual({ kind: 'locations', locations: [], resolvedWorkspaceUri: pathToFileURL(ws).href })
  118. })
  119. })
  120. describe('LspInstance query and abort', () => {
  121. it('sends includeDeclaration for references', async () => {
  122. const instance = makeInstance({ LSP_FAKE_REFS: JSON.stringify([JSON.parse(locJson())]) })
  123. await expect(run(instance, 'findReferences')).resolves.toMatchObject({ kind: 'locations' })
  124. })
  125. it('rejects a query aborted before it starts', async () => {
  126. const instance = makeInstance({ LSP_FAKE_DEF: 'null' })
  127. const controller = new AbortController()
  128. controller.abort(new Error('pre-abort'))
  129. await expect(run(instance, 'goToDefinition', controller.signal)).rejects.toThrow(/pre-abort/)
  130. })
  131. it('cancels an in-flight request on abort and rejects', async () => {
  132. const instance = makeInstance({ LSP_FAKE_HANG: '1' })
  133. const controller = new AbortController()
  134. // Warm the instance first so the abort lands during the hanging request, not during startup.
  135. const pending = run(instance, 'goToDefinition', controller.signal)
  136. await new Promise<void>(resolve => setTimeout(resolve, 300))
  137. controller.abort(new Error('mid-flight'))
  138. await expect(pending).rejects.toThrow(/mid-flight/)
  139. })
  140. it('terminates the instance when the server ignores $/cancelRequest past the grace', async () => {
  141. // The hang server never honors cancellation, so after the bounded grace the instance must be torn
  142. // down (its process closed) rather than left with an active request.
  143. const instance = makeInstance({ LSP_FAKE_HANG: '1' }, { killGraceMs: 100 })
  144. const controller = new AbortController()
  145. const pending = run(instance, 'goToDefinition', controller.signal)
  146. await new Promise<void>(resolve => setTimeout(resolve, 300))
  147. controller.abort(new Error('mid-flight'))
  148. await expect(pending).rejects.toThrow(/mid-flight/)
  149. expect(instance.dead).toBe(true)
  150. })
  151. it('resolves the cancel grace when the server honors $/cancelRequest', async () => {
  152. // A server that answers $/cancelRequest by settling the pending request lets the grace race
  153. // resolve via the request rather than the timeout, so the instance is NOT force-terminated.
  154. const script = 'let b=Buffer.alloc(0),reqId=null;'
  155. + 'const fr=(o)=>{const x=Buffer.from(JSON.stringify({jsonrpc:"2.0",...o}));return Buffer.concat([Buffer.from(`Content-Length: ${x.length}\\r\\n\\r\\n`),x]);};'
  156. + 'process.stdin.on("data",c=>{b=Buffer.concat([b,c]);for(;;){const s=b.indexOf("\\r\\n\\r\\n");if(s<0)break;const len=Number(/(\\d+)/.exec(b.toString("ascii",0,s))[1]);if(b.length<s+4+len)break;const m=JSON.parse(b.toString("utf8",s+4,s+4+len));b=b.subarray(s+4+len);'
  157. + 'if(m.method==="initialize")process.stdout.write(fr({id:m.id,result:{capabilities:{positionEncoding:"utf-16",textDocumentSync:1,definitionProvider:true}}}));'
  158. + 'else if(m.method==="textDocument/definition")reqId=m.id;'
  159. + 'else if(m.method==="$/cancelRequest"&&reqId!==null)process.stdout.write(fr({id:reqId,error:{code:-32800,message:"request cancelled"}}));'
  160. + 'else if(m.method==="shutdown")process.stdout.write(fr({id:m.id,result:null}));'
  161. + 'else if(m.method==="exit")process.exit(0);'
  162. + '}});'
  163. const instance = scriptInstance(script, { killGraceMs: 2_000 })
  164. const controller = new AbortController()
  165. const pending = run(instance, 'goToDefinition', controller.signal)
  166. await new Promise<void>(resolve => setTimeout(resolve, 300))
  167. controller.abort(new Error('mid-flight'))
  168. await expect(pending).rejects.toThrow(/mid-flight/)
  169. // The server acknowledged cancellation within grace, so the instance was not force-killed.
  170. expect(instance.dead).toBe(false)
  171. await instance.dispose()
  172. })
  173. it('observes abort while awaiting a slow initialize handshake', async () => {
  174. // A server that answers nothing (not even initialize) leaves `ready` pending; an abort must be
  175. // observed during that wait instead of hanging the tool-timeout signal.
  176. const instance = scriptInstance('setInterval(()=>{},1000)', { killGraceMs: 100 })
  177. const controller = new AbortController()
  178. const pending = run(instance, 'goToDefinition', controller.signal)
  179. await new Promise<void>(resolve => setTimeout(resolve, 150))
  180. controller.abort(new Error('handshake-abort'))
  181. await expect(pending).rejects.toThrow(/handshake-abort/)
  182. await instance.dispose()
  183. })
  184. it('terminates when abort interrupts a backpressured didOpen write', async () => {
  185. // The fixture consumes initialized, then stops reading. A document larger than the stdio pipe
  186. // keeps didOpen's write callback pending until cancellation forces bounded process teardown.
  187. await writeFile(join(ws, 'a.ts'), 'x'.repeat(2_000_000))
  188. const marker = join(root, 'initialized.log')
  189. const instance = makeInstance({
  190. LSP_FAKE_INITIALIZED_MARKER: marker,
  191. LSP_FAKE_PAUSE_STDIN_AFTER_INITIALIZED: '1',
  192. }, {
  193. shutdownTimeoutMs: 100,
  194. killGraceMs: 100,
  195. })
  196. const controller = new AbortController()
  197. const pending = run(instance, 'goToDefinition', controller.signal)
  198. await waitForFile(marker)
  199. // Let the client enter the large didOpen write after the fixture has paused stdin.
  200. await new Promise<void>(resolve => setTimeout(resolve, 100))
  201. controller.abort(new Error('didOpen-abort'))
  202. await expect(pending).rejects.toThrow(/didOpen-abort/)
  203. expect(instance.dead).toBe(true)
  204. })
  205. it('terminates when stdin fails during the didOpen write', async () => {
  206. const instance = makeInstance({}, {
  207. shutdownTimeoutMs: 100,
  208. killGraceMs: 100,
  209. }, failingWriter('textDocument/didOpen'))
  210. await expect(run(instance, 'goToDefinition')).rejects.toThrow()
  211. expect(instance.dead).toBe(true)
  212. })
  213. it('awaits process exit before rejecting a request write failure', async () => {
  214. const instance = makeInstance({}, {
  215. shutdownTimeoutMs: 100,
  216. killGraceMs: 100,
  217. }, failingWriter('textDocument/definition'))
  218. // The pid is observed only to prove the owned subprocess reached quiescence before rejection.
  219. const pid = (instance as unknown as { connection: { pid: number } }).connection.pid
  220. await expect(run(instance, 'goToDefinition')).rejects.toThrow(/fixture textDocument\/definition failure/)
  221. expect(processAlive(pid)).toBe(false)
  222. })
  223. it('rejects when the server lacks the operation capability', async () => {
  224. const instance = makeInstance({ LSP_FAKE_CAPS: JSON.stringify({ definitionProvider: false }), LSP_FAKE_DEF: 'null' })
  225. await expect(run(instance, 'goToDefinition')).rejects.toThrow(/does not support goToDefinition/)
  226. })
  227. it('propagates a server error response even when a signal is supplied (not an abort)', async () => {
  228. // A live signal is passed, but the request fails for a server reason; the catch must rethrow
  229. // without treating it as an abort.
  230. const instance = makeInstance({ LSP_FAKE_ERROR: '1' })
  231. const controller = new AbortController()
  232. await expect(run(instance, 'goToDefinition', controller.signal)).rejects.toThrow(/server refused/)
  233. })
  234. it('keeps a settled result but awaits teardown when didClose cannot be written', async () => {
  235. const instance = makeInstance({
  236. LSP_FAKE_DEF: 'null',
  237. }, { shutdownTimeoutMs: 100, killGraceMs: 100 }, failingWriter('textDocument/didClose'))
  238. await expect(run(instance, 'goToDefinition')).resolves.toEqual({
  239. kind: 'locations',
  240. locations: [],
  241. resolvedWorkspaceUri: pathToFileURL(ws).href,
  242. })
  243. expect(instance.dead).toBe(true)
  244. })
  245. })
  246. describe('LspInstance disposal', () => {
  247. it('lets a server finish protocol exit before signal escalation', async () => {
  248. const marker = join(root, 'graceful-exit.log')
  249. const instance = makeInstance({
  250. LSP_FAKE_DEF: 'null',
  251. LSP_FAKE_EXIT_DELAY_MS: '75',
  252. LSP_FAKE_EXIT_MARKER: marker,
  253. }, { shutdownTimeoutMs: 500 })
  254. await run(instance, 'goToDefinition')
  255. await instance.dispose()
  256. expect(await readFile(marker, 'utf8')).toBe('EXIT\nCLEAN\n')
  257. })
  258. it('is idempotent — a second dispose awaits close without error', async () => {
  259. const instance = makeInstance({ LSP_FAKE_DEF: 'null' })
  260. await run(instance, 'goToDefinition')
  261. await instance.dispose()
  262. await expect(instance.dispose()).resolves.toBeUndefined()
  263. })
  264. it('rejects a query after disposal', async () => {
  265. const instance = makeInstance({ LSP_FAKE_DEF: 'null' })
  266. await run(instance, 'goToDefinition')
  267. await instance.dispose()
  268. await expect(run(instance, 'goToDefinition')).rejects.toThrow(expect.objectContaining({ code: 'LSP_DISPOSED' }))
  269. })
  270. it('reports dead after the process closes', async () => {
  271. const instance = makeInstance({ LSP_FAKE_DEF: 'null' })
  272. await run(instance, 'goToDefinition')
  273. await instance.dispose()
  274. expect(instance.dead).toBe(true)
  275. })
  276. it('escalates to SIGKILL when the server ignores shutdown and SIGTERM', async () => {
  277. // Server answers initialize, ignores shutdown, and traps SIGTERM so only SIGKILL stops it.
  278. const script = RESPONDING_SERVER + 'process.on("SIGTERM",()=>{});'
  279. const instance = scriptInstance(script, { shutdownTimeoutMs: 100, killGraceMs: 100 })
  280. await run(instance, 'goToDefinition')
  281. await expect(instance.dispose()).resolves.toBeUndefined()
  282. })
  283. it('awaits a surviving process-tree helper on every concurrent dispose', async () => {
  284. const marker = join(root, 'helper.pid')
  285. const helper = 'process.on("SIGTERM",()=>{});setInterval(()=>{},1000);'
  286. const script = 'const{spawn}=require("node:child_process");const{writeFileSync}=require("node:fs");'
  287. + `const helper=spawn(process.execPath,["-e",${JSON.stringify(helper)}],{stdio:"ignore"});`
  288. + `writeFileSync(${JSON.stringify(marker)},String(helper.pid));`
  289. + RESPONDING_SERVER
  290. const instance = scriptInstance(script, { shutdownTimeoutMs: 100, killGraceMs: 100 })
  291. await run(instance, 'goToDefinition')
  292. const helperPid = Number(await readFile(marker, 'utf8'))
  293. try {
  294. const first = instance.dispose()
  295. await instance.dispose()
  296. expect(processAlive(helperPid)).toBe(false)
  297. await first
  298. } finally {
  299. if (processAlive(helperPid)) process.kill(helperPid, 'SIGKILL')
  300. await waitForProcessExit(helperPid)
  301. }
  302. })
  303. it('carries a non-Error abort reason as a generic aborted error', async () => {
  304. const instance = makeInstance({ LSP_FAKE_HANG: '1' })
  305. const controller = new AbortController()
  306. const pending = run(instance, 'goToDefinition', controller.signal)
  307. await new Promise<void>(resolve => setTimeout(resolve, 200))
  308. controller.abort('a string reason, not an Error')
  309. await expect(pending).rejects.toThrow(/aborted/)
  310. })
  311. })
  312. /** Probe a pid without changing its state. */
  313. function processAlive(pid: number): boolean {
  314. try {
  315. process.kill(pid, 0)
  316. } catch (error) {
  317. if ((error as NodeJS.ErrnoException).code === 'ESRCH') return false
  318. throw error
  319. }
  320. if (process.platform !== 'linux') return true
  321. try {
  322. const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
  323. const state = stat.slice(stat.lastIndexOf(')') + 2).split(/\s+/, 1)[0]
  324. return !/^[ZXx]$/.test(state ?? '')
  325. } catch (error) {
  326. if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false
  327. throw error
  328. }
  329. }
  330. /** Wait until a process can no longer execute so temporary-workspace cleanup cannot race handle release. */
  331. async function waitForProcessExit(pid: number, timeoutMs = 3_000): Promise<void> {
  332. const started = Date.now()
  333. while (processAlive(pid)) {
  334. if (Date.now() - started > timeoutMs) throw new Error(`process ${pid} did not exit`)
  335. await new Promise<void>(resolve => setTimeout(resolve, 10))
  336. }
  337. }
  338. /** Write normally except for one method whose callback receives a deterministic transport error. */
  339. function failingWriter(method: string): ConnectionWriter {
  340. return (stdin, message, done) => {
  341. if ((message as { method?: unknown }).method === method) {
  342. queueMicrotask(() => { done(new Error(`fixture ${method} failure`)) })
  343. return
  344. }
  345. stdin.write(encodeMessage(message), done)
  346. }
  347. }
  348. /** Wait until a fixture marker exists, bounded so a broken handshake cannot hang the test. */
  349. async function waitForFile(path: string, timeoutMs = 3000): Promise<void> {
  350. const started = Date.now()
  351. for (;;) {
  352. try {
  353. await readFile(path)
  354. return
  355. } catch (error) {
  356. if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
  357. }
  358. if (Date.now() - started > timeoutMs) throw new Error('waitForFile timed out')
  359. await new Promise<void>(resolve => setTimeout(resolve, 10))
  360. }
  361. }