-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathservice.go
364 lines (311 loc) · 10.5 KB
/
service.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
package handlers
import (
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"time"
"github.com/creachadair/jrpc2"
"github.com/creachadair/jrpc2/code"
rpch "github.com/creachadair/jrpc2/handler"
lsctx "github.com/hashicorp/terraform-ls/internal/context"
"github.com/hashicorp/terraform-ls/internal/filesystem"
"github.com/hashicorp/terraform-ls/internal/langserver/diagnostics"
"github.com/hashicorp/terraform-ls/internal/langserver/session"
lsp "github.com/hashicorp/terraform-ls/internal/protocol"
"github.com/hashicorp/terraform-ls/internal/terraform/rootmodule"
"github.com/hashicorp/terraform-ls/internal/watcher"
)
type service struct {
logger *log.Logger
srvCtx context.Context
sessCtx context.Context
stopSession context.CancelFunc
fs filesystem.Filesystem
watcher watcher.Watcher
walker *rootmodule.Walker
modMgr rootmodule.RootModuleManager
newRootModuleManager rootmodule.RootModuleManagerFactory
newWatcher watcher.WatcherFactory
newWalker rootmodule.WalkerFactory
}
var discardLogs = log.New(ioutil.Discard, "", 0)
func NewSession(srvCtx context.Context) session.Session {
fs := filesystem.NewFilesystem()
sessCtx, stopSession := context.WithCancel(srvCtx)
return &service{
logger: discardLogs,
fs: fs,
srvCtx: srvCtx,
sessCtx: sessCtx,
stopSession: stopSession,
newRootModuleManager: rootmodule.NewRootModuleManager,
newWatcher: watcher.NewWatcher,
newWalker: rootmodule.NewWalker,
}
}
func (svc *service) SetLogger(logger *log.Logger) {
svc.logger = logger
}
// Assigner builds out the jrpc2.Map according to the LSP protocol
// and passes related dependencies to handlers via context
func (svc *service) Assigner() (jrpc2.Assigner, error) {
svc.logger.Println("Preparing new session ...")
session := session.NewSession(svc.stopSession)
err := session.Prepare()
if err != nil {
return nil, fmt.Errorf("Unable to prepare session: %w", err)
}
svc.fs.SetLogger(svc.logger)
lh := LogHandler(svc.logger)
cc := &lsp.ClientCapabilities{}
svc.modMgr = svc.newRootModuleManager(svc.fs)
svc.modMgr.SetLogger(svc.logger)
svc.logger.Printf("Worker pool size set to %d", svc.modMgr.WorkerPoolSize())
tr := newTickReporter(5 * time.Second)
tr.AddReporter(func() {
queueSize := svc.modMgr.WorkerQueueSize()
if queueSize < 1 {
return
}
svc.logger.Printf("Root modules waiting to be loaded: %d", queueSize)
})
tr.StartReporting(svc.sessCtx)
svc.walker = svc.newWalker()
// The following is set via CLI flags, hence available in the server context
if path, ok := lsctx.TerraformExecPath(svc.srvCtx); ok {
svc.modMgr.SetTerraformExecPath(path)
}
if path, ok := lsctx.TerraformExecLogPath(svc.srvCtx); ok {
svc.modMgr.SetTerraformExecLogPath(path)
}
if timeout, ok := lsctx.TerraformExecTimeout(svc.srvCtx); ok {
svc.modMgr.SetTerraformExecTimeout(timeout)
}
ww, err := svc.newWatcher()
if err != nil {
return nil, err
}
svc.watcher = ww
svc.watcher.SetLogger(svc.logger)
svc.watcher.AddChangeHook(func(ctx context.Context, file watcher.TrackedFile) error {
rm, err := svc.modMgr.RootModuleByPath(file.Path())
if err != nil {
return err
}
if rm.IsKnownPluginLockFile(file.Path()) {
svc.logger.Printf("detected plugin cache change, updating schema ...")
err := rm.UpdateProviderSchemaCache(ctx, file)
if err != nil {
svc.logger.Printf(err.Error())
}
}
return nil
})
svc.watcher.AddChangeHook(func(_ context.Context, file watcher.TrackedFile) error {
rm, err := svc.modMgr.RootModuleByPath(file.Path())
if err != nil {
return err
}
if rm.IsKnownModuleManifestFile(file.Path()) {
svc.logger.Printf("detected module manifest change, updating ...")
err := rm.UpdateModuleManifest(file)
if err != nil {
svc.logger.Printf(err.Error())
}
}
return nil
})
err = svc.watcher.Start()
if err != nil {
return nil, err
}
rmLoader := rootmodule.NewRootModuleLoader(svc.sessCtx, svc.modMgr)
diags := diagnostics.NewNotifier(svc.sessCtx, svc.logger)
rootDir := ""
commandPrefix := ""
m := map[string]rpch.Func{
"initialize": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.Initialize(req)
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilitiesSetter(ctx, cc)
ctx = lsctx.WithWatcher(ctx, ww)
ctx = lsctx.WithRootModuleWalker(ctx, svc.walker)
ctx = lsctx.WithRootDirectory(ctx, &rootDir)
ctx = lsctx.WithCommandPrefix(ctx, &commandPrefix)
ctx = lsctx.WithRootModuleManager(ctx, svc.modMgr)
ctx = lsctx.WithRootModuleLoader(ctx, rmLoader)
version, ok := lsctx.LanguageServerVersion(svc.srvCtx)
if ok {
ctx = lsctx.WithLanguageServerVersion(ctx, version)
}
return handle(ctx, req, lh.Initialize)
},
"initialized": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.ConfirmInitialization(req)
if err != nil {
return nil, err
}
return handle(ctx, req, Initialized)
},
"textDocument/didChange": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDiagnostics(ctx, diags)
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithRootModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, TextDocumentDidChange)
},
"textDocument/didOpen": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithDiagnostics(ctx, diags)
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithRootDirectory(ctx, &rootDir)
ctx = lsctx.WithRootModuleManager(ctx, svc.modMgr)
ctx = lsctx.WithRootModuleFinder(ctx, svc.modMgr)
ctx = lsctx.WithRootModuleWalker(ctx, svc.walker)
ctx = lsctx.WithWatcher(ctx, ww)
return handle(ctx, req, lh.TextDocumentDidOpen)
},
"textDocument/didClose": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
return handle(ctx, req, TextDocumentDidClose)
},
"textDocument/documentSymbol": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithRootModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.TextDocumentSymbol)
},
"textDocument/completion": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithRootModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.TextDocumentComplete)
},
"textDocument/hover": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithClientCapabilities(ctx, cc)
ctx = lsctx.WithRootModuleFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.TextDocumentHover)
},
"textDocument/formatting": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
ctx = lsctx.WithTerraformFormatterFinder(ctx, svc.modMgr)
return handle(ctx, req, lh.TextDocumentFormatting)
},
"workspace/executeCommand": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithCommandPrefix(ctx, &commandPrefix)
ctx = lsctx.WithRootModuleFinder(ctx, svc.modMgr)
ctx = lsctx.WithRootModuleWalker(ctx, svc.walker)
ctx = lsctx.WithWatcher(ctx, ww)
ctx = lsctx.WithRootDirectory(ctx, &rootDir)
return handle(ctx, req, lh.WorkspaceExecuteCommand)
},
"shutdown": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.Shutdown(req)
if err != nil {
return nil, err
}
ctx = lsctx.WithDocumentStorage(ctx, svc.fs)
svc.shutdown()
return handle(ctx, req, Shutdown)
},
"exit": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.Exit()
if err != nil {
return nil, err
}
svc.stopSession()
return nil, nil
},
"$/cancelRequest": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
return handle(ctx, req, CancelRequest)
},
}
return convertMap(m), nil
}
func (svc *service) Finish(status jrpc2.ServerStatus) {
if status.Closed() || status.Err != nil {
svc.logger.Printf("session stopped unexpectedly (err: %v)", status.Err)
}
svc.shutdown()
svc.stopSession()
}
func (svc *service) shutdown() {
if svc.walker != nil {
svc.logger.Printf("stopping walker for session ...")
svc.walker.Stop()
svc.logger.Printf("walker stopped")
}
if svc.watcher != nil {
svc.logger.Println("stopping watcher for session ...")
err := svc.watcher.Stop()
if err != nil {
svc.logger.Println("unable to stop watcher for session:", err)
} else {
svc.logger.Println("watcher stopped")
}
}
if svc.modMgr != nil {
svc.logger.Println("cancelling any root module loading ...")
svc.modMgr.CancelLoading()
svc.logger.Println("root module loading cancelled")
}
}
// convertMap is a helper function allowing us to omit the jrpc2.Func
// signature from the method definitions
func convertMap(m map[string]rpch.Func) rpch.Map {
hm := make(rpch.Map, len(m))
for method, fun := range m {
hm[method] = rpch.New(fun)
}
return hm
}
const requestCancelled code.Code = -32800
// handle calls a jrpc2.Func compatible function
func handle(ctx context.Context, req *jrpc2.Request, fn interface{}) (interface{}, error) {
f := rpch.New(fn)
result, err := f.Handle(ctx, req)
if ctx.Err() != nil && errors.Is(ctx.Err(), context.Canceled) {
err = fmt.Errorf("%w: %s", requestCancelled.Err(), err)
}
return result, err
}