Debian Codegraph @

gopls/internal/lsprpc/lsprpc.go

raw symbols SCIP
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package lsprpc implements a jsonrpc2.StreamServer that may be used to
6 // serve the LSP on a jsonrpc2 channel.
7 package lsprpc
8
9 import (
10 "context"
11 "encoding/json"
12 "fmt"
13 "log"
14 "maps"
15 "net"
16 "os"
17 "slices"
18 "strconv"
19 "strings"
20 "sync"
21 "sync/atomic"
22 "time"
23
24 "golang.org/x/tools/gopls/internal/cache"
25 "golang.org/x/tools/gopls/internal/debug"
26 "golang.org/x/tools/gopls/internal/label"
27 "golang.org/x/tools/gopls/internal/protocol"
28 "golang.org/x/tools/gopls/internal/protocol/command"
29 "golang.org/x/tools/gopls/internal/server"
30 "golang.org/x/tools/gopls/internal/settings"
31 "golang.org/x/tools/internal/event"
32 "golang.org/x/tools/internal/jsonrpc2"
33 )
34
35 // Unique identifiers for client/server.
36 var serverIndex int64
37
38 // The streamServer type is a jsonrpc2.streamServer that handles incoming
39 // streams as a new LSP session, using a shared cache.
40 type StreamServer struct {
41 cache *cache.Cache
42 // daemon controls whether or not to log new connections.
43 daemon bool
44
45 // optionsOverrides is passed to newly created sessions.
46 optionsOverrides func(*settings.Options)
47
48 // onSessionExit is called whenever a session exits, with the session ID.
49 onSessionExit func(id string)
50
51 // serverForTest may be set to a test fake for testing.
52 serverForTest protocol.Server
53
54 // Keep track of active sessions, for interrogation.
55 sessionMu sync.Mutex
56 sessions map[string]sessionServer
57 }
58
59 type sessionServer struct {
60 session *cache.Session
61 server protocol.Server
62 }
63
64 // NewStreamServer creates a StreamServer using the shared cache. If
65 // withTelemetry is true, each session is instrumented with telemetry that
66 // records RPC statistics.
67 func NewStreamServer(cache *cache.Cache, daemon bool, optionsFunc func(*settings.Options)) *StreamServer {
68 return &StreamServer{
69 cache: cache,
70 daemon: daemon,
71 optionsOverrides: optionsFunc,
72 sessions: make(map[string]sessionServer),
73 }
74 }
75
76 // SetSessionExitFunc sets the function to call when sessions exit.
77 // It is not concurrency safe, and must only be called at most once, before the
78 // receiver is passed to jsonrpc2.Serve.
79 func (s *StreamServer) SetSessionExitFunc(f func(id string)) {
80 if s.onSessionExit != nil {
81 panic("duplicate call to SetSessionExitFunc")
82 }
83 s.onSessionExit = f
84 }
85
86 // ServeStream implements the jsonrpc2.StreamServer interface, by handling
87 // incoming streams using a new lsp server.
88 func (s *StreamServer) ServeStream(ctx context.Context, conn jsonrpc2.Conn) error {
89 client := protocol.ClientDispatcher(conn)
90 session := cache.NewSession(ctx, s.cache)
91 svr := s.serverForTest
92 if svr == nil {
93 options := settings.DefaultOptions(s.optionsOverrides)
94 svr = server.New(session, client, options)
95 if instance := debug.GetInstance(ctx); instance != nil {
96 instance.AddService(svr, session)
97 }
98 }
99 s.sessionMu.Lock()
100 s.sessions[session.ID()] = sessionServer{session, svr}
101 s.sessionMu.Unlock()
102 defer func() {
103 s.sessionMu.Lock()
104 delete(s.sessions, session.ID())
105 s.sessionMu.Unlock()
106 if s.onSessionExit != nil {
107 s.onSessionExit(session.ID())
108 }
109 }()
110
111 // Clients may or may not send a shutdown message. Make sure the server is
112 // shut down.
113 // TODO(rFindley): this shutdown should perhaps be on a disconnected context.
114 defer func() {
115 if err := svr.Shutdown(ctx); err != nil {
116 event.Error(ctx, "error shutting down", err)
117 }
118 }()
119 executable, err := os.Executable()
120 if err != nil {
121 log.Printf("error getting gopls path: %v", err)
122 executable = ""
123 }
124 ctx = protocol.WithClient(ctx, client)
125 conn.Go(ctx,
126 protocol.Handlers(
127 handshaker(session, executable, s.daemon,
128 protocol.ServerHandler(svr,
129 jsonrpc2.MethodNotFound))))
130
131 if s.daemon {
132 log.Printf("Session %s: connected", session.ID())
133 defer log.Printf("Session %s: exited", session.ID())
134 }
135
136 <-conn.Done()
137 return conn.Err()
138 }
139
140 // Session returns the current active session for the given id, or (nil, nil)
141 // if none exists.
142 func (s *StreamServer) Session(id string) (*cache.Session, protocol.Server) {
143 s.sessionMu.Lock()
144 defer s.sessionMu.Unlock()
145 ss := s.sessions[id]
146 return ss.session, ss.server // possibly nil for zero value
147 }
148
149 // FirstSession returns the first session by lexically sorted session ID, or
150 // (nil, nil).
151 func (s *StreamServer) FirstSession() (*cache.Session, protocol.Server) {
152 s.sessionMu.Lock()
153 defer s.sessionMu.Unlock()
154 keys := slices.Collect(maps.Keys(s.sessions))
155 if len(keys) == 0 {
156 return nil, nil
157 }
158 id := slices.Min(keys)
159 ss := s.sessions[id]
160 return ss.session, ss.server
161 }
162
163 // A forwarder is a jsonrpc2.StreamServer that handles an LSP stream by
164 // forwarding it to a remote. This is used when the gopls process started by
165 // the editor is in the `-remote` mode, which means it finds and connects to a
166 // separate gopls daemon. In these cases, we still want the forwarder gopls to
167 // be instrumented with telemetry, and want to be able to in some cases hijack
168 // the jsonrpc2 connection with the daemon.
169 type forwarder struct {
170 dialer *autoDialer
171
172 mu sync.Mutex
173 // Hold on to the server connection so that we can redo the handshake if any
174 // information changes.
175 serverConn jsonrpc2.Conn
176 serverID string
177 }
178
179 // NewForwarder creates a new forwarder (a [jsonrpc2.StreamServer]),
180 // ready to forward connections to the
181 // remote server specified by rawAddr. If provided and rawAddr indicates an
182 // 'automatic' address (starting with 'auto;'), argFunc may be used to start a
183 // remote server for the auto-discovered address.
184 func NewForwarder(rawAddr string, argFunc func(network, address string) []string) (jsonrpc2.StreamServer, error) {
185 dialer, err := newAutoDialer(rawAddr, argFunc)
186 if err != nil {
187 return nil, err
188 }
189 fwd := &forwarder{
190 dialer: dialer,
191 }
192 return fwd, nil
193 }
194
195 // QueryServerState returns a JSON-encodable struct describing the state of the named server.
196 func QueryServerState(ctx context.Context, addr string) (any, error) {
197 serverConn, err := dialRemote(ctx, addr)
198 if err != nil {
199 return nil, err
200 }
201 var state serverState
202 if err := protocol.Call(ctx, serverConn, sessionsMethod, nil, &state); err != nil {
203 return nil, fmt.Errorf("querying server state: %w", err)
204 }
205 return &state, nil
206 }
207
208 // dialRemote is used for making calls into the gopls daemon. addr should be a
209 // URL, possibly on the synthetic 'auto' network (e.g. tcp://..., unix://...,
210 // or auto://...).
211 func dialRemote(ctx context.Context, addr string) (jsonrpc2.Conn, error) {
212 network, address := ParseAddr(addr)
213 if network == autoNetwork {
214 gp, err := os.Executable()
215 if err != nil {
216 return nil, fmt.Errorf("getting gopls path: %w", err)
217 }
218 network, address = autoNetworkAddress(gp, address)
219 }
220 netConn, err := net.DialTimeout(network, address, 5*time.Second)
221 if err != nil {
222 return nil, fmt.Errorf("dialing remote: %w", err)
223 }
224 serverConn := jsonrpc2.NewConn(jsonrpc2.NewHeaderStream(netConn))
225 serverConn.Go(ctx, jsonrpc2.MethodNotFound)
226 return serverConn, nil
227 }
228
229 // ExecuteCommand connects to the named server, sends it a
230 // workspace/executeCommand request (with command 'id' and arguments
231 // JSON encoded in 'request'), and populates the result variable.
232 func ExecuteCommand(ctx context.Context, addr string, id string, request, result any) error {
233 serverConn, err := dialRemote(ctx, addr)
234 if err != nil {
235 return err
236 }
237 args, err := command.MarshalArgs(request)
238 if err != nil {
239 return err
240 }
241 params := protocol.ExecuteCommandParams{
242 Command: id,
243 Arguments: args,
244 }
245 return protocol.Call(ctx, serverConn, "workspace/executeCommand", params, result)
246 }
247
248 // ServeStream dials the forwarder remote and binds the remote to serve the LSP
249 // on the incoming stream.
250 func (f *forwarder) ServeStream(ctx context.Context, clientConn jsonrpc2.Conn) error {
251 client := protocol.ClientDispatcher(clientConn)
252
253 netConn, err := f.dialer.dialNet(ctx)
254 if err != nil {
255 return fmt.Errorf("forwarder: connecting to remote: %w", err)
256 }
257 serverConn := jsonrpc2.NewConn(jsonrpc2.NewHeaderStream(netConn))
258 server := protocol.ServerDispatcher(serverConn)
259
260 // Forward between connections.
261 serverConn.Go(ctx,
262 protocol.Handlers(
263 protocol.ClientHandler(client,
264 jsonrpc2.MethodNotFound)))
265
266 // Don't run the clientConn yet, so that we can complete the handshake before
267 // processing any client messages.
268
269 // Do a handshake with the server instance to exchange debug information.
270 index := atomic.AddInt64(&serverIndex, 1)
271 f.mu.Lock()
272 f.serverConn = serverConn
273 f.serverID = strconv.FormatInt(index, 10)
274 f.mu.Unlock()
275 f.handshake(ctx)
276 clientConn.Go(ctx,
277 protocol.Handlers(
278 f.handler(
279 protocol.ServerHandler(server,
280 jsonrpc2.MethodNotFound))))
281
282 select {
283 case <-serverConn.Done():
284 clientConn.Close() // ignore error
285 case <-clientConn.Done():
286 serverConn.Close() // ignore error
287 }
288
289 err = nil
290 if serverConn.Err() != nil {
291 err = fmt.Errorf("remote disconnected: %v", serverConn.Err())
292 } else if clientConn.Err() != nil {
293 err = fmt.Errorf("client disconnected: %v", clientConn.Err())
294 }
295 event.Log(ctx, fmt.Sprintf("forwarder: exited with error: %v", err))
296 return err
297 }
298
299 // TODO(rfindley): remove this handshaking in favor of middleware.
300 func (f *forwarder) handshake(ctx context.Context) {
301 // This call to os.Executable is redundant, and will be eliminated by the
302 // transition to the V2 API.
303 goplsPath, err := os.Executable()
304 if err != nil {
305 event.Error(ctx, "getting executable for handshake", err)
306 goplsPath = ""
307 }
308 var (
309 hreq = handshakeRequest{
310 ServerID: f.serverID,
311 GoplsPath: goplsPath,
312 }
313 hresp handshakeResponse
314 )
315 if di := debug.GetInstance(ctx); di != nil {
316 hreq.Logfile = di.Logfile
317 hreq.DebugAddr = di.ListenedDebugAddress()
318 }
319 if err := protocol.Call(ctx, f.serverConn, handshakeMethod, hreq, &hresp); err != nil {
320 // TODO(rfindley): at some point in the future we should return an error
321 // here. Handshakes have become functional in nature.
322 event.Error(ctx, "forwarder: gopls handshake failed", err)
323 }
324 if hresp.GoplsPath != goplsPath {
325 event.Error(ctx, "", fmt.Errorf("forwarder: gopls path mismatch: forwarder is %q, remote is %q", goplsPath, hresp.GoplsPath))
326 }
327 event.Log(ctx, "New server",
328 label.NewServer.Of(f.serverID),
329 label.Logfile.Of(hresp.Logfile),
330 label.DebugAddress.Of(hresp.DebugAddr),
331 label.GoplsPath.Of(hresp.GoplsPath),
332 label.ClientID.Of(hresp.SessionID),
333 )
334 }
335
336 func ConnectToRemote(ctx context.Context, addr string) (net.Conn, error) {
337 dialer, err := newAutoDialer(addr, nil)
338 if err != nil {
339 return nil, err
340 }
341 return dialer.dialNet(ctx)
342 }
343
344 // handler intercepts messages to the daemon to enrich them with local
345 // information.
346 func (f *forwarder) handler(handler jsonrpc2.Handler) jsonrpc2.Handler {
347 return func(ctx context.Context, reply jsonrpc2.Replier, r jsonrpc2.Request) error {
348 // Intercept certain messages to add special handling.
349 switch r.Method() {
350 case "initialize":
351 if newr, err := addGoEnvToInitializeRequest(ctx, r); err == nil {
352 r = newr
353 } else {
354 log.Printf("unable to add local env to initialize request: %v", err)
355 }
356 case "workspace/executeCommand":
357 var params protocol.ExecuteCommandParams
358 if err := json.Unmarshal(r.Params(), &params); err == nil {
359 if params.Command == command.StartDebugging.String() {
360 var args command.DebuggingArgs
361 if err := command.UnmarshalArgs(params.Arguments, &args); err == nil {
362 reply = f.replyWithDebugAddress(ctx, reply, args)
363 } else {
364 event.Error(ctx, "unmarshaling debugging args", err)
365 }
366 }
367 } else {
368 event.Error(ctx, "intercepting executeCommand request", err)
369 }
370 }
371 // The gopls workspace environment defaults to the process environment in
372 // which gopls daemon was started. To avoid discrepancies in Go environment
373 // between the editor and daemon, inject any unset variables in `go env`
374 // into the options sent by initialize.
375 //
376 // See also golang.org/issue/37830.
377 return handler(ctx, reply, r)
378 }
379 }
380
381 // addGoEnvToInitializeRequest builds a new initialize request in which we set
382 // any environment variables output by `go env` and not already present in the
383 // request.
384 //
385 // It returns an error if r is not an initialize request, or is otherwise
386 // malformed.
387 func addGoEnvToInitializeRequest(ctx context.Context, r jsonrpc2.Request) (jsonrpc2.Request, error) {
388 var params protocol.ParamInitialize
389 if err := json.Unmarshal(r.Params(), &params); err != nil {
390 return nil, err
391 }
392 var opts map[string]any
393 switch v := params.InitializationOptions.(type) {
394 case nil:
395 opts = make(map[string]any)
396 case map[string]any:
397 opts = v
398 default:
399 return nil, fmt.Errorf("unexpected type for InitializationOptions: %T", v)
400 }
401 envOpt, ok := opts["env"]
402 if !ok {
403 envOpt = make(map[string]any)
404 }
405 env, ok := envOpt.(map[string]any)
406 if !ok {
407 return nil, fmt.Errorf(`env option is %T, expected a map`, envOpt)
408 }
409 goenv, err := getGoEnv(ctx, env)
410 if err != nil {
411 return nil, err
412 }
413 // We don't want to propagate GOWORK unless explicitly set since that could mess with
414 // path inference during cmd/go invocations, see golang/go#51825.
415 _, goworkSet := os.LookupEnv("GOWORK")
416 for govar, value := range goenv {
417 if govar == "GOWORK" && !goworkSet {
418 continue
419 }
420 env[govar] = value
421 }
422 opts["env"] = env
423 params.InitializationOptions = opts
424 call, ok := r.(*jsonrpc2.Call)
425 if !ok {
426 return nil, fmt.Errorf("%T is not a *jsonrpc2.Call", r)
427 }
428 return jsonrpc2.NewCall(call.ID(), "initialize", params)
429 }
430
431 func (f *forwarder) replyWithDebugAddress(outerCtx context.Context, r jsonrpc2.Replier, args command.DebuggingArgs) jsonrpc2.Replier {
432 di := debug.GetInstance(outerCtx)
433 if di == nil {
434 event.Log(outerCtx, "no debug instance to start")
435 return r
436 }
437 return func(ctx context.Context, result any, outerErr error) error {
438 if outerErr != nil {
439 return r(ctx, result, outerErr)
440 }
441 // Enrich the result with our own debugging information. Since we're an
442 // intermediary, the jsonrpc2 package has deserialized the result into
443 // maps, by default. Re-do the unmarshalling.
444 raw, err := json.Marshal(result)
445 if err != nil {
446 event.Error(outerCtx, "marshaling intermediate command result", err)
447 return r(ctx, result, err)
448 }
449 var modified command.DebuggingResult
450 if err := json.Unmarshal(raw, &modified); err != nil {
451 event.Error(outerCtx, "unmarshaling intermediate command result", err)
452 return r(ctx, result, err)
453 }
454 addr := args.Addr
455 if addr == "" {
456 addr = "localhost:0"
457 }
458 addr, err = di.Serve(outerCtx, addr)
459 if err != nil {
460 event.Error(outerCtx, "starting debug server", err)
461 return r(ctx, result, err)
462 }
463 urls := []string{"http://" + addr}
464 modified.URLs = append(urls, modified.URLs...)
465 go f.handshake(ctx)
466 return r(ctx, modified, nil)
467 }
468 }
469
470 // A handshakeRequest identifies a client to the LSP server.
471 type handshakeRequest struct {
472 // ServerID is the ID of the server on the client. This should usually be 0.
473 ServerID string `json:"serverID"`
474 // Logfile is the location of the clients log file.
475 Logfile string `json:"logfile"`
476 // DebugAddr is the client debug address.
477 DebugAddr string `json:"debugAddr"`
478 // GoplsPath is the path to the Gopls binary running the current client
479 // process.
480 GoplsPath string `json:"goplsPath"`
481 }
482
483 // A handshakeResponse is returned by the LSP server to tell the LSP client
484 // information about its session.
485 type handshakeResponse struct {
486 // SessionID is the server session associated with the client.
487 SessionID string `json:"sessionID"`
488 // Logfile is the location of the server logs.
489 Logfile string `json:"logfile"`
490 // DebugAddr is the server debug address.
491 DebugAddr string `json:"debugAddr"`
492 // GoplsPath is the path to the Gopls binary running the current server
493 // process.
494 GoplsPath string `json:"goplsPath"`
495 }
496
497 // clientSession identifies a current client LSP session on the server. Note
498 // that it looks similar to handshakeResponse, but in fact 'Logfile' and
499 // 'DebugAddr' now refer to the client.
500 type clientSession struct {
501 SessionID string `json:"sessionID"`
502 Logfile string `json:"logfile"`
503 DebugAddr string `json:"debugAddr"`
504 }
505
506 // serverState holds information about the gopls daemon process, including its
507 // debug information and debug information of all of its current connected
508 // clients.
509 type serverState struct {
510 Logfile string `json:"logfile"`
511 DebugAddr string `json:"debugAddr"`
512 GoplsPath string `json:"goplsPath"`
513 CurrentClientID string `json:"currentClientID"`
514 Clients []clientSession `json:"clients"`
515 }
516
517 const (
518 handshakeMethod = "gopls/handshake"
519 sessionsMethod = "gopls/sessions"
520 )
521
522 func handshaker(session *cache.Session, goplsPath string, logHandshakes bool, handler jsonrpc2.Handler) jsonrpc2.Handler {
523 return func(ctx context.Context, reply jsonrpc2.Replier, r jsonrpc2.Request) error {
524 switch r.Method() {
525 case handshakeMethod:
526 // We log.Printf in this handler, rather than event.Log when we want logs
527 // to go to the daemon log rather than being reflected back to the
528 // client.
529 var req handshakeRequest
530 if err := json.Unmarshal(r.Params(), &req); err != nil {
531 if logHandshakes {
532 log.Printf("Error processing handshake for session %s: %v", session.ID(), err)
533 }
534 sendError(ctx, reply, err)
535 return nil
536 }
537 if logHandshakes {
538 log.Printf("Session %s: got handshake. Logfile: %q, Debug addr: %q", session.ID(), req.Logfile, req.DebugAddr)
539 }
540 event.Log(ctx, "Handshake session update",
541 cache.KeyUpdateSession.Of(session),
542 label.DebugAddress.Of(req.DebugAddr),
543 label.Logfile.Of(req.Logfile),
544 label.ServerID.Of(req.ServerID),
545 label.GoplsPath.Of(req.GoplsPath),
546 )
547 resp := handshakeResponse{
548 SessionID: session.ID(),
549 GoplsPath: goplsPath,
550 }
551 if di := debug.GetInstance(ctx); di != nil {
552 resp.Logfile = di.Logfile
553 resp.DebugAddr = di.ListenedDebugAddress()
554 }
555 return reply(ctx, resp, nil)
556
557 case sessionsMethod:
558 resp := serverState{
559 GoplsPath: goplsPath,
560 CurrentClientID: session.ID(),
561 }
562 if di := debug.GetInstance(ctx); di != nil {
563 resp.Logfile = di.Logfile
564 resp.DebugAddr = di.ListenedDebugAddress()
565 for _, c := range di.State.Clients() {
566 resp.Clients = append(resp.Clients, clientSession{
567 SessionID: c.Session.ID(),
568 Logfile: c.Logfile,
569 DebugAddr: c.DebugAddress,
570 })
571 }
572 }
573 return reply(ctx, resp, nil)
574 }
575 return handler(ctx, reply, r)
576 }
577 }
578
579 func sendError(ctx context.Context, reply jsonrpc2.Replier, err error) {
580 err = fmt.Errorf("%v: %w", err, jsonrpc2.ErrParse)
581 if err := reply(ctx, nil, err); err != nil {
582 event.Error(ctx, "", err)
583 }
584 }
585
586 // ParseAddr parses the address of a gopls remote (e.g. "tcp;localhost:12345").
587 // TODO(rFindley): further document this syntax, and allow URI-style remote
588 // addresses such as "auto://...".
589 func ParseAddr(listen string) (network string, address string) {
590 // Allow passing just -remote=auto, as a shorthand for using automatic remote
591 // resolution.
592 if listen == autoNetwork {
593 return autoNetwork, ""
594 }
595 if network, address, ok := strings.Cut(listen, ";"); ok {
596 return network, address
597 }
598 return "tcp", listen
599 }