forked from runytry1/go-langserver
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
185 lines (160 loc) · 5.92 KB
/
main.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
package main // import "github.com/sourcegraph/go-langserver"
import (
"context"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"runtime/debug"
"time"
"github.com/sourcegraph/go-langserver/langserver"
"github.com/sourcegraph/jsonrpc2"
_ "net/http/pprof"
)
var (
mode = flag.String("mode", "stdio", "communication mode (stdio|tcp)")
addr = flag.String("addr", ":4389", "server listen address (tcp)")
trace = flag.Bool("trace", false, "print all requests and responses")
logfile = flag.String("logfile", "", "also log to this file (in addition to stderr)")
printVersion = flag.Bool("version", false, "print version and exit")
pprof = flag.String("pprof", "", "start a pprof http server (https://golang.org/pkg/net/http/pprof/)")
freeosmemory = flag.Bool("freeosmemory", true, "aggressively free memory back to the OS")
// Default Config, can be overridden by InitializationOptions
usebinarypkgcache = flag.Bool("usebinarypkgcache", true, "use $GOPATH/pkg binary .a files (improves performance). Can be overridden by InitializationOptions.")
maxparallelism = flag.Int("maxparallelism", 0, "use at max N parallel goroutines to fulfill requests. Can be overridden by InitializationOptions.")
gocodecompletion = flag.Bool("gocodecompletion", false, "enable completion (extra memory burden). Can be overridden by InitializationOptions.")
diagnostics = flag.Bool("diagnostics", false, "enable diagnostics (extra memory burden). Can be overridden by InitializationOptions.")
funcSnippetEnabled = flag.Bool("func-snippet-enabled", true, "enable argument snippets on func completion. Can be overridden by InitializationOptions.")
formatTool = flag.String("format-tool", "goimports", "which tool is used to format documents. Supported: goimports and gofmt. Can be overridden by InitializationOptions.")
)
// version is the version field we report back. If you are releasing a new version:
// 1. Create commit without -dev suffix.
// 2. Create commit with version incremented and -dev suffix
// 3. Push to master
// 4. Tag the commit created in (1) with the value of the version string
const version = "v2-dev"
func main() {
flag.Parse()
log.SetFlags(0)
// Start pprof server, if desired.
if *pprof != "" {
go func() {
log.Println(http.ListenAndServe(*pprof, nil))
}()
}
if *freeosmemory {
go freeOSMemory()
}
cfg := langserver.NewDefaultConfig()
cfg.FuncSnippetEnabled = *funcSnippetEnabled
cfg.GocodeCompletionEnabled = *gocodecompletion
cfg.DiagnosticsEnabled = *diagnostics
cfg.UseBinaryPkgCache = *usebinarypkgcache
cfg.FormatTool = *formatTool
if *maxparallelism > 0 {
cfg.MaxParallelism = *maxparallelism
}
if err := run(cfg); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(cfg langserver.Config) error {
if *printVersion {
fmt.Println(version)
return nil
}
var logW io.Writer
if *logfile == "" {
logW = os.Stderr
} else {
f, err := os.Create(*logfile)
if err != nil {
return err
}
defer f.Close()
logW = io.MultiWriter(os.Stderr, f)
}
log.SetOutput(logW)
var connOpt []jsonrpc2.ConnOpt
if *trace {
connOpt = append(connOpt, jsonrpc2.LogMessages(log.New(logW, "", 0)))
}
handler := langserver.NewHandler(cfg)
switch *mode {
case "tcp":
lis, err := net.Listen("tcp", *addr)
if err != nil {
return err
}
defer lis.Close()
log.Println("langserver-go: listening on", *addr)
for {
conn, err := lis.Accept()
if err != nil {
return err
}
jsonrpc2.NewConn(context.Background(), jsonrpc2.NewBufferedStream(conn, jsonrpc2.VSCodeObjectCodec{}), handler, connOpt...)
}
case "stdio":
log.Println("langserver-go: reading on stdin, writing on stdout")
<-jsonrpc2.NewConn(context.Background(), jsonrpc2.NewBufferedStream(stdrwc{}, jsonrpc2.VSCodeObjectCodec{}), handler, connOpt...).DisconnectNotify()
log.Println("connection closed")
return nil
default:
return fmt.Errorf("invalid mode %q", *mode)
}
}
type stdrwc struct{}
func (stdrwc) Read(p []byte) (int, error) {
return os.Stdin.Read(p)
}
func (stdrwc) Write(p []byte) (int, error) {
return os.Stdout.Write(p)
}
func (stdrwc) Close() error {
if err := os.Stdin.Close(); err != nil {
return err
}
return os.Stdout.Close()
}
// freeOSMemory should be called in a goroutine, it invokes
// runtime/debug.FreeOSMemory() more aggressively than the runtime default of
// 5 minutes after GC.
//
// There is a long-standing known issue with Go in which memory is not returned
// to the OS aggressively enough[1], which coincidently harms our application
// quite a lot because we perform so many short-burst heap allocations during
// the type-checking phase.
//
// This function should only be invoked in editor mode, not in sourcegraph.com
// mode, because users running the language server as part of their editor
// generally expect much lower memory usage. In contrast, on sourcegraph.com we
// can give our servers plenty of RAM and allow Go to consume as much as it
// wants. Go does reuse the memory not free'd to the OS, and as such enabling
// this does _technically_ make our application perform less optimally -- but
// in practice this has no observable effect in editor mode.
//
// The end effect of performing this is that repeating "hover over code" -> "make an edit"
// 10 times inside a large package like github.com/docker/docker/cmd/dockerd:
//
//
// | Real Before | Real After | Real Change | Go Before | Go After | Go Change |
// |-------------|------------|-------------|-----------|----------|-----------|
// | 7.61GB | 4.12GB | -45.86% | 3.92GB | 3.33GB | -15.05% |
//
// Where `Real` means real memory reported by OS X Activity Monitor, and `Go`
// means memory reported by Go as being in use.
//
// TL;DR: 46% less memory consumption for users running with the vscode-go extension.
//
// [1] https://github.com/golang/go/issues/14735#issuecomment-194470114
func freeOSMemory() {
for {
time.Sleep(1 * time.Second)
debug.FreeOSMemory()
}
}