forked from janpfeifer/gonb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
426 lines (389 loc) · 12.6 KB
/
conn.go
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
package goplsclient
import (
"context"
"encoding/json"
"fmt"
"log"
"net"
"strings"
"time"
jsonrpc2 "github.com/go-language-server/jsonrpc2"
lsp "github.com/go-language-server/protocol"
"github.com/go-language-server/uri"
"github.com/golang/glog"
"github.com/pkg/errors"
)
var _ = lsp.MethodInitialize
var (
ConnectTimeout = 2000 * time.Millisecond
CommunicationTimeout = 500 * time.Millisecond
)
// jsonrpc2Handler implements jsonrpc2.Handler, listening to incoming events.
type jsonrpc2Handler struct {
client *Client
}
func (c *Client) ConnClose() {
c.mu.Lock()
defer c.mu.Unlock()
c.connCloseLocked()
}
// connCloseLocked assumes Client.mu lock is acquired.
func (c *Client) connCloseLocked() {
// Wait for any pending concurrent connection attempt.
if c.conn != nil {
_ = c.conn.Close()
c.conn = nil
}
}
// minTimeout extends (or returns a new context with extended Deadline), discarding the
// previous one -- not the correct use of context, but will do for now.
func minTimeout(ctx context.Context, timeout time.Duration) context.Context {
minDeadline := time.Now().Add(timeout)
if deadline, ok := ctx.Deadline(); !ok || deadline.After(minDeadline) {
ctx, _ = context.WithDeadline(ctx, minDeadline)
}
return ctx
}
// Connect to the `gopls` in address given by `c.Address()`. It also starts
// a goroutine to monitor receiving requests.
func (c *Client) Connect(ctx context.Context) error {
ctx = minTimeout(ctx, ConnectTimeout)
c.mu.Lock()
defer c.mu.Unlock()
// Already connected ?
if c.conn != nil {
return nil
}
netMethod := "tcp"
addr := c.address
if strings.HasPrefix(addr, "/") {
netMethod = "unix"
} else if strings.HasPrefix(addr, "unix;") {
netMethod = "unix"
addr = addr[5:]
}
var err error
c.conn, err = net.DialTimeout(netMethod, addr, ConnectTimeout)
if err != nil {
c.conn = nil
return errors.Wrapf(err, "failed to connect to gopls in %q", addr)
}
jsonStream := jsonrpc2.NewStream(c.conn, c.conn)
c.jsonConn = jsonrpc2.NewConn(jsonStream)
c.jsonHandler = &jsonrpc2Handler{client: c}
c.jsonConn.AddHandler(c.jsonHandler)
go func(currentConn net.Conn) {
// Run should use a non-expiring context.
ctx := context.Background()
_ = c.jsonConn.Run(ctx)
log.Printf("- gopls connection stopped")
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == currentConn {
c.connCloseLocked()
}
}(c.conn)
err = c.jsonConn.Call(ctx, lsp.MethodInitialize, &lsp.InitializeParams{
ProcessID: 0,
RootURI: uri.File(c.dir),
// Capabilities: lsp.ClientCapabilities{},
}, &c.lspCapabilities)
if err != nil {
if closeErr := c.conn.Close(); closeErr != nil {
glog.Errorf("Failed to close connection: %+v", closeErr)
}
c.conn = nil
return errors.Wrapf(err, "failed \"initialize\" call to gopls in %q", addr)
}
err = c.jsonConn.Notify(ctx, lsp.MethodInitialized, &lsp.InitializedParams{})
if err != nil {
if closeErr := c.conn.Close(); closeErr != nil {
glog.Errorf("Failed to close connection: %+v", closeErr)
}
c.conn = nil
return errors.Wrapf(err, "failed \"initialized\" notification to gopls in %q", addr)
}
return nil
}
// NotifyDidOpenOrChange sends a notification to `gopls` with the open file, which also sends the
// file content (from `Client.fileCache` if available).
// File version sent is incremented.
func (c *Client) NotifyDidOpenOrChange(ctx context.Context, filePath string) (err error) {
if !c.WaitConnection(ctx) {
// Silently do nothing, if no connection available.
return
}
ctx = minTimeout(ctx, CommunicationTimeout)
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == nil {
return
}
return c.notifyDidOpenOrChangeLocked(ctx, filePath)
}
func (c *Client) notifyDidOpenOrChangeLocked(ctx context.Context, filePath string) (err error) {
var fileData *FileData
var fileUpdated bool
fileData, fileUpdated, err = c.FileData(filePath)
if err != nil {
return err
}
fileVersion, previouslyOpened := c.fileVersions[filePath]
if previouslyOpened && !fileUpdated {
// File already opened, and it hasn't changed, nothing to do.
return nil
}
fileVersion += 1
c.fileVersions[filePath] = fileVersion
if !previouslyOpened {
glog.V(2).Infof("goplsclient.NotifyDidOpenOrChange(ctx, %s) -- file opened", fileData.URI)
params := &lsp.DidOpenTextDocumentParams{
TextDocument: lsp.TextDocumentItem{
URI: fileData.URI,
LanguageID: "go",
Version: float64(fileVersion),
Text: fileData.Content,
}}
err = c.jsonConn.Notify(ctx, lsp.MethodTextDocumentDidOpen, params)
if err != nil {
return errors.Wrapf(err, "Failed Client.NotifyDidOpenOrChange notification for %q", filePath)
}
} else {
glog.V(2).Infof("goplsclient.NotifyDidOpenOrChange(ctx, %s) -- file changed at %s", fileData.URI, fileData.ContentTime)
version := uint64(fileVersion)
params := &lsp.DidChangeTextDocumentParams{
TextDocument: lsp.VersionedTextDocumentIdentifier{
TextDocumentIdentifier: lsp.TextDocumentIdentifier{
URI: fileData.URI,
},
Version: &version,
},
ContentChanges: []lsp.TextDocumentContentChangeEvent{
{
Text: fileData.Content,
},
},
}
err = c.jsonConn.Notify(ctx, lsp.MethodTextDocumentDidChange, params)
if err != nil {
return errors.Wrapf(err, "Failed Client.NotifyDidOpenOrChange::change notification for %q", filePath)
}
}
return
}
// CallDefinition service in `gopls`. This returns just the range of where a symbol, under
// the cursor, is defined. See `Definition()` for the full definition service.
//
// This will automatically call NotifyDidOpenOrChange, if file hasn't been sent yet.
func (c *Client) CallDefinition(ctx context.Context, filePath string, line, col int) (results []lsp.Location, err error) {
if !c.WaitConnection(ctx) {
// Silently do nothing, if no connection available.
return
}
ctx = minTimeout(ctx, CommunicationTimeout)
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == nil {
return
}
return c.callDefinitionLocked(ctx, filePath, line, col)
}
func (c *Client) callDefinitionLocked(ctx context.Context, filePath string, line, col int) (results []lsp.Location, err error) {
glog.V(2).Infof("goplsclient.CallDefinition(ctx, %s, %d, %d)", uri.File(filePath), line, col)
if _, found := c.fileVersions[filePath]; !found {
err = c.notifyDidOpenOrChangeLocked(ctx, filePath)
if err != nil {
return nil, err
}
}
params := &lsp.TextDocumentPositionParams{
TextDocument: lsp.TextDocumentIdentifier{
URI: uri.File(filePath),
},
Position: lsp.Position{
Line: float64(line),
Character: float64(col),
},
}
err = c.jsonConn.Call(ctx, lsp.MethodTextDocumentDefinition, params, &results)
if err != nil {
return nil, errors.Wrapf(err, "failed call to `gopls` \"definition_request\"")
}
for ii, r := range results {
log.Printf(" Result[%d].URI=%s\n", ii, r.URI)
}
return
}
// CallHover service in `gopls`. This returns stuff ... defined here:
// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_hover
//
// Documentation was not very clear to me, but it's what gopls uses for Definition.
//
// This will automatically call NotifyDidOpenOrChange, if file hasn't been sent yet.
func (c *Client) CallHover(ctx context.Context, filePath string, line, col int) (hover lsp.Hover, err error) {
if !c.WaitConnection(ctx) {
// Silently do nothing, if no connection available.
return
}
ctx = minTimeout(ctx, CommunicationTimeout)
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == nil {
return
}
return c.callHoverLocked(ctx, filePath, line, col)
}
func (c *Client) callHoverLocked(ctx context.Context, filePath string, line, col int) (hover lsp.Hover, err error) {
glog.V(2).Infof("goplsclient.CallHover(ctx, %s, %d, %d)", uri.File(filePath), line, col)
if _, found := c.fileVersions[filePath]; !found {
err = c.notifyDidOpenOrChangeLocked(ctx, filePath)
if err != nil {
return
}
}
params := &lsp.TextDocumentPositionParams{
TextDocument: lsp.TextDocumentIdentifier{
URI: uri.File(filePath),
},
Position: lsp.Position{
Line: float64(line),
Character: float64(col),
},
}
err = c.jsonConn.Call(ctx, lsp.MethodTextDocumentHover, params, &hover)
if err != nil {
glog.V(2).Infof("goplsclient.CallHover(ctx, %s, %d, %d): %+v", uri.File(filePath), line, col, err)
err = errors.Wrapf(err, "Failed Client.CallHover notification for %q", filePath)
return
}
return
}
func (c *Client) CallComplete(ctx context.Context, filePath string, line, col int) (items *lsp.CompletionList, err error) {
if !c.WaitConnection(ctx) {
// Silently do nothing, if no connection available.
return
}
ctx = minTimeout(ctx, CommunicationTimeout)
c.mu.Lock()
defer c.mu.Unlock()
if c.conn == nil {
return
}
return c.callCompleteLocked(ctx, filePath, line, col)
}
func (c *Client) callCompleteLocked(ctx context.Context, filePath string, line, col int) (items *lsp.CompletionList, err error) {
if _, found := c.fileVersions[filePath]; !found {
err = c.notifyDidOpenOrChangeLocked(ctx, filePath)
if err != nil {
return nil, err
}
}
params := &lsp.CompletionParams{
TextDocumentPositionParams: lsp.TextDocumentPositionParams{
TextDocument: lsp.TextDocumentIdentifier{
URI: uri.File(filePath),
},
Position: lsp.Position{
Line: float64(line),
Character: float64(col),
},
},
Context: &lsp.CompletionContext{
TriggerKind: lsp.Invoked,
},
}
items = &lsp.CompletionList{}
err = c.jsonConn.Call(ctx, lsp.MethodTextDocumentCompletion, params, items)
if err != nil {
return nil, errors.Wrapf(err, "failed call to `gopls` \"complete_request\"")
}
return
}
func (c *Client) ConsumeMessages() []string {
c.mu.Lock()
defer c.mu.Unlock()
messages := c.messages
c.messages = nil
return messages
}
func trimString(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
return s[:maxLen-1] + `…`
}
// Deliver implements jsonrpc2.Handler.
func (h *jsonrpc2Handler) Deliver(ctx context.Context, r *jsonrpc2.Request, delivered bool) bool {
_ = ctx
_ = delivered
switch r.Method {
case lsp.MethodWindowShowMessage:
var params lsp.ShowMessageParams
err := json.Unmarshal(*r.WireRequest.Params, ¶ms)
if err != nil {
log.Printf("Failed to parse ShowMessageParams: %v", err)
return true
}
h.client.messages = append(h.client.messages, params.Message)
log.Printf("gopls message: %s", trimString(params.Message, 100))
return true
case lsp.MethodWindowLogMessage:
var params lsp.LogMessageParams
err := json.Unmarshal(*r.WireRequest.Params, ¶ms)
if err != nil {
log.Printf("Failed to parse LogMessageParams: %v", err)
return true
}
h.client.messages = append(h.client.messages, params.Message)
log.Printf("gopls message: %s", trimString(params.Message, 100))
return true
case lsp.MethodTextDocumentPublishDiagnostics:
var params lsp.PublishDiagnosticsParams
err := json.Unmarshal(*r.WireRequest.Params, ¶ms)
if err != nil {
log.Printf("Failed to parse LogMessageParams: %v", err)
return true
}
h.client.messages = append(h.client.messages, fmt.Sprintf("Diagnostics:\n%+v", params))
log.Printf("gopls diagnostics: %s", trimString(fmt.Sprintf("%+v", params), 100))
return true
default:
log.Printf("gopls jsonrpc2 delivered but not handled: %q", r.Method)
}
return false
}
// Cancel implements jsonrpc2.Handler.
func (h *jsonrpc2Handler) Cancel(ctx context.Context, conn *jsonrpc2.Conn, id jsonrpc2.ID, canceled bool) bool {
_ = ctx
_ = conn
_ = canceled
log.Printf("- jsonrpc2 cancelled request id=%+v", id)
return false
}
// Request implements jsonrpc2.Handler.
func (h *jsonrpc2Handler) Request(ctx context.Context, conn *jsonrpc2.Conn, direction jsonrpc2.Direction, r *jsonrpc2.WireRequest) context.Context {
_ = conn
_ = direction
//log.Printf("- jsonrpc2 Request(direction=%s) %q", direction, r.Method)
return ctx
}
// Response implements jsonrpc2.Handler.
func (h *jsonrpc2Handler) Response(ctx context.Context, conn *jsonrpc2.Conn, direction jsonrpc2.Direction, r *jsonrpc2.WireResponse) context.Context {
_ = conn
var content string
if r.Result != nil && len(*r.Result) > 0 {
content = trimString(string(*r.Result), 100)
}
log.Printf("- jsonrpc2 Response(direction=%s) id=%+v, content=%s", direction, r.ID, content)
return ctx
}
// Done implements jsonrpc2.Handler.
func (h *jsonrpc2Handler) Done(context.Context, error) {}
// Read implements jsonrpc2.Handler.
func (h *jsonrpc2Handler) Read(ctx context.Context, _ int64) context.Context { return ctx }
// Write implements jsonrpc2.Handler.
func (h *jsonrpc2Handler) Write(ctx context.Context, _ int64) context.Context { return ctx }
// Error implements jsonrpc2.Handler.
func (h *jsonrpc2Handler) Error(ctx context.Context, err error) {
log.Printf("- jsonrpc2 Error: %+v", err)
}