Debian Codegraph @

gopls/internal/protocol/protocol.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package protocol
6
7 import (
8 "bytes"
9 "context"
10 "encoding/json"
11 "fmt"
12 "io"
13
14 "golang.org/x/tools/internal/event"
15 "golang.org/x/tools/internal/jsonrpc2"
16 jsonrpc2_v2 "golang.org/x/tools/internal/jsonrpc2_v2"
17 )
18
19 var (
20 // RequestCancelledError should be used when a request is cancelled early.
21 RequestCancelledError = jsonrpc2.NewError(-32800, "JSON RPC cancelled")
22 RequestCancelledErrorV2 = jsonrpc2_v2.NewError(-32800, "JSON RPC cancelled")
23 )
24
25 type ClientCloser interface {
26 Client
27 io.Closer
28 }
29
30 type connSender interface {
31 io.Closer
32
33 Notify(ctx context.Context, method string, params any) error
34 Call(ctx context.Context, method string, params, result any) error
35 }
36
37 type clientDispatcher struct {
38 sender connSender
39 }
40
41 func (c *clientDispatcher) Close() error {
42 return c.sender.Close()
43 }
44
45 // ClientDispatcher returns a Client that dispatches LSP requests across the
46 // given jsonrpc2 connection.
47 func ClientDispatcher(conn jsonrpc2.Conn) ClientCloser {
48 return &clientDispatcher{sender: clientConn{conn}}
49 }
50
51 type clientConn struct {
52 conn jsonrpc2.Conn
53 }
54
55 func (c clientConn) Close() error {
56 return c.conn.Close()
57 }
58
59 func (c clientConn) Notify(ctx context.Context, method string, params any) error {
60 return c.conn.Notify(ctx, method, params)
61 }
62
63 func (c clientConn) Call(ctx context.Context, method string, params any, result any) error {
64 id, err := c.conn.Call(ctx, method, params, result)
65 if ctx.Err() != nil {
66 cancelCall(ctx, c, id)
67 }
68 return err
69 }
70
71 func ClientDispatcherV2(conn *jsonrpc2_v2.Connection) ClientCloser {
72 return &clientDispatcher{clientConnV2{conn}}
73 }
74
75 type clientConnV2 struct {
76 conn *jsonrpc2_v2.Connection
77 }
78
79 func (c clientConnV2) Close() error {
80 return c.conn.Close()
81 }
82
83 func (c clientConnV2) Notify(ctx context.Context, method string, params any) error {
84 return c.conn.Notify(ctx, method, params)
85 }
86
87 func (c clientConnV2) Call(ctx context.Context, method string, params any, result any) error {
88 call := c.conn.Call(ctx, method, params)
89 err := call.Await(ctx, result)
90 if ctx.Err() != nil {
91 detached := context.WithoutCancel(ctx)
92 c.conn.Notify(detached, "$/cancelRequest", &CancelParams{ID: call.ID().Raw()})
93 }
94 return err
95 }
96
97 // ServerDispatcher returns a Server that dispatches LSP requests across the
98 // given jsonrpc2 connection.
99 func ServerDispatcher(conn jsonrpc2.Conn) Server {
100 return &serverDispatcher{sender: clientConn{conn}}
101 }
102
103 func ServerDispatcherV2(conn *jsonrpc2_v2.Connection) Server {
104 return &serverDispatcher{sender: clientConnV2{conn}}
105 }
106
107 type serverDispatcher struct {
108 sender connSender
109 }
110
111 func ClientHandler(client Client, handler jsonrpc2.Handler) jsonrpc2.Handler {
112 return func(ctx context.Context, reply jsonrpc2.Replier, req jsonrpc2.Request) error {
113 if ctx.Err() != nil {
114 ctx := context.WithoutCancel(ctx)
115 return reply(ctx, nil, RequestCancelledError)
116 }
117 handled, err := clientDispatch(ctx, client, reply, req)
118 if handled || err != nil {
119 return err
120 }
121 return handler(ctx, reply, req)
122 }
123 }
124
125 func ClientHandlerV2(client Client) jsonrpc2_v2.Handler {
126 return jsonrpc2_v2.HandlerFunc(func(ctx context.Context, req *jsonrpc2_v2.Request) (any, error) {
127 if ctx.Err() != nil {
128 return nil, RequestCancelledErrorV2
129 }
130 req1 := req2to1(req)
131 var (
132 result any
133 resErr error
134 )
135 replier := func(_ context.Context, res any, err error) error {
136 if err != nil {
137 resErr = err
138 return nil
139 }
140 result = res
141 return nil
142 }
143 _, err := clientDispatch(ctx, client, replier, req1)
144 if err != nil {
145 return nil, err
146 }
147 return result, resErr
148 })
149 }
150
151 func ServerHandler(server Server, handler jsonrpc2.Handler) jsonrpc2.Handler {
152 return func(ctx context.Context, reply jsonrpc2.Replier, req jsonrpc2.Request) error {
153 if ctx.Err() != nil {
154 ctx := context.WithoutCancel(ctx)
155 return reply(ctx, nil, RequestCancelledError)
156 }
157 handled, err := serverDispatch(ctx, server, reply, req)
158 if handled || err != nil {
159 return err
160 }
161 return handler(ctx, reply, req)
162 }
163 }
164
165 func ServerHandlerV2(server Server) jsonrpc2_v2.Handler {
166 return jsonrpc2_v2.HandlerFunc(func(ctx context.Context, req *jsonrpc2_v2.Request) (any, error) {
167 if ctx.Err() != nil {
168 return nil, RequestCancelledErrorV2
169 }
170 req1 := req2to1(req)
171 var (
172 result any
173 resErr error
174 )
175 replier := func(_ context.Context, res any, err error) error {
176 if err != nil {
177 resErr = err
178 return nil
179 }
180 result = res
181 return nil
182 }
183 _, err := serverDispatch(ctx, server, replier, req1)
184 if err != nil {
185 return nil, err
186 }
187 return result, resErr
188 })
189 }
190
191 func req2to1(req2 *jsonrpc2_v2.Request) jsonrpc2.Request {
192 if req2.ID.IsValid() {
193 raw := req2.ID.Raw()
194 var idv1 jsonrpc2.ID
195 switch v := raw.(type) {
196 case int64:
197 idv1 = jsonrpc2.NewIntID(v)
198 case string:
199 idv1 = jsonrpc2.NewStringID(v)
200 default:
201 panic(fmt.Sprintf("unsupported ID type %T", raw))
202 }
203 req1, err := jsonrpc2.NewCall(idv1, req2.Method, req2.Params)
204 if err != nil {
205 panic(err)
206 }
207 return req1
208 }
209 req1, err := jsonrpc2.NewNotification(req2.Method, req2.Params)
210 if err != nil {
211 panic(err)
212 }
213 return req1
214 }
215
216 func Handlers(handler jsonrpc2.Handler) jsonrpc2.Handler {
217 return CancelHandler(
218 jsonrpc2.AsyncHandler(
219 jsonrpc2.MustReplyHandler(handler)))
220 }
221
222 func CancelHandler(handler jsonrpc2.Handler) jsonrpc2.Handler {
223 handler, canceller := jsonrpc2.CancelHandler(handler)
224 return func(ctx context.Context, reply jsonrpc2.Replier, req jsonrpc2.Request) error {
225 if req.Method() != "$/cancelRequest" {
226 // TODO(iancottrell): See if we can generate a reply for the request to be cancelled
227 // at the point of cancellation rather than waiting for gopls to naturally reply.
228 // To do that, we need to keep track of whether a reply has been sent already and
229 // be careful about racing between the two paths.
230 // TODO(iancottrell): Add a test that watches the stream and verifies the response
231 // for the cancelled request flows.
232 replyWithDetachedContext := func(ctx context.Context, resp any, err error) error {
233 // https://microsoft.github.io/language-server-protocol/specifications/specification-current/#cancelRequest
234 if ctx.Err() != nil && err == nil {
235 err = RequestCancelledError
236 }
237 ctx = context.WithoutCancel(ctx)
238 return reply(ctx, resp, err)
239 }
240 return handler(ctx, replyWithDetachedContext, req)
241 }
242 var params CancelParams
243 if err := UnmarshalJSON(req.Params(), &params); err != nil {
244 return sendParseError(ctx, reply, err)
245 }
246 if n, ok := params.ID.(float64); ok {
247 canceller(jsonrpc2.NewIntID(int64(n)))
248 } else if s, ok := params.ID.(string); ok {
249 canceller(jsonrpc2.NewStringID(s))
250 } else {
251 return sendParseError(ctx, reply, fmt.Errorf("request ID %v malformed", params.ID))
252 }
253 return reply(ctx, nil, nil)
254 }
255 }
256
257 func Call(ctx context.Context, conn jsonrpc2.Conn, method string, params any, result any) error {
258 id, err := conn.Call(ctx, method, params, result)
259 if ctx.Err() != nil {
260 cancelCall(ctx, clientConn{conn}, id)
261 }
262 return err
263 }
264
265 func cancelCall(ctx context.Context, sender connSender, id jsonrpc2.ID) {
266 ctx = context.WithoutCancel(ctx)
267 ctx, done := event.Start(ctx, "protocol.canceller")
268 defer done()
269 // Note that only *jsonrpc2.ID implements json.Marshaler.
270 sender.Notify(ctx, "$/cancelRequest", &CancelParams{ID: &id})
271 }
272
273 // UnmarshalJSON unmarshals msg into the variable pointed to by
274 // params. In JSONRPC, optional messages may be
275 // "null", in which case it is a no-op.
276 func UnmarshalJSON(msg json.RawMessage, v any) error {
277 if len(msg) == 0 || bytes.Equal(msg, []byte("null")) {
278 return nil
279 }
280 return json.Unmarshal(msg, v)
281 }
282
283 func sendParseError(ctx context.Context, reply jsonrpc2.Replier, err error) error {
284 return reply(ctx, nil, fmt.Errorf("%w: %s", jsonrpc2.ErrParse, err))
285 }
286
287 // NonNilSlice returns x, or an empty slice if x was nil.
288 //
289 // (Many slice fields of protocol structs must be non-nil
290 // to avoid being encoded as JSON "null".)
291 func NonNilSlice[T comparable](x []T) []T {
292 if x == nil {
293 return []T{}
294 }
295 return x
296 }