xonecas.io
62159
Sy

symb / files

symb / internal / lsp / client.go

5.5 KB
1// Package lsp wraps powernap to provide LSP diagnostics for file mutations.
2package lsp
3
4import (
5	"context"
6	"encoding/json"
7	"fmt"
8	"os"
9	"sync"
10	"time"
11
12	powernap "github.com/charmbracelet/x/powernap/pkg/lsp"
13	"github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
14	"github.com/rs/zerolog/log"
15)
16
17// Severity constants matching LSP DiagnosticSeverity.
18const (
19	SeverityError   = 1
20	SeverityWarning = 2
21)
22
23// Client wraps a powernap LSP client with diagnostics tracking.
24type Client struct {
25	inner    *powernap.Client
26	serverID string
27
28	mu          sync.Mutex
29	diags       map[string][]protocol.Diagnostic // uri -> diagnostics
30	versions    map[string]int                   // uri -> document version
31	diagChanged chan struct{}                    // signaled on publishDiagnostics
32}
33
34// newClient spawns an LSP server and returns a wrapped client.
35func newClient(serverID string, cfg powernap.ClientConfig) (*Client, error) {
36	inner, err := powernap.NewClient(cfg)
37	if err != nil {
38		return nil, fmt.Errorf("lsp: start %s: %w", serverID, err)
39	}
40
41	c := &Client{
42		inner:       inner,
43		serverID:    serverID,
44		diags:       make(map[string][]protocol.Diagnostic),
45		versions:    make(map[string]int),
46		diagChanged: make(chan struct{}, 1),
47	}
48
49	// Register publishDiagnostics handler before Initialize.
50	inner.RegisterNotificationHandler(
51		"textDocument/publishDiagnostics",
52		func(_ context.Context, _ string, params json.RawMessage) {
53			var p protocol.PublishDiagnosticsParams
54			if err := json.Unmarshal(params, &p); err != nil {
55				log.Error().Err(err).Msg("lsp: unmarshal diagnostics")
56				return
57			}
58			c.mu.Lock()
59			c.diags[string(p.URI)] = p.Diagnostics
60			c.mu.Unlock()
61
62			// Non-blocking signal.
63			select {
64			case c.diagChanged <- struct{}{}:
65			default:
66			}
67		},
68	)
69
70	// Stub handlers so the server doesn't error on common requests.
71	inner.RegisterHandler("window/workDoneProgress/create",
72		func(_ context.Context, _ string, _ json.RawMessage) (any, error) {
73			return nil, nil
74		},
75	)
76	inner.RegisterNotificationHandler("$/progress",
77		func(_ context.Context, _ string, _ json.RawMessage) {},
78	)
79	inner.RegisterNotificationHandler("window/logMessage",
80		func(_ context.Context, _ string, _ json.RawMessage) {},
81	)
82	inner.RegisterHandler("client/registerCapability",
83		func(_ context.Context, _ string, _ json.RawMessage) (any, error) {
84			return nil, nil
85		},
86	)
87
88	return c, nil
89}
90
91// initialize sends initialize+initialized to the server.
92func (c *Client) initialize(ctx context.Context) error {
93	return c.inner.Initialize(ctx, false)
94}
95
96// openFile reads a file from disk and sends textDocument/didOpen.
97// If already open, sends didChange instead.
98func (c *Client) openFile(ctx context.Context, absPath string) error {
99	uri := string(protocol.URIFromPath(absPath))
100
101	c.mu.Lock()
102	_, alreadyOpen := c.versions[uri]
103	c.mu.Unlock()
104	if alreadyOpen {
105		return c.notifyChange(ctx, absPath)
106	}
107
108	data, err := os.ReadFile(absPath)
109	if err != nil {
110		return fmt.Errorf("lsp: read %s: %w", absPath, err)
111	}
112
113	lang := powernap.DetectLanguage(absPath)
114
115	c.mu.Lock()
116	c.versions[uri] = 0
117	c.mu.Unlock()
118
119	return c.inner.NotifyDidOpenTextDocument(ctx, uri, string(lang), 0, string(data))
120}
121
122// notifyChange reads a file from disk and sends textDocument/didChange.
123func (c *Client) notifyChange(ctx context.Context, absPath string) error {
124	uri := string(protocol.URIFromPath(absPath))
125
126	data, err := os.ReadFile(absPath)
127	if err != nil {
128		return fmt.Errorf("lsp: read %s: %w", absPath, err)
129	}
130
131	c.mu.Lock()
132	v := c.versions[uri] + 1
133	c.versions[uri] = v
134	c.mu.Unlock()
135
136	change := protocol.TextDocumentContentChangeEvent{
137		Value: protocol.TextDocumentContentChangeWholeDocument{
138			Text: string(data),
139		},
140	}
141	return c.inner.NotifyDidChangeTextDocument(ctx, uri, v, []protocol.TextDocumentContentChangeEvent{change})
142}
143
144// waitForDiagnostics blocks until diagnostics arrive or timeout expires.
145func (c *Client) waitForDiagnostics(ctx context.Context, absPath string, timeout time.Duration) []protocol.Diagnostic {
146	uri := string(protocol.URIFromPath(absPath))
147	deadline := time.After(timeout)
148
149	const debounce = 150 * time.Millisecond
150	var timer *time.Timer
151
152	for {
153		select {
154		case <-c.diagChanged:
155			if timer != nil {
156				timer.Stop()
157			}
158			timer = time.NewTimer(debounce)
159		case <-timerChan(timer):
160			c.mu.Lock()
161			d := c.diags[uri]
162			c.mu.Unlock()
163			return d
164		case <-deadline:
165			c.mu.Lock()
166			d := c.diags[uri]
167			c.mu.Unlock()
168			return d
169		case <-ctx.Done():
170			c.mu.Lock()
171			d := c.diags[uri]
172			c.mu.Unlock()
173			return d
174		}
175	}
176}
177
178// close gracefully shuts down the LSP server.
179func (c *Client) close(ctx context.Context) error {
180	if err := c.inner.Shutdown(ctx); err != nil {
181		c.inner.Kill()
182		return fmt.Errorf("lsp: shutdown %s: %w", c.serverID, err)
183	}
184	return c.inner.Exit()
185}
186
187// drainDiagChan drains stale signals before waiting.
188func (c *Client) drainDiagChan() {
189	for {
190		select {
191		case <-c.diagChanged:
192		default:
193			return
194		}
195	}
196}
197
198// notifyAndWait opens (or re-notifies) the file and waits for diagnostics.
199// Uses openFile which handles both didOpen (first time) and didChange (subsequent).
200func (c *Client) notifyAndWait(ctx context.Context, absPath string, timeout time.Duration) ([]protocol.Diagnostic, error) {
201	c.drainDiagChan()
202	if err := c.openFile(ctx, absPath); err != nil {
203		return nil, err
204	}
205	return c.waitForDiagnostics(ctx, absPath, timeout), nil
206}
207
208// timerChan returns the timer's channel, or a nil channel if timer is nil.
209func timerChan(t *time.Timer) <-chan time.Time {
210	if t != nil {
211		return t.C
212	}
213	return nil
214}