File size: 16,864 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | import * as path from 'path'
import { pathToFileURL } from 'url'
import type { InitializeParams } from 'vscode-languageserver-protocol'
import { getCwd } from '../../utils/cwd.js'
import { logForDebugging } from '../../utils/debug.js'
import { errorMessage } from '../../utils/errors.js'
import { logError } from '../../utils/log.js'
import { sleep } from '../../utils/sleep.js'
import type { createLSPClient as createLSPClientType } from './LSPClient.js'
import type { LspServerState, ScopedLspServerConfig } from './types.js'
/**
* LSP error code for "content modified" - indicates the server's state changed
* during request processing (e.g., rust-analyzer still indexing the project).
* This is a transient error that can be retried.
*/
const LSP_ERROR_CONTENT_MODIFIED = -32801
/**
* Maximum number of retries for transient LSP errors like "content modified".
*/
const MAX_RETRIES_FOR_TRANSIENT_ERRORS = 3
/**
* Base delay in milliseconds for exponential backoff on transient errors.
* Actual delays: 500ms, 1000ms, 2000ms
*/
const RETRY_BASE_DELAY_MS = 500
/**
* LSP server instance interface returned by createLSPServerInstance.
* Manages the lifecycle of a single LSP server with state tracking and health monitoring.
*/
export type LSPServerInstance = {
/** Unique server identifier */
readonly name: string
/** Server configuration */
readonly config: ScopedLspServerConfig
/** Current server state */
readonly state: LspServerState
/** When the server was last started */
readonly startTime: Date | undefined
/** Last error encountered */
readonly lastError: Error | undefined
/** Number of times restart() has been called */
readonly restartCount: number
/** Start the server and initialize it */
start(): Promise<void>
/** Stop the server gracefully */
stop(): Promise<void>
/** Manually restart the server (stop then start) */
restart(): Promise<void>
/** Check if server is healthy and ready for requests */
isHealthy(): boolean
/** Send an LSP request to the server */
sendRequest<T>(method: string, params: unknown): Promise<T>
/** Send an LSP notification to the server (fire-and-forget) */
sendNotification(method: string, params: unknown): Promise<void>
/** Register a handler for LSP notifications */
onNotification(method: string, handler: (params: unknown) => void): void
/** Register a handler for LSP requests from the server */
onRequest<TParams, TResult>(
method: string,
handler: (params: TParams) => TResult | Promise<TResult>,
): void
}
/**
* Creates and manages a single LSP server instance.
*
* Uses factory function pattern with closures for state encapsulation (avoiding classes).
* Provides state tracking, health monitoring, and request forwarding for an LSP server.
* Supports manual restart with configurable retry limits.
*
* State machine transitions:
* - stopped → starting → running
* - running → stopping → stopped
* - any → error (on failure)
* - error → starting (on retry)
*
* @param name - Unique identifier for this server instance
* @param config - Server configuration including command, args, and limits
* @returns LSP server instance with lifecycle management methods
*
* @example
* const instance = createLSPServerInstance('my-server', config)
* await instance.start()
* const result = await instance.sendRequest('textDocument/definition', params)
* await instance.stop()
*/
export function createLSPServerInstance(
name: string,
config: ScopedLspServerConfig,
): LSPServerInstance {
// Validate that unimplemented fields are not set
if (config.restartOnCrash !== undefined) {
throw new Error(
`LSP server '${name}': restartOnCrash is not yet implemented. Remove this field from the configuration.`,
)
}
if (config.shutdownTimeout !== undefined) {
throw new Error(
`LSP server '${name}': shutdownTimeout is not yet implemented. Remove this field from the configuration.`,
)
}
// Private state encapsulated via closures. Lazy-require LSPClient so
// vscode-jsonrpc (~129KB) only loads when an LSP server is actually
// instantiated, not when the static import chain reaches this module.
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { createLSPClient } = require('./LSPClient.js') as {
createLSPClient: typeof createLSPClientType
}
let state: LspServerState = 'stopped'
let startTime: Date | undefined
let lastError: Error | undefined
let restartCount = 0
let crashRecoveryCount = 0
// Propagate crash state so ensureServerStarted can restart on next use.
// Without this, state stays 'running' after crash and the server is never
// restarted (zombie state).
const client = createLSPClient(name, error => {
state = 'error'
lastError = error
crashRecoveryCount++
})
/**
* Starts the LSP server and initializes it with workspace information.
*
* If the server is already running or starting, this method returns immediately.
* On failure, sets state to 'error', logs for monitoring, and throws.
*
* @throws {Error} If server fails to start or initialize
*/
async function start(): Promise<void> {
if (state === 'running' || state === 'starting') {
return
}
// Cap crash-recovery attempts so a persistently crashing server doesn't
// spawn unbounded child processes on every incoming request.
const maxRestarts = config.maxRestarts ?? 3
if (state === 'error' && crashRecoveryCount > maxRestarts) {
const error = new Error(
`LSP server '${name}' exceeded max crash recovery attempts (${maxRestarts})`,
)
lastError = error
logError(error)
throw error
}
let initPromise: Promise<unknown> | undefined
try {
state = 'starting'
logForDebugging(`Starting LSP server instance: ${name}`)
// Start the client
await client.start(config.command, config.args || [], {
env: config.env,
cwd: config.workspaceFolder,
})
// Initialize with workspace info
const workspaceFolder = config.workspaceFolder || getCwd()
const workspaceUri = pathToFileURL(workspaceFolder).href
const initParams: InitializeParams = {
processId: process.pid,
// Pass server-specific initialization options from plugin config
// Required by vue-language-server, optional for others
// Provide empty object as default to avoid undefined errors in servers
// that expect this field to exist
initializationOptions: config.initializationOptions ?? {},
// Modern approach (LSP 3.16+) - required for Pyright, gopls
workspaceFolders: [
{
uri: workspaceUri,
name: path.basename(workspaceFolder),
},
],
// Deprecated fields - some servers still need these for proper URI resolution
rootPath: workspaceFolder, // Deprecated in LSP 3.8 but needed by some servers
rootUri: workspaceUri, // Deprecated in LSP 3.16 but needed by typescript-language-server for goToDefinition
// Client capabilities - declare what features we support
capabilities: {
workspace: {
// Don't claim to support workspace/configuration since we don't implement it
// This prevents servers from requesting config we can't provide
configuration: false,
// Don't claim to support workspace folders changes since we don't handle
// workspace/didChangeWorkspaceFolders notifications
workspaceFolders: false,
},
textDocument: {
synchronization: {
dynamicRegistration: false,
willSave: false,
willSaveWaitUntil: false,
didSave: true,
},
publishDiagnostics: {
relatedInformation: true,
tagSupport: {
valueSet: [1, 2], // Unnecessary (1), Deprecated (2)
},
versionSupport: false,
codeDescriptionSupport: true,
dataSupport: false,
},
hover: {
dynamicRegistration: false,
contentFormat: ['markdown', 'plaintext'],
},
definition: {
dynamicRegistration: false,
linkSupport: true,
},
references: {
dynamicRegistration: false,
},
documentSymbol: {
dynamicRegistration: false,
hierarchicalDocumentSymbolSupport: true,
},
callHierarchy: {
dynamicRegistration: false,
},
},
general: {
positionEncodings: ['utf-16'],
},
},
}
initPromise = client.initialize(initParams)
if (config.startupTimeout !== undefined) {
await withTimeout(
initPromise,
config.startupTimeout,
`LSP server '${name}' timed out after ${config.startupTimeout}ms during initialization`,
)
} else {
await initPromise
}
state = 'running'
startTime = new Date()
crashRecoveryCount = 0
logForDebugging(`LSP server instance started: ${name}`)
} catch (error) {
// Clean up the spawned child process on timeout/error
client.stop().catch(() => {})
// Prevent unhandled rejection from abandoned initialize promise
initPromise?.catch(() => {})
state = 'error'
lastError = error as Error
logError(error)
throw error
}
}
/**
* Stops the LSP server gracefully.
*
* If already stopped or stopping, returns immediately.
* On failure, sets state to 'error', logs for monitoring, and throws.
*
* @throws {Error} If server fails to stop
*/
async function stop(): Promise<void> {
if (state === 'stopped' || state === 'stopping') {
return
}
try {
state = 'stopping'
await client.stop()
state = 'stopped'
logForDebugging(`LSP server instance stopped: ${name}`)
} catch (error) {
state = 'error'
lastError = error as Error
logError(error)
throw error
}
}
/**
* Manually restarts the server by stopping and starting it.
*
* Increments restartCount and enforces maxRestarts limit.
* Note: This is NOT automatic - must be called explicitly.
*
* @throws {Error} If stop or start fails, or if restartCount exceeds config.maxRestarts (default: 3)
*/
async function restart(): Promise<void> {
try {
await stop()
} catch (error) {
const stopError = new Error(
`Failed to stop LSP server '${name}' during restart: ${errorMessage(error)}`,
)
logError(stopError)
throw stopError
}
restartCount++
const maxRestarts = config.maxRestarts ?? 3
if (restartCount > maxRestarts) {
const error = new Error(
`Max restart attempts (${maxRestarts}) exceeded for server '${name}'`,
)
logError(error)
throw error
}
try {
await start()
} catch (error) {
const startError = new Error(
`Failed to start LSP server '${name}' during restart (attempt ${restartCount}/${maxRestarts}): ${errorMessage(error)}`,
)
logError(startError)
throw startError
}
}
/**
* Checks if the server is healthy and ready to handle requests.
*
* @returns true if state is 'running' AND the client has completed initialization
*/
function isHealthy(): boolean {
return state === 'running' && client.isInitialized
}
/**
* Sends an LSP request to the server with retry logic for transient errors.
*
* Checks server health before sending and wraps errors with context.
* Automatically retries on "content modified" errors (code -32801) which occur
* when servers like rust-analyzer are still indexing. This is expected LSP behavior
* and clients should retry silently per the LSP specification.
*
* @param method - LSP method name (e.g., 'textDocument/definition')
* @param params - Method-specific parameters
* @returns The server's response
* @throws {Error} If server is not healthy or request fails after all retries
*/
async function sendRequest<T>(method: string, params: unknown): Promise<T> {
if (!isHealthy()) {
const error = new Error(
`Cannot send request to LSP server '${name}': server is ${state}` +
`${lastError ? `, last error: ${lastError.message}` : ''}`,
)
logError(error)
throw error
}
let lastAttemptError: Error | undefined
for (
let attempt = 0;
attempt <= MAX_RETRIES_FOR_TRANSIENT_ERRORS;
attempt++
) {
try {
return await client.sendRequest(method, params)
} catch (error) {
lastAttemptError = error as Error
// Check if this is a transient "content modified" error that we should retry
// This commonly happens with rust-analyzer during initial project indexing.
// We use duck typing instead of instanceof because there may be multiple
// versions of vscode-jsonrpc in the dependency tree (8.2.0 vs 8.2.1).
const errorCode = (error as { code?: number }).code
const isContentModifiedError =
typeof errorCode === 'number' &&
errorCode === LSP_ERROR_CONTENT_MODIFIED
if (
isContentModifiedError &&
attempt < MAX_RETRIES_FOR_TRANSIENT_ERRORS
) {
const delay = RETRY_BASE_DELAY_MS * Math.pow(2, attempt)
logForDebugging(
`LSP request '${method}' to '${name}' got ContentModified error, ` +
`retrying in ${delay}ms (attempt ${attempt + 1}/${MAX_RETRIES_FOR_TRANSIENT_ERRORS})…`,
)
await sleep(delay)
continue
}
// Non-retryable error or max retries exceeded
break
}
}
// All retries failed or non-retryable error
const requestError = new Error(
`LSP request '${method}' failed for server '${name}': ${lastAttemptError?.message ?? 'unknown error'}`,
)
logError(requestError)
throw requestError
}
/**
* Send a notification to the LSP server (fire-and-forget).
* Used for file synchronization (didOpen, didChange, didClose).
*/
async function sendNotification(
method: string,
params: unknown,
): Promise<void> {
if (!isHealthy()) {
const error = new Error(
`Cannot send notification to LSP server '${name}': server is ${state}`,
)
logError(error)
throw error
}
try {
await client.sendNotification(method, params)
} catch (error) {
const notificationError = new Error(
`LSP notification '${method}' failed for server '${name}': ${errorMessage(error)}`,
)
logError(notificationError)
throw notificationError
}
}
/**
* Registers a handler for LSP notifications from the server.
*
* @param method - LSP notification method (e.g., 'window/logMessage')
* @param handler - Callback function to handle the notification
*/
function onNotification(
method: string,
handler: (params: unknown) => void,
): void {
client.onNotification(method, handler)
}
/**
* Registers a handler for LSP requests from the server.
*
* Some LSP servers send requests TO the client (reverse direction).
* This allows registering handlers for such requests.
*
* @param method - LSP request method (e.g., 'workspace/configuration')
* @param handler - Callback function to handle the request and return a response
*/
function onRequest<TParams, TResult>(
method: string,
handler: (params: TParams) => TResult | Promise<TResult>,
): void {
client.onRequest(method, handler)
}
// Return public API
return {
name,
config,
get state() {
return state
},
get startTime() {
return startTime
},
get lastError() {
return lastError
},
get restartCount() {
return restartCount
},
start,
stop,
restart,
isHealthy,
sendRequest,
sendNotification,
onNotification,
onRequest,
}
}
/**
* Race a promise against a timeout. Cleans up the timer regardless of outcome
* to avoid unhandled rejections from orphaned setTimeout callbacks.
*/
function withTimeout<T>(
promise: Promise<T>,
ms: number,
message: string,
): Promise<T> {
let timer: ReturnType<typeof setTimeout>
const timeoutPromise = new Promise<never>((_, reject) => {
timer = setTimeout((rej, msg) => rej(new Error(msg)), ms, reject, message)
})
return Promise.race([promise, timeoutPromise]).finally(() =>
clearTimeout(timer!),
)
}
|