/
server.go
374 lines (317 loc) · 9.61 KB
/
server.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
package langserver
import (
"context"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/x1unix/go-playground/pkg/analyzer"
"github.com/x1unix/go-playground/pkg/compiler"
"github.com/x1unix/go-playground/pkg/compiler/storage"
"github.com/x1unix/go-playground/pkg/goplay"
"go.uber.org/zap"
"golang.org/x/time/rate"
)
const (
// limit for wasm compile requests per second (250ms per request)
compileRequestsPerFrame = 4
frameTime = time.Second
maxBuildTimeDuration = time.Second * 30
wasmMimeType = "application/wasm"
formatQueryParam = "format"
artifactParamVal = "artifactId"
playgroundBackendParam = "backend"
playgroundGoTip = "gotip"
)
type PlaygroundServices struct {
Default *goplay.Client
GoTip *goplay.Client
}
// Service is language server service
type Service struct {
version string
log *zap.SugaredLogger
index analyzer.PackageIndex
compiler compiler.BuildService
playgrounds *PlaygroundServices
limiter *rate.Limiter
}
// New is Service constructor
func New(version string, playgrounds *PlaygroundServices, packages []*analyzer.Package, builder compiler.BuildService) *Service {
return &Service{
compiler: builder,
version: version,
playgrounds: playgrounds,
log: zap.S().Named("langserver"),
index: analyzer.BuildPackageIndex(packages),
limiter: rate.NewLimiter(rate.Every(frameTime), compileRequestsPerFrame),
}
}
// Mount mounts service on route
func (s *Service) Mount(r *mux.Router) {
r.Path("/version").
HandlerFunc(WrapHandler(s.HandleGetVersion))
r.Path("/suggest").
HandlerFunc(WrapHandler(s.HandleGetSuggestion))
r.Path("/run").Methods(http.MethodPost).
HandlerFunc(WrapHandler(s.HandleRunCode, ValidateContentLength))
r.Path("/compile").Methods(http.MethodPost).
HandlerFunc(WrapHandler(s.HandleCompile, ValidateContentLength))
r.Path("/format").Methods(http.MethodPost).
HandlerFunc(WrapHandler(s.HandleFormatCode, ValidateContentLength))
r.Path("/share").Methods(http.MethodPost).
HandlerFunc(WrapHandler(s.HandleShare, ValidateContentLength))
r.Path("/snippet/{id}").Methods(http.MethodGet).
HandlerFunc(WrapHandler(s.HandleGetSnippet))
r.Path("/artifacts/{artifactId:[a-fA-F0-9]+}.wasm").Methods(http.MethodGet).
HandlerFunc(WrapHandler(s.HandleArtifactRequest))
}
func (s *Service) lookupBuiltin(val string) (*SuggestionsResponse, error) {
// Package or built-in lookup
pkg, ok := s.index.PackageByName("builtin")
if !ok {
return nil, fmt.Errorf("failed to find %q package and it's weird", "builtin")
}
if err := pkg.Analyze(); err != nil {
return nil, fmt.Errorf("failed to analyze builtin package: %s", err)
}
// Lookup in built-in functions and them package names
resp := SuggestionsResponse{
Suggestions: pkg.SymbolByChar(val),
}
resp.Suggestions = append(resp.Suggestions, s.index.Match(val)...)
return &resp, nil
}
func (s *Service) provideSuggestion(req SuggestionRequest) (*SuggestionsResponse, error) {
// Provide package suggestions (if requested)
if req.PackageName != "" {
pkg, ok := s.index.PackageByName(req.PackageName)
if !ok {
return nil, fmt.Errorf("package %q doesn't exists in index", req.PackageName)
}
if err := pkg.Analyze(); err != nil {
return nil, fmt.Errorf("failed to analyze package %q: %s", req.PackageName, err)
}
var symbols []*analyzer.CompletionItem
if req.Value != "" {
symbols = pkg.SymbolByChar(req.Value)
} else {
symbols = pkg.AllSymbols()
}
return &SuggestionsResponse{
Suggestions: symbols,
}, nil
}
if req.Value == "" {
return nil, fmt.Errorf("empty suggestion request value, nothing to provide")
}
return s.lookupBuiltin(req.Value)
}
// HandleGetVersion handles /api/version
func (s *Service) HandleGetVersion(w http.ResponseWriter, _ *http.Request) error {
WriteJSON(w, VersionResponse{Version: s.version})
return nil
}
// HandleGetSuggestion handles code suggestion
func (s *Service) HandleGetSuggestion(w http.ResponseWriter, r *http.Request) error {
q := r.URL.Query()
value := q.Get("value")
pkgName := q.Get("packageName")
resp, err := s.provideSuggestion(SuggestionRequest{PackageName: pkgName, Value: value})
if err != nil {
return err
}
resp.Write(w)
return nil
}
// HandleFormatCode handles goimports action
func (s *Service) HandleFormatCode(w http.ResponseWriter, r *http.Request) error {
src, err := getPayloadFromRequest(r)
if err != nil {
return err
}
formatted, _, err := s.goImportsCode(r, src)
if err != nil {
if goplay.IsCompileError(err) {
return NewHTTPError(http.StatusBadRequest, err)
}
s.log.Error(err)
return err
}
WriteJSON(w, RunResponse{Formatted: string(formatted)})
return nil
}
// HandleShare handles snippet share
func (s *Service) HandleShare(w http.ResponseWriter, r *http.Request) error {
client := s.getPlaygroundClientFromRequest(r)
shareID, err := client.Share(r.Context(), r.Body)
defer r.Body.Close()
if err != nil {
if err == goplay.ErrSnippetTooLarge {
return NewHTTPError(http.StatusRequestEntityTooLarge, err)
}
s.log.Error("failed to share code: ", err)
return err
}
WriteJSON(w, ShareResponse{SnippetID: shareID})
return nil
}
// HandleGetSnippet handles snippet load
func (s *Service) HandleGetSnippet(w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
snippetID := vars["id"]
client := s.getPlaygroundClientFromRequest(r)
snippet, err := client.GetSnippet(r.Context(), snippetID)
if err != nil {
if err == goplay.ErrSnippetNotFound {
return Errorf(http.StatusNotFound, "snippet %q not found", snippetID)
}
s.log.Errorw("failed to get snippet",
"snippetID", snippetID,
"err", err,
)
return err
}
WriteJSON(w, SnippetResponse{
FileName: snippet.FileName,
Code: snippet.Contents,
})
return nil
}
// HandleRunCode handles code run
func (s *Service) HandleRunCode(w http.ResponseWriter, r *http.Request) error {
src, err := getPayloadFromRequest(r)
if err != nil {
return err
}
shouldFormat, err := shouldFormatCode(r)
if err != nil {
return err
}
var changed bool
if shouldFormat {
src, changed, err = s.goImportsCode(r, src)
if err != nil {
if goplay.IsCompileError(err) {
return NewHTTPError(http.StatusBadRequest, err)
}
s.log.Error(err)
return err
}
}
client := s.getPlaygroundClientFromRequest(r)
res, err := client.Compile(r.Context(), src)
if err != nil {
return err
}
if err := res.HasError(); err != nil {
return NewHTTPError(http.StatusBadRequest, err)
}
result := RunResponse{Events: res.Events}
if changed {
// Return formatted code if goimports had any effect
result.Formatted = string(src)
}
s.log.Debugw("response from compiler", "res", res)
WriteJSON(w, result)
return nil
}
// HandleArtifactRequest handles WASM build artifact request
func (s *Service) HandleArtifactRequest(w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
artifactId := storage.ArtifactID(vars[artifactParamVal])
data, err := s.compiler.GetArtifact(artifactId)
if err != nil {
if err == storage.ErrNotExists {
return Errorf(http.StatusNotFound, "artifact not found")
}
return err
}
n, err := io.Copy(w, data)
defer data.Close()
if err != nil {
s.log.Errorw("failed to send artifact",
"artifactID", artifactId,
"err", err,
)
return err
}
w.Header().Set("Content-Type", wasmMimeType)
w.Header().Set("Content-Length", strconv.FormatInt(n, 10))
return nil
}
func (s *Service) getPlaygroundClientFromRequest(r *http.Request) *goplay.Client {
playgroundBackend := strings.TrimSpace(r.URL.Query().Get(playgroundBackendParam))
if playgroundBackend == playgroundGoTip {
s.log.Debugw("Using goTip backend for request", zap.String("url", r.RequestURI))
return s.playgrounds.GoTip
}
return s.playgrounds.Default
}
// HandleCompile handles WASM build request
func (s *Service) HandleCompile(w http.ResponseWriter, r *http.Request) error {
// Limit for request timeout
ctx, cancel := context.WithDeadline(r.Context(), time.Now().Add(maxBuildTimeDuration))
defer cancel()
// Wait for our queue in line for compilation
if err := s.limiter.Wait(ctx); err != nil {
return NewHTTPError(http.StatusTooManyRequests, err)
}
src, err := getPayloadFromRequest(r)
if err != nil {
return err
}
shouldFormat, err := shouldFormatCode(r)
if err != nil {
return err
}
var changed bool
if shouldFormat {
src, changed, err = s.goImportsCode(r, src)
if err != nil {
if goplay.IsCompileError(err) {
return NewHTTPError(http.StatusBadRequest, err)
}
s.log.Error(err)
return err
}
}
result, err := s.compiler.Build(ctx, src)
if err != nil {
switch err.(type) {
case *compiler.BuildError:
return NewHTTPError(http.StatusBadRequest, err)
default:
return err
}
}
resp := BuildResponse{FileName: result.FileName}
if changed {
// Return formatted code if goimports had any effect
resp.Formatted = string(src)
}
WriteJSON(w, resp)
return nil
}
// goImportsCode reads code from request and performs "goimports" on it
// if any error occurs, it sends error response to client and closes connection
//
// if "format" url query param is undefined or set to "false", just returns code as is
func (s *Service) goImportsCode(r *http.Request, src []byte) ([]byte, bool, error) {
client := s.getPlaygroundClientFromRequest(r)
resp, err := client.GoImports(r.Context(), src)
if err != nil {
if err == goplay.ErrSnippetTooLarge {
return nil, false, NewHTTPError(http.StatusRequestEntityTooLarge, err)
}
return nil, false, err
}
if err = resp.HasError(); err != nil {
return nil, false, err
}
changed := resp.Body != string(src)
return []byte(resp.Body), changed, nil
}