1
0
mirror of https://github.com/golang/go synced 2024-10-01 07:28:35 -06:00
go/internal/lsp/cmd/serve.go

115 lines
4.1 KiB
Go
Raw Normal View History

// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"context"
"flag"
"fmt"
"os"
"strings"
"time"
"golang.org/x/tools/internal/jsonrpc2"
"golang.org/x/tools/internal/lsp/cache"
"golang.org/x/tools/internal/lsp/debug"
internal/lsp: refactor LSP server instantiation Previously, the process of instantiating and running the LSP server was sharded across the lsp, protocol, and cmd packages, and this resulted in some APIs that are hard to work with. For example, it's hard to guess the difference between lsp.NewClientServer, lsp.NewServer, protocol.NewServer (which returns a client), and protocol.NewClient (which returns a server). This change reorganizes Server instantiation as follows: + The lsp.Server is now purely an implementation of the protocol.Server interface. It is no longer responsible for installing itself into the jsonrpc2 Stream, nor for running itself. + A new package 'lsprpc' is added, to implement the logic of binding an incoming connection to an LSP server session. This is put in a separate package for lack of a clear home: it didn't really philosophically belong in any of the lsp, cmd, or protocol packages. We can perhaps move it to cmd in the future, but I'd like to keep it as a separate package while I develop request forwarding. simplified import graph: jsonrpc2 ⭠ lsprpc ⭠ cmd ⭩ ⭦ lsp (t.b.d. client tests) ⭩ ⭨ protocol source + The jsonrpc2 package is extended to have a minimal API for running a 'StreamServer': something analogous to an HTTP server that listens for new connections and delegates to a handler (but we couldn't use the word 'Handler' for this delegate as it was already taken). After these changes, I hope that the concerns of "serving the LSP", "serving jsonrpc2", and "installing the LSP on jsonrpc2" are more logically organized, though one legitimate criticism is that the word 'Server' is still heavily overloaded. This change prepares a subsequent change which hijacks the jsonrpc2 connection when forwarding messages to a shared gopls instance. To test this change, the following improvements are made: + A servertest package is added to make it easier to run a test against an in-process jsonrpc2 server. For now, this uses TCP but it could easily be modified to use io.Pipe. + cmd tests are updated to use the servertest package. Unfortunately it wasn't yet possible to eliminate the concept of `remote=internal` in favor of just using multiple sessions, because view initialization involves calling both `go env` and `packages.Load`, which slow down session startup significantly. See also golang.org/issue/35968. Instead, the syntax for `-remote=internal` is modified to be `-remote=internal@127.0.0.1:12345`. + An additional test for request cancellation is added for the sessionserver package. This test uncovered a bug: when calling Canceller.Cancel, we were using id rather than &id, which resulted in incorrect json serialization (as only the pointer receiver implements the json.Marshaller interface). Updates golang/go#34111 Change-Id: I75c219df634348cdf53a9e57839b98588311a9ef Reviewed-on: https://go-review.googlesource.com/c/tools/+/215742 Run-TryBot: Robert Findley <rfindley@google.com> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Rebecca Stambler <rstambler@golang.org> Reviewed-by: Heschi Kreinick <heschi@google.com>
2020-01-21 17:34:50 -07:00
"golang.org/x/tools/internal/lsp/lsprpc"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/tool"
)
// Serve is a struct that exposes the configurable parts of the LSP server as
// flags, in the right form for tool.Main to consume.
type Serve struct {
Logfile string `flag:"logfile" help:"filename to log to. if value is \"auto\", then logging to a default output file is enabled"`
Mode string `flag:"mode" help:"no effect"`
Port int `flag:"port" help:"port on which to run gopls for debugging purposes"`
Address string `flag:"listen" help:"address on which to listen for remote connections. If prefixed by 'unix;', the subsequent address is assumed to be a unix domain socket. Otherwise, TCP is used."`
IdleTimeout time.Duration `flag:"listen.timeout" help:"when used with -listen, shut down the server when there are no connected clients for this duration"`
Trace bool `flag:"rpc.trace" help:"print the full rpc trace in lsp inspector format"`
Debug string `flag:"debug" help:"serve debug information on the supplied address"`
internal/lsp/lsprpc: expose configuration for auto-started daemon Three new flags are added to the serve command, and threaded through to the LSP forwarder: -remote.listen.timeout: -listen.timeout for the auto-started daemon -remote.debug: -debug for the auto-started daemon -remote.logfile: -logfile for the auto-started daemon As part of this change, no longer enable debugging the daemon by default. Notably none of this configuration affects serving, so modifying this configuration has been chosen not to change the path to the automatic daemon. In other words, this configuration has effect only for the forwarder process that starts the daemon: all others will connect to the daemon and inherit whatever configuration it had at startup. This should be OK, because in the common case this configuration should be static across all clients (e.g., many Vim sessions all sharing the same .vimrc). Exposing this configuration made the signature of lsprpc.NewForwarder a bit hard to understand, so I decided to go ahead and switch to a variadic options pattern for initializing both the Forwarder and StreamServer, the latter just for consistency with the Forwarder. Updates golang/go#34111 Change-Id: Iefb71e337befe08b23e451477d19fd57e69f36c6 Reviewed-on: https://go-review.googlesource.com/c/tools/+/222670 Run-TryBot: Robert Findley <rfindley@google.com> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Rebecca Stambler <rstambler@golang.org> Reviewed-by: Heschi Kreinick <heschi@google.com>
2020-03-09 11:22:56 -06:00
RemoteListenTimeout time.Duration `flag:"remote.listen.timeout" help:"when used with -remote=auto, the listen.timeout used when auto-starting the remote"`
RemoteDebug string `flag:"remote.debug" help:"when used with -remote=auto, the debug address used when auto-starting the remote"`
RemoteLogfile string `flag:"remote.logfile" help:"when used with -remote=auto, the filename for the remote daemon to log to"`
app *Application
}
func (s *Serve) Name() string { return "serve" }
func (s *Serve) Usage() string { return "" }
func (s *Serve) ShortHelp() string {
return "run a server for Go code using the Language Server Protocol"
}
func (s *Serve) DetailedHelp(f *flag.FlagSet) {
fmt.Fprint(f.Output(), `
The server communicates using JSONRPC2 on stdin and stdout, and is intended to be run directly as
a child of an editor process.
gopls server flags are:
`)
f.PrintDefaults()
}
// Run configures a server based on the flags, and then runs it.
// It blocks until the server shuts down.
func (s *Serve) Run(ctx context.Context, args ...string) error {
if len(args) > 0 {
return tool.CommandLineErrorf("server does not take arguments, got %v", args)
}
di := debug.GetInstance(ctx)
if di != nil {
closeLog, err := di.SetLogFile(s.Logfile)
if err != nil {
return err
}
defer closeLog()
di.ServerAddress = s.Address
di.DebugAddress = s.Debug
di.Serve(ctx)
di.MonitorMemory(ctx)
}
var ss jsonrpc2.StreamServer
if s.app.Remote != "" {
network, addr := parseAddr(s.app.Remote)
internal/lsp/lsprpc: expose configuration for auto-started daemon Three new flags are added to the serve command, and threaded through to the LSP forwarder: -remote.listen.timeout: -listen.timeout for the auto-started daemon -remote.debug: -debug for the auto-started daemon -remote.logfile: -logfile for the auto-started daemon As part of this change, no longer enable debugging the daemon by default. Notably none of this configuration affects serving, so modifying this configuration has been chosen not to change the path to the automatic daemon. In other words, this configuration has effect only for the forwarder process that starts the daemon: all others will connect to the daemon and inherit whatever configuration it had at startup. This should be OK, because in the common case this configuration should be static across all clients (e.g., many Vim sessions all sharing the same .vimrc). Exposing this configuration made the signature of lsprpc.NewForwarder a bit hard to understand, so I decided to go ahead and switch to a variadic options pattern for initializing both the Forwarder and StreamServer, the latter just for consistency with the Forwarder. Updates golang/go#34111 Change-Id: Iefb71e337befe08b23e451477d19fd57e69f36c6 Reviewed-on: https://go-review.googlesource.com/c/tools/+/222670 Run-TryBot: Robert Findley <rfindley@google.com> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Rebecca Stambler <rstambler@golang.org> Reviewed-by: Heschi Kreinick <heschi@google.com>
2020-03-09 11:22:56 -06:00
ss = lsprpc.NewForwarder(network, addr,
lsprpc.WithTelemetry(true),
lsprpc.RemoteDebugAddress(s.RemoteDebug),
lsprpc.RemoteListenTimeout(s.RemoteListenTimeout),
lsprpc.RemoteLogfile(s.RemoteLogfile),
)
} else {
internal/lsp/lsprpc: expose configuration for auto-started daemon Three new flags are added to the serve command, and threaded through to the LSP forwarder: -remote.listen.timeout: -listen.timeout for the auto-started daemon -remote.debug: -debug for the auto-started daemon -remote.logfile: -logfile for the auto-started daemon As part of this change, no longer enable debugging the daemon by default. Notably none of this configuration affects serving, so modifying this configuration has been chosen not to change the path to the automatic daemon. In other words, this configuration has effect only for the forwarder process that starts the daemon: all others will connect to the daemon and inherit whatever configuration it had at startup. This should be OK, because in the common case this configuration should be static across all clients (e.g., many Vim sessions all sharing the same .vimrc). Exposing this configuration made the signature of lsprpc.NewForwarder a bit hard to understand, so I decided to go ahead and switch to a variadic options pattern for initializing both the Forwarder and StreamServer, the latter just for consistency with the Forwarder. Updates golang/go#34111 Change-Id: Iefb71e337befe08b23e451477d19fd57e69f36c6 Reviewed-on: https://go-review.googlesource.com/c/tools/+/222670 Run-TryBot: Robert Findley <rfindley@google.com> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Rebecca Stambler <rstambler@golang.org> Reviewed-by: Heschi Kreinick <heschi@google.com>
2020-03-09 11:22:56 -06:00
ss = lsprpc.NewStreamServer(cache.New(ctx, s.app.options), lsprpc.WithTelemetry(true))
}
if s.Address != "" {
network, addr := parseAddr(s.Address)
return jsonrpc2.ListenAndServe(ctx, network, addr, ss, s.IdleTimeout)
}
if s.Port != 0 {
internal/lsp: refactor LSP server instantiation Previously, the process of instantiating and running the LSP server was sharded across the lsp, protocol, and cmd packages, and this resulted in some APIs that are hard to work with. For example, it's hard to guess the difference between lsp.NewClientServer, lsp.NewServer, protocol.NewServer (which returns a client), and protocol.NewClient (which returns a server). This change reorganizes Server instantiation as follows: + The lsp.Server is now purely an implementation of the protocol.Server interface. It is no longer responsible for installing itself into the jsonrpc2 Stream, nor for running itself. + A new package 'lsprpc' is added, to implement the logic of binding an incoming connection to an LSP server session. This is put in a separate package for lack of a clear home: it didn't really philosophically belong in any of the lsp, cmd, or protocol packages. We can perhaps move it to cmd in the future, but I'd like to keep it as a separate package while I develop request forwarding. simplified import graph: jsonrpc2 ⭠ lsprpc ⭠ cmd ⭩ ⭦ lsp (t.b.d. client tests) ⭩ ⭨ protocol source + The jsonrpc2 package is extended to have a minimal API for running a 'StreamServer': something analogous to an HTTP server that listens for new connections and delegates to a handler (but we couldn't use the word 'Handler' for this delegate as it was already taken). After these changes, I hope that the concerns of "serving the LSP", "serving jsonrpc2", and "installing the LSP on jsonrpc2" are more logically organized, though one legitimate criticism is that the word 'Server' is still heavily overloaded. This change prepares a subsequent change which hijacks the jsonrpc2 connection when forwarding messages to a shared gopls instance. To test this change, the following improvements are made: + A servertest package is added to make it easier to run a test against an in-process jsonrpc2 server. For now, this uses TCP but it could easily be modified to use io.Pipe. + cmd tests are updated to use the servertest package. Unfortunately it wasn't yet possible to eliminate the concept of `remote=internal` in favor of just using multiple sessions, because view initialization involves calling both `go env` and `packages.Load`, which slow down session startup significantly. See also golang.org/issue/35968. Instead, the syntax for `-remote=internal` is modified to be `-remote=internal@127.0.0.1:12345`. + An additional test for request cancellation is added for the sessionserver package. This test uncovered a bug: when calling Canceller.Cancel, we were using id rather than &id, which resulted in incorrect json serialization (as only the pointer receiver implements the json.Marshaller interface). Updates golang/go#34111 Change-Id: I75c219df634348cdf53a9e57839b98588311a9ef Reviewed-on: https://go-review.googlesource.com/c/tools/+/215742 Run-TryBot: Robert Findley <rfindley@google.com> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Rebecca Stambler <rstambler@golang.org> Reviewed-by: Heschi Kreinick <heschi@google.com>
2020-01-21 17:34:50 -07:00
addr := fmt.Sprintf(":%v", s.Port)
return jsonrpc2.ListenAndServe(ctx, "tcp", addr, ss, s.IdleTimeout)
}
stream := jsonrpc2.NewHeaderStream(os.Stdin, os.Stdout)
if s.Trace && di != nil {
stream = protocol.LoggingStream(stream, di.LogWriter)
}
internal/lsp: refactor LSP server instantiation Previously, the process of instantiating and running the LSP server was sharded across the lsp, protocol, and cmd packages, and this resulted in some APIs that are hard to work with. For example, it's hard to guess the difference between lsp.NewClientServer, lsp.NewServer, protocol.NewServer (which returns a client), and protocol.NewClient (which returns a server). This change reorganizes Server instantiation as follows: + The lsp.Server is now purely an implementation of the protocol.Server interface. It is no longer responsible for installing itself into the jsonrpc2 Stream, nor for running itself. + A new package 'lsprpc' is added, to implement the logic of binding an incoming connection to an LSP server session. This is put in a separate package for lack of a clear home: it didn't really philosophically belong in any of the lsp, cmd, or protocol packages. We can perhaps move it to cmd in the future, but I'd like to keep it as a separate package while I develop request forwarding. simplified import graph: jsonrpc2 ⭠ lsprpc ⭠ cmd ⭩ ⭦ lsp (t.b.d. client tests) ⭩ ⭨ protocol source + The jsonrpc2 package is extended to have a minimal API for running a 'StreamServer': something analogous to an HTTP server that listens for new connections and delegates to a handler (but we couldn't use the word 'Handler' for this delegate as it was already taken). After these changes, I hope that the concerns of "serving the LSP", "serving jsonrpc2", and "installing the LSP on jsonrpc2" are more logically organized, though one legitimate criticism is that the word 'Server' is still heavily overloaded. This change prepares a subsequent change which hijacks the jsonrpc2 connection when forwarding messages to a shared gopls instance. To test this change, the following improvements are made: + A servertest package is added to make it easier to run a test against an in-process jsonrpc2 server. For now, this uses TCP but it could easily be modified to use io.Pipe. + cmd tests are updated to use the servertest package. Unfortunately it wasn't yet possible to eliminate the concept of `remote=internal` in favor of just using multiple sessions, because view initialization involves calling both `go env` and `packages.Load`, which slow down session startup significantly. See also golang.org/issue/35968. Instead, the syntax for `-remote=internal` is modified to be `-remote=internal@127.0.0.1:12345`. + An additional test for request cancellation is added for the sessionserver package. This test uncovered a bug: when calling Canceller.Cancel, we were using id rather than &id, which resulted in incorrect json serialization (as only the pointer receiver implements the json.Marshaller interface). Updates golang/go#34111 Change-Id: I75c219df634348cdf53a9e57839b98588311a9ef Reviewed-on: https://go-review.googlesource.com/c/tools/+/215742 Run-TryBot: Robert Findley <rfindley@google.com> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Rebecca Stambler <rstambler@golang.org> Reviewed-by: Heschi Kreinick <heschi@google.com>
2020-01-21 17:34:50 -07:00
return ss.ServeStream(ctx, stream)
}
// parseAddr parses the -listen flag in to a network, and address.
func parseAddr(listen string) (network string, address string) {
// Allow passing just -remote=auto, as a shorthand for using automatic remote
// resolution.
if listen == lsprpc.AutoNetwork {
return lsprpc.AutoNetwork, ""
}
if parts := strings.SplitN(listen, ";", 2); len(parts) == 2 {
return parts[0], parts[1]
}
return "tcp", listen
}