Debian Codegraph @

internal/jsonrpc2/conn.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 jsonrpc2
6
7 import (
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "sync"
13 "sync/atomic"
14 "time"
15
16 "golang.org/x/tools/internal/event"
17 "golang.org/x/tools/internal/event/label"
18 )
19
20 // Conn is the common interface to jsonrpc clients and servers.
21 // Conn is bidirectional; it does not have a designated server or client end.
22 // It manages the jsonrpc2 protocol, connecting responses back to their calls.
23 type Conn interface {
24 // Call invokes the target method and waits for a response.
25 // The params will be marshaled to JSON before sending over the wire, and will
26 // be handed to the method invoked.
27 // The response will be unmarshaled from JSON into the result.
28 // The id returned will be unique from this connection, and can be used for
29 // logging or tracking.
30 Call(ctx context.Context, method string, params, result any) (ID, error)
31
32 // Notify invokes the target method but does not wait for a response.
33 // The params will be marshaled to JSON before sending over the wire, and will
34 // be handed to the method invoked.
35 Notify(ctx context.Context, method string, params any) error
36
37 // Go starts a goroutine to handle the connection.
38 // It must be called exactly once for each Conn.
39 // It returns immediately.
40 // You must block on Done() to wait for the connection to shut down.
41 // This is a temporary measure, this should be started automatically in the
42 // future.
43 Go(ctx context.Context, handler Handler)
44
45 // Close closes the connection and it's underlying stream.
46 // It does not wait for the close to complete, use the Done() channel for
47 // that.
48 Close() error
49
50 // Done returns a channel that will be closed when the processing goroutine
51 // has terminated, which will happen if Close() is called or an underlying
52 // stream is closed.
53 Done() <-chan struct{}
54
55 // Err returns an error if there was one from within the processing goroutine.
56 // If err returns non nil, the connection will be already closed or closing.
57 Err() error
58 }
59
60 type conn struct {
61 seq atomic.Int64 // must only be accessed using atomic operations
62 writeMu sync.Mutex // protects writes to the stream
63 stream Stream
64 pendingMu sync.Mutex // protects the pending map
65 pending map[ID]chan *Response
66
67 done chan struct{}
68 err atomic.Value
69 }
70
71 // NewConn creates a new connection object around the supplied stream.
72 func NewConn(s Stream) Conn {
73 conn := &conn{
74 stream: s,
75 pending: make(map[ID]chan *Response),
76 done: make(chan struct{}),
77 }
78 return conn
79 }
80
81 func (c *conn) Notify(ctx context.Context, method string, params any) (err error) {
82 notify, err := NewNotification(method, params)
83 if err != nil {
84 return fmt.Errorf("marshaling notify parameters: %v", err)
85 }
86 ctx, done := event.Start(ctx, method,
87 Method.Of(method),
88 RPCDirection.Of(Outbound),
89 )
90 start := time.Now()
91 defer func() {
92 ctx = recordStatus(ctx, err)
93 event.Metric(ctx, Latency.Of(time.Since(start).Seconds()))
94 done()
95 }()
96
97 event.Metric(ctx, Started.Of(1))
98 n, err := c.write(ctx, notify)
99 event.Metric(ctx, SentBytes.Of64(n))
100 return err
101 }
102
103 func (c *conn) Call(ctx context.Context, method string, params, result any) (_ ID, err error) {
104 // generate a new request identifier
105 id := ID{number: c.seq.Add(1)}
106 call, err := NewCall(id, method, params)
107 if err != nil {
108 return id, fmt.Errorf("marshaling call parameters: %v", err)
109 }
110 ctx, done := event.Start(ctx, method,
111 Method.Of(method),
112 RPCDirection.Of(Outbound),
113 RPCID.Of(fmt.Sprintf("%q", id)),
114 )
115 start := time.Now()
116 var rpcErr error
117 defer func() {
118 ctx = recordStatus(ctx, rpcErr)
119 event.Metric(ctx, Latency.Of(time.Since(start).Seconds()))
120 done()
121 }()
122 event.Metric(ctx, Started.Of(1))
123 // We have to add ourselves to the pending map before we send, otherwise we
124 // are racing the response. Also add a buffer to rchan, so that if we get a
125 // wire response between the time this call is cancelled and id is deleted
126 // from c.pending, the send to rchan will not block.
127 rchan := make(chan *Response, 1)
128 c.pendingMu.Lock()
129 c.pending[id] = rchan
130 c.pendingMu.Unlock()
131 defer func() {
132 c.pendingMu.Lock()
133 delete(c.pending, id)
134 c.pendingMu.Unlock()
135 }()
136 // now we are ready to send
137 n, err := c.write(ctx, call)
138 event.Metric(ctx, SentBytes.Of64(n))
139 if err != nil {
140 // sending failed, we will never get a response, so don't leave it pending
141 return id, err
142 }
143 // now wait for the response
144 select {
145 case response := <-rchan:
146 // is it an error response?
147 if response.err != nil {
148 rpcErr = response.err
149 return id, response.err
150 }
151 if result == nil || len(response.result) == 0 {
152 return id, nil
153 }
154 if err := json.Unmarshal(response.result, result); err != nil {
155 return id, fmt.Errorf("unmarshaling result: %v", err)
156 }
157 return id, nil
158 case <-ctx.Done():
159 rpcErr = ctx.Err()
160 return id, ctx.Err()
161 }
162 }
163
164 func (c *conn) replier(req Request, start time.Time, spanDone func()) Replier {
165 return func(ctx context.Context, result any, err error) error {
166 // Save the RPC error before err gets reassigned by NewResponse/write below.
167 rpcErr := err
168 defer func() {
169 ctx = recordStatus(ctx, rpcErr)
170 event.Metric(ctx, Latency.Of(time.Since(start).Seconds()))
171 spanDone()
172 }()
173 call, ok := req.(*Call)
174 if !ok {
175 // request was a notify, no need to respond
176 return nil
177 }
178 response, err := NewResponse(call.id, result, err)
179 if err != nil {
180 return err
181 }
182 n, err := c.write(ctx, response)
183 event.Metric(ctx, SentBytes.Of64(n))
184 if err != nil {
185 // TODO(iancottrell): if a stream write fails, we really need to shut down
186 // the whole stream
187 return err
188 }
189 return nil
190 }
191 }
192
193 func (c *conn) write(ctx context.Context, msg Message) (int64, error) {
194 c.writeMu.Lock()
195 defer c.writeMu.Unlock()
196 return c.stream.Write(ctx, msg)
197 }
198
199 func (c *conn) Go(ctx context.Context, handler Handler) {
200 go c.run(ctx, handler)
201 }
202
203 func (c *conn) run(ctx context.Context, handler Handler) {
204 defer close(c.done)
205 for {
206 // get the next message
207 msg, n, err := c.stream.Read(ctx)
208 if err != nil {
209 // The stream failed, we cannot continue.
210 c.fail(err)
211 return
212 }
213 switch msg := msg.(type) {
214 case Request:
215 labels := []label.Label{
216 Method.Of(msg.Method()),
217 RPCDirection.Of(Inbound),
218 {}, // reserved for ID if present
219 }
220 if call, ok := msg.(*Call); ok {
221 labels[len(labels)-1] = RPCID.Of(fmt.Sprintf("%q", call.ID()))
222 } else {
223 labels = labels[:len(labels)-1]
224 }
225 reqCtx, spanDone := event.Start(ctx, msg.Method(), labels...)
226 start := time.Now()
227 event.Metric(reqCtx,
228 Started.Of(1),
229 ReceivedBytes.Of64(n))
230 if err := handler(reqCtx, c.replier(msg, start, spanDone), msg); err != nil {
231 // delivery failed, not much we can do
232 event.Error(reqCtx, "jsonrpc2 message delivery failed", err)
233 }
234 case *Response:
235 // If method is not set, this should be a response, in which case we must
236 // have an id to send the response back to the caller.
237 c.pendingMu.Lock()
238 rchan, ok := c.pending[msg.id]
239 c.pendingMu.Unlock()
240 if ok {
241 rchan <- msg
242 }
243 }
244 }
245 }
246
247 func (c *conn) Close() error {
248 return c.stream.Close()
249 }
250
251 func (c *conn) Done() <-chan struct{} {
252 return c.done
253 }
254
255 func (c *conn) Err() error {
256 if err := c.err.Load(); err != nil {
257 return err.(error)
258 }
259 return nil
260 }
261
262 // fail sets a failure condition on the stream and closes it.
263 func (c *conn) fail(err error) {
264 c.err.Store(err)
265 c.stream.Close()
266 }
267
268 func recordStatus(ctx context.Context, err error) context.Context {
269 var status string
270 var wireError *WireError
271 switch {
272 case err == nil:
273 status = "OK"
274 case errors.Is(err, context.Canceled):
275 status = "CANCELED"
276 case errors.As(err, &wireError) && wireError.Code == -32800: // JSON RPC request canceled
277 status = "CANCELED"
278 case errors.Is(err, context.DeadlineExceeded):
279 status = "DEADLINE_EXCEEDED"
280 case errors.Is(err, ErrMethodNotFound):
281 status = "METHOD_NOT_FOUND"
282 default:
283 status = "ERROR"
284 }
285 return event.Label(ctx, StatusCode.Of(status))
286 }