client.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. package lsp
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "log/slog"
  7. "maps"
  8. "os"
  9. "path/filepath"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "github.com/charmbracelet/crush/internal/config"
  14. "github.com/charmbracelet/crush/internal/csync"
  15. "github.com/charmbracelet/crush/internal/fsext"
  16. "github.com/charmbracelet/crush/internal/home"
  17. powernap "github.com/charmbracelet/x/powernap/pkg/lsp"
  18. "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
  19. "github.com/charmbracelet/x/powernap/pkg/transport"
  20. )
  21. // DiagnosticCounts holds the count of diagnostics by severity.
  22. type DiagnosticCounts struct {
  23. Error int
  24. Warning int
  25. Information int
  26. Hint int
  27. }
  28. type Client struct {
  29. client *powernap.Client
  30. name string
  31. debug bool
  32. // Working directory this LSP is scoped to.
  33. cwd string
  34. // File types this LSP server handles (e.g., .go, .rs, .py)
  35. fileTypes []string
  36. // Configuration for this LSP client
  37. config config.LSPConfig
  38. // Original context and resolver for recreating the client
  39. ctx context.Context
  40. resolver config.VariableResolver
  41. // Diagnostic change callback
  42. onDiagnosticsChanged func(name string, count int)
  43. // Diagnostic cache
  44. diagnostics *csync.VersionedMap[protocol.DocumentURI, []protocol.Diagnostic]
  45. // Cached diagnostic counts to avoid map copy on every UI render.
  46. diagCountsCache DiagnosticCounts
  47. diagCountsVersion uint64
  48. diagCountsMu sync.Mutex
  49. // Files are currently opened by the LSP
  50. openFiles *csync.Map[string, *OpenFileInfo]
  51. // Server state
  52. serverState atomic.Value
  53. }
  54. // New creates a new LSP client using the powernap implementation.
  55. func New(
  56. ctx context.Context,
  57. name string,
  58. cfg config.LSPConfig,
  59. resolver config.VariableResolver,
  60. cwd string,
  61. debug bool,
  62. ) (*Client, error) {
  63. client := &Client{
  64. name: name,
  65. fileTypes: cfg.FileTypes,
  66. diagnostics: csync.NewVersionedMap[protocol.DocumentURI, []protocol.Diagnostic](),
  67. openFiles: csync.NewMap[string, *OpenFileInfo](),
  68. config: cfg,
  69. ctx: ctx,
  70. debug: debug,
  71. resolver: resolver,
  72. cwd: cwd,
  73. }
  74. client.serverState.Store(StateStopped)
  75. if err := client.createPowernapClient(); err != nil {
  76. return nil, err
  77. }
  78. return client, nil
  79. }
  80. // Initialize initializes the LSP client and returns the server capabilities.
  81. func (c *Client) Initialize(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
  82. if err := c.client.Initialize(ctx, false); err != nil {
  83. return nil, fmt.Errorf("failed to initialize the lsp client: %w", err)
  84. }
  85. // Convert powernap capabilities to protocol capabilities
  86. caps := c.client.GetCapabilities()
  87. protocolCaps := protocol.ServerCapabilities{
  88. TextDocumentSync: caps.TextDocumentSync,
  89. CompletionProvider: func() *protocol.CompletionOptions {
  90. if caps.CompletionProvider != nil {
  91. return &protocol.CompletionOptions{
  92. TriggerCharacters: caps.CompletionProvider.TriggerCharacters,
  93. AllCommitCharacters: caps.CompletionProvider.AllCommitCharacters,
  94. ResolveProvider: caps.CompletionProvider.ResolveProvider,
  95. }
  96. }
  97. return nil
  98. }(),
  99. }
  100. result := &protocol.InitializeResult{
  101. Capabilities: protocolCaps,
  102. }
  103. c.registerHandlers()
  104. return result, nil
  105. }
  106. // closeTimeout is the maximum time to wait for a graceful LSP shutdown.
  107. const closeTimeout = 5 * time.Second
  108. // Kill kills the client without doing anything else.
  109. func (c *Client) Kill() { c.client.Kill() }
  110. // Close closes all open files in the client, then shuts down gracefully.
  111. // If shutdown takes longer than closeTimeout, it falls back to Kill().
  112. func (c *Client) Close(ctx context.Context) error {
  113. c.CloseAllFiles(ctx)
  114. // Use a timeout to prevent hanging on unresponsive LSP servers.
  115. // jsonrpc2's send lock doesn't respect context cancellation, so we
  116. // need to fall back to Kill() which closes the underlying connection.
  117. closeCtx, cancel := context.WithTimeout(ctx, closeTimeout)
  118. defer cancel()
  119. done := make(chan error, 1)
  120. go func() {
  121. if err := c.client.Shutdown(closeCtx); err != nil {
  122. slog.Warn("Failed to shutdown LSP client", "error", err)
  123. }
  124. done <- c.client.Exit()
  125. }()
  126. select {
  127. case err := <-done:
  128. return err
  129. case <-closeCtx.Done():
  130. c.client.Kill()
  131. return closeCtx.Err()
  132. }
  133. }
  134. // createPowernapClient creates a new powernap client with the current configuration.
  135. func (c *Client) createPowernapClient() error {
  136. rootURI := string(protocol.URIFromPath(c.cwd))
  137. command, err := c.resolver.ResolveValue(c.config.Command)
  138. if err != nil {
  139. return fmt.Errorf("invalid lsp command: %w", err)
  140. }
  141. clientConfig := powernap.ClientConfig{
  142. Command: home.Long(command),
  143. Args: c.config.Args,
  144. RootURI: rootURI,
  145. Environment: maps.Clone(c.config.Env),
  146. Settings: c.config.Options,
  147. InitOptions: c.config.InitOptions,
  148. WorkspaceFolders: []protocol.WorkspaceFolder{
  149. {
  150. URI: rootURI,
  151. Name: filepath.Base(c.cwd),
  152. },
  153. },
  154. }
  155. powernapClient, err := powernap.NewClient(clientConfig)
  156. if err != nil {
  157. return fmt.Errorf("failed to create lsp client: %w", err)
  158. }
  159. c.client = powernapClient
  160. return nil
  161. }
  162. // registerHandlers registers the standard LSP notification and request handlers.
  163. func (c *Client) registerHandlers() {
  164. c.RegisterServerRequestHandler("workspace/applyEdit", HandleApplyEdit(c.client.GetOffsetEncoding()))
  165. c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
  166. c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
  167. c.RegisterNotificationHandler("window/showMessage", func(ctx context.Context, method string, params json.RawMessage) {
  168. if c.debug {
  169. HandleServerMessage(ctx, method, params)
  170. }
  171. })
  172. c.RegisterNotificationHandler("textDocument/publishDiagnostics", func(_ context.Context, _ string, params json.RawMessage) {
  173. HandleDiagnostics(c, params)
  174. })
  175. }
  176. // Restart closes the current LSP client and creates a new one with the same configuration.
  177. func (c *Client) Restart() error {
  178. var openFiles []string
  179. for uri := range c.openFiles.Seq2() {
  180. openFiles = append(openFiles, string(uri))
  181. }
  182. closeCtx, cancel := context.WithTimeout(c.ctx, 10*time.Second)
  183. defer cancel()
  184. if err := c.Close(closeCtx); err != nil {
  185. slog.Warn("Error closing client during restart", "name", c.name, "error", err)
  186. }
  187. c.SetServerState(StateStopped)
  188. c.diagCountsCache = DiagnosticCounts{}
  189. c.diagCountsVersion = 0
  190. if err := c.createPowernapClient(); err != nil {
  191. return err
  192. }
  193. initCtx, cancel := context.WithTimeout(c.ctx, 30*time.Second)
  194. defer cancel()
  195. c.SetServerState(StateStarting)
  196. if err := c.client.Initialize(initCtx, false); err != nil {
  197. c.SetServerState(StateError)
  198. return fmt.Errorf("failed to initialize lsp client: %w", err)
  199. }
  200. c.registerHandlers()
  201. if err := c.WaitForServerReady(initCtx); err != nil {
  202. slog.Error("Server failed to become ready after restart", "name", c.name, "error", err)
  203. c.SetServerState(StateError)
  204. return err
  205. }
  206. for _, uri := range openFiles {
  207. if err := c.OpenFile(initCtx, uri); err != nil {
  208. slog.Warn("Failed to reopen file after restart", "file", uri, "error", err)
  209. }
  210. }
  211. return nil
  212. }
  213. // ServerState represents the state of an LSP server
  214. type ServerState int
  215. const (
  216. StateUnstarted ServerState = iota
  217. StateStarting
  218. StateReady
  219. StateError
  220. StateStopped
  221. StateDisabled
  222. )
  223. // GetServerState returns the current state of the LSP server
  224. func (c *Client) GetServerState() ServerState {
  225. if val := c.serverState.Load(); val != nil {
  226. return val.(ServerState)
  227. }
  228. return StateStarting
  229. }
  230. // SetServerState sets the current state of the LSP server
  231. func (c *Client) SetServerState(state ServerState) {
  232. c.serverState.Store(state)
  233. }
  234. // GetName returns the name of the LSP client
  235. func (c *Client) GetName() string {
  236. return c.name
  237. }
  238. // SetDiagnosticsCallback sets the callback function for diagnostic changes
  239. func (c *Client) SetDiagnosticsCallback(callback func(name string, count int)) {
  240. c.onDiagnosticsChanged = callback
  241. }
  242. // WaitForServerReady waits for the server to be ready
  243. func (c *Client) WaitForServerReady(ctx context.Context) error {
  244. // Set initial state
  245. c.SetServerState(StateStarting)
  246. // Try to ping the server with a simple request
  247. ticker := time.NewTicker(500 * time.Millisecond)
  248. defer ticker.Stop()
  249. if c.debug {
  250. slog.Debug("Waiting for LSP server to be ready...")
  251. }
  252. c.openKeyConfigFiles(ctx)
  253. for {
  254. select {
  255. case <-ctx.Done():
  256. c.SetServerState(StateError)
  257. return fmt.Errorf("timeout waiting for LSP server to be ready")
  258. case <-ticker.C:
  259. // Check if client is running
  260. if !c.client.IsRunning() {
  261. if c.debug {
  262. slog.Debug("LSP server not ready yet", "server", c.name)
  263. }
  264. continue
  265. }
  266. // Server is ready
  267. c.SetServerState(StateReady)
  268. if c.debug {
  269. slog.Debug("LSP server is ready")
  270. }
  271. return nil
  272. }
  273. }
  274. }
  275. // OpenFileInfo contains information about an open file
  276. type OpenFileInfo struct {
  277. Version int32
  278. URI protocol.DocumentURI
  279. }
  280. // HandlesFile checks if this LSP client handles the given file based on its
  281. // extension and whether it's within the working directory.
  282. func (c *Client) HandlesFile(path string) bool {
  283. if c == nil {
  284. return false
  285. }
  286. if !fsext.HasPrefix(path, c.cwd) {
  287. slog.Debug("File outside workspace", "name", c.name, "file", path, "workDir", c.cwd)
  288. return false
  289. }
  290. return handlesFiletype(c.name, c.fileTypes, path)
  291. }
  292. // OpenFile opens a file in the LSP server.
  293. func (c *Client) OpenFile(ctx context.Context, filepath string) error {
  294. if !c.HandlesFile(filepath) {
  295. return nil
  296. }
  297. uri := string(protocol.URIFromPath(filepath))
  298. if _, exists := c.openFiles.Get(uri); exists {
  299. return nil // Already open
  300. }
  301. // Skip files that do not exist or cannot be read
  302. content, err := os.ReadFile(filepath)
  303. if err != nil {
  304. return fmt.Errorf("error reading file: %w", err)
  305. }
  306. // Notify the server about the opened document
  307. if err = c.client.NotifyDidOpenTextDocument(ctx, uri, string(powernap.DetectLanguage(filepath)), 1, string(content)); err != nil {
  308. return err
  309. }
  310. c.openFiles.Set(uri, &OpenFileInfo{
  311. Version: 1,
  312. URI: protocol.DocumentURI(uri),
  313. })
  314. return nil
  315. }
  316. // NotifyChange notifies the server about a file change.
  317. func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
  318. if c == nil {
  319. return nil
  320. }
  321. uri := string(protocol.URIFromPath(filepath))
  322. content, err := os.ReadFile(filepath)
  323. if err != nil {
  324. return fmt.Errorf("error reading file: %w", err)
  325. }
  326. fileInfo, isOpen := c.openFiles.Get(uri)
  327. if !isOpen {
  328. return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
  329. }
  330. // Increment version
  331. fileInfo.Version++
  332. // Create change event
  333. changes := []protocol.TextDocumentContentChangeEvent{
  334. {
  335. Value: protocol.TextDocumentContentChangeWholeDocument{
  336. Text: string(content),
  337. },
  338. },
  339. }
  340. return c.client.NotifyDidChangeTextDocument(ctx, uri, int(fileInfo.Version), changes)
  341. }
  342. // IsFileOpen checks if a file is currently open.
  343. func (c *Client) IsFileOpen(filepath string) bool {
  344. uri := string(protocol.URIFromPath(filepath))
  345. _, exists := c.openFiles.Get(uri)
  346. return exists
  347. }
  348. // CloseAllFiles closes all currently open files.
  349. func (c *Client) CloseAllFiles(ctx context.Context) {
  350. for uri := range c.openFiles.Seq2() {
  351. if c.debug {
  352. slog.Debug("Closing file", "file", uri)
  353. }
  354. if err := c.client.NotifyDidCloseTextDocument(ctx, uri); err != nil {
  355. slog.Warn("Error closing file", "uri", uri, "error", err)
  356. continue
  357. }
  358. c.openFiles.Del(uri)
  359. }
  360. }
  361. // GetFileDiagnostics returns diagnostics for a specific file.
  362. func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
  363. diags, _ := c.diagnostics.Get(uri)
  364. return diags
  365. }
  366. // GetDiagnostics returns all diagnostics for all files.
  367. func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
  368. if c == nil {
  369. return nil
  370. }
  371. return c.diagnostics.Copy()
  372. }
  373. // GetDiagnosticCounts returns cached diagnostic counts by severity.
  374. // Uses the VersionedMap version to avoid recomputing on every call.
  375. func (c *Client) GetDiagnosticCounts() DiagnosticCounts {
  376. if c == nil {
  377. return DiagnosticCounts{}
  378. }
  379. currentVersion := c.diagnostics.Version()
  380. c.diagCountsMu.Lock()
  381. defer c.diagCountsMu.Unlock()
  382. if currentVersion == c.diagCountsVersion {
  383. return c.diagCountsCache
  384. }
  385. // Recompute counts.
  386. counts := DiagnosticCounts{}
  387. for _, diags := range c.diagnostics.Seq2() {
  388. for _, diag := range diags {
  389. switch diag.Severity {
  390. case protocol.SeverityError:
  391. counts.Error++
  392. case protocol.SeverityWarning:
  393. counts.Warning++
  394. case protocol.SeverityInformation:
  395. counts.Information++
  396. case protocol.SeverityHint:
  397. counts.Hint++
  398. }
  399. }
  400. }
  401. c.diagCountsCache = counts
  402. c.diagCountsVersion = currentVersion
  403. return counts
  404. }
  405. // OpenFileOnDemand opens a file only if it's not already open.
  406. func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
  407. if c == nil {
  408. return nil
  409. }
  410. // Check if the file is already open
  411. if c.IsFileOpen(filepath) {
  412. return nil
  413. }
  414. // Open the file
  415. return c.OpenFile(ctx, filepath)
  416. }
  417. // RegisterNotificationHandler registers a notification handler.
  418. func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
  419. c.client.RegisterNotificationHandler(method, handler)
  420. }
  421. // RegisterServerRequestHandler handles server requests.
  422. func (c *Client) RegisterServerRequestHandler(method string, handler transport.Handler) {
  423. c.client.RegisterHandler(method, handler)
  424. }
  425. // openKeyConfigFiles opens important configuration files that help initialize the server.
  426. func (c *Client) openKeyConfigFiles(ctx context.Context) {
  427. // Try to open each file, ignoring errors if they don't exist
  428. for _, file := range c.config.RootMarkers {
  429. file = filepath.Join(c.cwd, file)
  430. if _, err := os.Stat(file); err == nil {
  431. // File exists, try to open it
  432. if err := c.OpenFile(ctx, file); err != nil {
  433. slog.Error("Failed to open key config file", "file", file, "error", err)
  434. } else {
  435. slog.Debug("Opened key config file for initialization", "file", file)
  436. }
  437. }
  438. }
  439. }
  440. // WaitForDiagnostics waits until diagnostics change or the timeout is reached.
  441. func (c *Client) WaitForDiagnostics(ctx context.Context, d time.Duration) {
  442. if c == nil {
  443. return
  444. }
  445. ticker := time.NewTicker(200 * time.Millisecond)
  446. defer ticker.Stop()
  447. timeout := time.After(d)
  448. pv := c.diagnostics.Version()
  449. for {
  450. select {
  451. case <-ctx.Done():
  452. return
  453. case <-timeout:
  454. return
  455. case <-ticker.C:
  456. if pv != c.diagnostics.Version() {
  457. return
  458. }
  459. }
  460. }
  461. }
  462. // FindReferences finds all references to the symbol at the given position.
  463. func (c *Client) FindReferences(ctx context.Context, filepath string, line, character int, includeDeclaration bool) ([]protocol.Location, error) {
  464. if err := c.OpenFileOnDemand(ctx, filepath); err != nil {
  465. return nil, err
  466. }
  467. // Add timeout to prevent hanging on slow LSP servers.
  468. ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
  469. defer cancel()
  470. // NOTE: line and character should be 0-based.
  471. // See: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#position
  472. return c.client.FindReferences(ctx, filepath, line-1, character-1, includeDeclaration)
  473. }