-
Notifications
You must be signed in to change notification settings - Fork 130
/
service.go
255 lines (217 loc) · 7 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
package handlers
import (
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"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/terraform/rootmodule"
"github.com/hashicorp/terraform-ls/internal/watcher"
"github.com/hashicorp/terraform-ls/langserver/session"
"github.com/sourcegraph/go-lsp"
)
type service struct {
logger *log.Logger
srvCtx context.Context
sessCtx context.Context
stopSession context.CancelFunc
ww watcher.Watcher
newRootModuleManager rootmodule.RootModuleManagerFactory
newWatcher watcher.WatcherFactory
}
var discardLogs = log.New(ioutil.Discard, "", 0)
func NewSession(srvCtx context.Context) session.Session {
sessCtx, stopSession := context.WithCancel(srvCtx)
return &service{
logger: discardLogs,
srvCtx: srvCtx,
sessCtx: sessCtx,
stopSession: stopSession,
newRootModuleManager: rootmodule.NewRootModuleManager,
newWatcher: watcher.NewWatcher,
}
}
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)
}
fs := filesystem.NewFilesystem()
fs.SetLogger(svc.logger)
lh := LogHandler(svc.logger)
cc := &lsp.ClientCapabilities{}
rmm := svc.newRootModuleManager(svc.sessCtx)
rmm.SetLogger(svc.logger)
// The following is set via CLI flags, hence available in the server context
if path, ok := lsctx.TerraformExecPath(svc.srvCtx); ok {
rmm.SetTerraformExecPath(path)
}
if path, ok := lsctx.TerraformExecLogPath(svc.srvCtx); ok {
rmm.SetTerraformExecLogPath(path)
}
if timeout, ok := lsctx.TerraformExecTimeout(svc.srvCtx); ok {
rmm.SetTerraformExecTimeout(timeout)
}
ww, err := svc.newWatcher()
if err != nil {
return nil, err
}
svc.ww = ww
svc.ww.SetLogger(svc.logger)
svc.ww.AddChangeHook(func(file watcher.TrackedFile) error {
w, err := rmm.RootModuleByPath(file.Path())
if err != nil {
return err
}
if w.IsKnownPluginLockFile(file.Path()) {
svc.logger.Printf("detected plugin cache change, updating ...")
return w.UpdatePluginCache(file)
}
return nil
})
svc.ww.AddChangeHook(func(file watcher.TrackedFile) error {
rm, err := rmm.RootModuleByPath(file.Path())
if err != nil {
return err
}
if rm.IsKnownModuleManifestFile(file.Path()) {
svc.logger.Printf("detected module manifest change, updating ...")
return rm.UpdateModuleManifest(file)
}
return nil
})
rootDir := ""
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.WithFilesystem(fs, ctx)
ctx = lsctx.WithClientCapabilitiesSetter(cc, ctx)
ctx = lsctx.WithWatcher(ww, ctx)
ctx = lsctx.WithRootDirectory(&rootDir, ctx)
ctx = lsctx.WithRootModuleManager(rmm, ctx)
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
}
ctx = lsctx.WithFilesystem(fs, ctx)
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.WithFilesystem(fs, ctx)
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.WithFilesystem(fs, ctx)
ctx = lsctx.WithRootDirectory(&rootDir, ctx)
ctx = lsctx.WithRootModuleCandidateFinder(rmm, ctx)
return handle(ctx, req, TextDocumentDidOpen)
},
"textDocument/didClose": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithFilesystem(fs, ctx)
return handle(ctx, req, TextDocumentDidClose)
},
"textDocument/completion": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithFilesystem(fs, ctx) // TODO: Read-only FS
ctx = lsctx.WithClientCapabilities(cc, ctx)
ctx = lsctx.WithParserFinder(rmm, ctx)
return handle(ctx, req, lh.TextDocumentComplete)
},
"textDocument/formatting": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.CheckInitializationIsConfirmed()
if err != nil {
return nil, err
}
ctx = lsctx.WithFilesystem(fs, ctx)
ctx = lsctx.WithTerraformExecFinder(rmm, ctx)
return handle(ctx, req, lh.TextDocumentFormatting)
},
"shutdown": func(ctx context.Context, req *jrpc2.Request) (interface{}, error) {
err := session.Shutdown(req)
if err != nil {
return nil, err
}
ctx = lsctx.WithFilesystem(fs, ctx)
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.logger.Println("Stopping watcher for session ...")
err := svc.ww.Stop()
if err != nil {
svc.logger.Println("Unable to stop watcher for session:", err)
}
svc.stopSession()
}
// 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
}