Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2/conn.go

raw symbols SCIP
1 // Copyright 2018 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package jsonrpc2
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "io"
12 "sync"
13 "sync/atomic"
14 "time"
15
16 "github.com/modelcontextprotocol/go-sdk/internal/json"
17 )
18
19 // Connection manages the jsonrpc2 protocol, connecting responses back to their
20 // calls. Connection is bidirectional; it does not have a designated server or
21 // client end.
22 //
23 // Note that the word 'Connection' is overloaded: the mcp.Connection represents
24 // the bidirectional stream of messages between client an server. The
25 // jsonrpc2.Connection layers RPC logic on top of that stream, dispatching RPC
26 // handlers, and correlating requests with responses from the peer.
27 //
28 // Some of the complexity of the Connection type is grown out of its usage in
29 // gopls: it could probably be simplified based on our usage in MCP.
30 type Connection struct {
31 seq int64 // must only be accessed using atomic operations
32
33 stateMu sync.Mutex
34 state inFlightState // accessed only in updateInFlight
35 done chan struct{} // closed (under stateMu) when state.closed is true and all goroutines have completed
36
37 writer Writer
38 handler Handler
39
40 onInternalError func(error)
41 onDone func()
42 }
43
44 // inFlightState records the state of the incoming and outgoing calls on a
45 // Connection.
46 type inFlightState struct {
47 connClosing bool // true when the Connection's Close method has been called
48 reading bool // true while the readIncoming goroutine is running
49 readErr error // non-nil when the readIncoming goroutine exits (typically io.EOF)
50 writeErr error // non-nil if a call to the Writer has failed with a non-canceled Context
51
52 // closer shuts down and cleans up the Reader and Writer state, ideally
53 // interrupting any Read or Write call that is currently blocked. It is closed
54 // when the state is idle and one of: connClosing is true, readErr is non-nil,
55 // or writeErr is non-nil.
56 //
57 // After the closer has been invoked, the closer field is set to nil
58 // and the closeErr field is simultaneously set to its result.
59 closer io.Closer
60 closeErr error // error returned from closer.Close
61
62 outgoingCalls map[ID]*AsyncCall // calls only
63 outgoingNotifications int // # of notifications awaiting "write"
64
65 // incoming stores the total number of incoming calls and notifications
66 // that have not yet written or processed a result.
67 incoming int
68
69 incomingByID map[ID]*incomingRequest // calls only
70
71 // handlerQueue stores the backlog of calls and notifications that were not
72 // already handled by a preempter.
73 // The queue does not include the request currently being handled (if any).
74 handlerQueue []*incomingRequest
75 handlerRunning bool
76 }
77
78 // updateInFlight locks the state of the connection's in-flight requests, allows
79 // f to mutate that state, and closes the connection if it is idle and either
80 // is closing or has a read or write error.
81 func (c *Connection) updateInFlight(f func(*inFlightState)) {
82 c.stateMu.Lock()
83 defer c.stateMu.Unlock()
84
85 s := &c.state
86
87 f(s)
88
89 select {
90 case <-c.done:
91 // The connection was already completely done at the start of this call to
92 // updateInFlight, so it must remain so. (The call to f should have noticed
93 // that and avoided making any updates that would cause the state to be
94 // non-idle.)
95 if !s.idle() {
96 panic("jsonrpc2: updateInFlight transitioned to non-idle when already done")
97 }
98 return
99 default:
100 }
101
102 if s.idle() && s.shuttingDown(ErrUnknown) != nil {
103 if s.closer != nil {
104 s.closeErr = s.closer.Close()
105 s.closer = nil // prevent duplicate Close calls
106 }
107 if s.reading {
108 // The readIncoming goroutine is still running. Our call to Close should
109 // cause it to exit soon, at which point it will make another call to
110 // updateInFlight, set s.reading to false, and mark the Connection done.
111 } else {
112 // The readIncoming goroutine has exited, or never started to begin with.
113 // Since everything else is idle, we're completely done.
114 if c.onDone != nil {
115 c.onDone()
116 }
117 close(c.done)
118 }
119 }
120 }
121
122 // idle reports whether the connection is in a state with no pending calls or
123 // notifications.
124 //
125 // If idle returns true, the readIncoming goroutine may still be running,
126 // but no other goroutines are doing work on behalf of the connection.
127 func (s *inFlightState) idle() bool {
128 return len(s.outgoingCalls) == 0 && s.outgoingNotifications == 0 && s.incoming == 0 && !s.handlerRunning
129 }
130
131 // shuttingDown reports whether the connection is in a state that should
132 // disallow new (incoming and outgoing) calls. It returns either nil or
133 // an error that is or wraps the provided errClosing.
134 func (s *inFlightState) shuttingDown(errClosing error) error {
135 if s.connClosing {
136 // If Close has been called explicitly, it doesn't matter what state the
137 // Reader and Writer are in: we shouldn't be starting new work because the
138 // caller told us not to start new work.
139 return errClosing
140 }
141 if s.readErr != nil {
142 // If the read side of the connection is broken, we cannot read new call
143 // requests, and cannot read responses to our outgoing calls.
144 return fmt.Errorf("%w: %v", errClosing, s.readErr)
145 }
146 if s.writeErr != nil {
147 // If the write side of the connection is broken, we cannot write responses
148 // for incoming calls, and cannot write requests for outgoing calls.
149 return fmt.Errorf("%w: %v", errClosing, s.writeErr)
150 }
151 return nil
152 }
153
154 // incomingRequest is used to track an incoming request as it is being handled
155 type incomingRequest struct {
156 *Request // the request being processed
157 ctx context.Context
158 cancel context.CancelFunc
159 }
160
161 // Reader abstracts the transport mechanics from the JSON RPC protocol.
162 // A Connection reads messages from the reader it was provided on construction,
163 // and assumes that each call to Read fully transfers a single message,
164 // or returns an error.
165 //
166 // A reader is not safe for concurrent use, it is expected it will be used by
167 // a single Connection in a safe manner.
168 type Reader interface {
169 // Read gets the next message from the stream.
170 Read(context.Context) (Message, error)
171 }
172
173 // Writer abstracts the transport mechanics from the JSON RPC protocol.
174 // A Connection writes messages using the writer it was provided on construction,
175 // and assumes that each call to Write fully transfers a single message,
176 // or returns an error.
177 //
178 // A writer must be safe for concurrent use, as writes may occur concurrently
179 // in practice: libraries may make calls or respond to requests asynchronously.
180 type Writer interface {
181 // Write sends a message to the stream.
182 Write(context.Context, Message) error
183 }
184
185 // A ConnectionConfig configures a bidirectional jsonrpc2 connection.
186 type ConnectionConfig struct {
187 Reader Reader // required
188 Writer Writer // required
189 Closer io.Closer // required
190 Preempter Preempter // optional
191 Bind func(*Connection) Handler // required
192 OnDone func() // optional
193 OnInternalError func(error) // optional
194 }
195
196 // NewConnection creates a new [Connection] object and starts processing
197 // incoming messages.
198 func NewConnection(ctx context.Context, cfg ConnectionConfig) *Connection {
199 ctx = notDone{ctx}
200
201 c := &Connection{
202 state: inFlightState{closer: cfg.Closer},
203 done: make(chan struct{}),
204 writer: cfg.Writer,
205 onDone: cfg.OnDone,
206 onInternalError: cfg.OnInternalError,
207 }
208 c.handler = cfg.Bind(c)
209 c.start(ctx, cfg.Reader, cfg.Preempter)
210 return c
211 }
212
213 func (c *Connection) start(ctx context.Context, reader Reader, preempter Preempter) {
214 c.updateInFlight(func(s *inFlightState) {
215 select {
216 case <-c.done:
217 // The connection was already closed; don't start a goroutine to read it.
218 return
219 default:
220 }
221
222 // The goroutine started here will continue until the underlying stream is closed.
223 s.reading = true
224 go c.readIncoming(ctx, reader, preempter)
225 })
226 }
227
228 // Notify invokes the target method but does not wait for a response.
229 // The params will be marshaled to JSON before sending over the wire, and will
230 // be handed to the method invoked.
231 func (c *Connection) Notify(ctx context.Context, method string, params any) (err error) {
232 attempted := false
233
234 defer func() {
235 if attempted {
236 c.updateInFlight(func(s *inFlightState) {
237 s.outgoingNotifications--
238 })
239 }
240 }()
241
242 c.updateInFlight(func(s *inFlightState) {
243 // If the connection is shutting down, allow outgoing notifications only if
244 // there is at least one call still in flight. The number of calls in flight
245 // cannot increase once shutdown begins, and allowing outgoing notifications
246 // may permit notifications that will cancel in-flight calls.
247 if len(s.outgoingCalls) == 0 && len(s.incomingByID) == 0 {
248 err = s.shuttingDown(ErrClientClosing)
249 if err != nil {
250 return
251 }
252 }
253 s.outgoingNotifications++
254 attempted = true
255 })
256 if err != nil {
257 return err
258 }
259
260 notify, err := NewNotification(method, params)
261 if err != nil {
262 return fmt.Errorf("marshaling notify parameters: %v", err)
263 }
264
265 return c.write(ctx, notify)
266 }
267
268 // Call invokes the target method and returns an object that can be used to await the response.
269 // The params will be marshaled to JSON before sending over the wire, and will
270 // be handed to the method invoked.
271 // You do not have to wait for the response, it can just be ignored if not needed.
272 // If sending the call failed, the response will be ready and have the error in it.
273 func (c *Connection) Call(ctx context.Context, method string, params any) *AsyncCall {
274 // Generate a new request identifier.
275 id := Int64ID(atomic.AddInt64(&c.seq, 1))
276
277 ac := &AsyncCall{
278 id: id,
279 ready: make(chan struct{}),
280 }
281 // When this method returns, either ac is retired, or the request has been
282 // written successfully and the call is awaiting a response (to be provided by
283 // the readIncoming goroutine).
284
285 call, err := NewCall(ac.id, method, params)
286 if err != nil {
287 ac.retire(&Response{ID: id, Error: fmt.Errorf("marshaling call parameters: %w", err)})
288 return ac
289 }
290
291 c.updateInFlight(func(s *inFlightState) {
292 err = s.shuttingDown(ErrClientClosing)
293 if err != nil {
294 return
295 }
296 if s.outgoingCalls == nil {
297 s.outgoingCalls = make(map[ID]*AsyncCall)
298 }
299 s.outgoingCalls[ac.id] = ac
300 })
301 if err != nil {
302 ac.retire(&Response{ID: id, Error: err})
303 return ac
304 }
305
306 if err := c.write(ctx, call); err != nil {
307 // Sending failed. We will never get a response, so deliver a fake one if it
308 // wasn't already retired by the connection breaking.
309 c.Retire(ac, err)
310 }
311 return ac
312 }
313
314 // Retire stops tracking the call, and reports err as its terminal error.
315 //
316 // Retire is safe to call multiple times: if the call is already no longer
317 // tracked, Retire is a no op.
318 func (c *Connection) Retire(ac *AsyncCall, err error) {
319 c.updateInFlight(func(s *inFlightState) {
320 if s.outgoingCalls[ac.id] == ac {
321 delete(s.outgoingCalls, ac.id)
322 ac.retire(&Response{ID: ac.id, Error: err})
323 } else {
324 // ac was already retired elsewhere.
325 }
326 })
327 }
328
329 // Async, signals that the current jsonrpc2 request may be handled
330 // asynchronously to subsequent requests, when ctx is the request context.
331 //
332 // Async must be called at most once on each request's context (and its
333 // descendants).
334 func Async(ctx context.Context) {
335 if r, ok := ctx.Value(asyncKey).(*releaser); ok {
336 r.release(false)
337 }
338 }
339
340 type asyncKeyType struct{}
341
342 var asyncKey = asyncKeyType{}
343
344 // A releaser implements concurrency safe 'releasing' of async requests. (A
345 // request is released when it is allowed to run concurrent with other
346 // requests, via a call to [Async].)
347 type releaser struct {
348 mu sync.Mutex
349 ch chan struct{}
350 released bool
351 }
352
353 // release closes the associated channel. If soft is set, multiple calls to
354 // release are allowed.
355 func (r *releaser) release(soft bool) {
356 r.mu.Lock()
357 defer r.mu.Unlock()
358
359 if r.released {
360 if !soft {
361 panic("jsonrpc2.Async called multiple times")
362 }
363 } else {
364 close(r.ch)
365 r.released = true
366 }
367 }
368
369 type AsyncCall struct {
370 id ID
371 ready chan struct{} // closed after response has been set
372 response *Response
373 }
374
375 // ID used for this call.
376 // This can be used to cancel the call if needed.
377 func (ac *AsyncCall) ID() ID { return ac.id }
378
379 // retire processes the response to the call.
380 //
381 // It is an error to call retire more than once: retire is guarded by the
382 // connection's outgoingCalls map.
383 func (ac *AsyncCall) retire(response *Response) {
384 select {
385 case <-ac.ready:
386 panic(fmt.Sprintf("jsonrpc2: retire called twice for ID %v", ac.id))
387 default:
388 }
389
390 ac.response = response
391 close(ac.ready)
392 }
393
394 // Await waits for (and decodes) the results of a Call.
395 // The response will be unmarshaled from JSON into the result.
396 //
397 // If the call is cancelled due to context cancellation, the result is
398 // ctx.Err().
399 func (ac *AsyncCall) Await(ctx context.Context, result any) error {
400 select {
401 case <-ctx.Done():
402 return ctx.Err()
403 case <-ac.ready:
404 }
405 if ac.response.Error != nil {
406 return ac.response.Error
407 }
408 if result == nil {
409 return nil
410 }
411 return json.Unmarshal(ac.response.Result, result)
412 }
413
414 // Cancel cancels the Context passed to the Handle call for the inbound message
415 // with the given ID.
416 //
417 // Cancel will not complain if the ID is not a currently active message, and it
418 // will not cause any messages that have not arrived yet with that ID to be
419 // cancelled.
420 func (c *Connection) Cancel(id ID) {
421 var req *incomingRequest
422 c.updateInFlight(func(s *inFlightState) {
423 req = s.incomingByID[id]
424 })
425 if req != nil {
426 req.cancel()
427 }
428 }
429
430 // Wait blocks until the connection is fully closed, but does not close it.
431 func (c *Connection) Wait() error {
432 return c.wait(true)
433 }
434
435 // wait for the connection to close, and aggregates the most cause of its
436 // termination, if abnormal.
437 //
438 // The fromWait argument allows this logic to be shared with Close, where we
439 // only want to expose the closeErr.
440 //
441 // (Previously, Wait also only returned the closeErr, which was misleading if
442 // the connection was broken for another reason).
443 func (c *Connection) wait(fromWait bool) error {
444 var err error
445 <-c.done
446 c.updateInFlight(func(s *inFlightState) {
447 if fromWait {
448 if !errors.Is(s.readErr, io.EOF) {
449 err = s.readErr
450 }
451 if err == nil && !errors.Is(s.writeErr, io.EOF) {
452 err = s.writeErr
453 }
454 }
455 if err == nil {
456 err = s.closeErr
457 }
458 })
459 return err
460 }
461
462 // Close stops accepting new requests, waits for in-flight requests and enqueued
463 // Handle calls to complete, and then closes the underlying stream.
464 //
465 // After the start of a Close, notification requests (that lack IDs and do not
466 // receive responses) will continue to be passed to the Preempter, but calls
467 // with IDs will receive immediate responses with ErrServerClosing, and no new
468 // requests (not even notifications!) will be enqueued to the Handler.
469 func (c *Connection) Close() error {
470 // Stop handling new requests, and interrupt the reader (by closing the
471 // connection) as soon as the active requests finish.
472 c.updateInFlight(func(s *inFlightState) { s.connClosing = true })
473 return c.wait(false)
474 }
475
476 // readIncoming collects inbound messages from the reader and delivers them, either responding
477 // to outgoing calls or feeding requests to the queue.
478 func (c *Connection) readIncoming(ctx context.Context, reader Reader, preempter Preempter) {
479 var err error
480 for {
481 var msg Message
482 msg, err = reader.Read(ctx)
483 if err != nil {
484 break
485 }
486
487 switch msg := msg.(type) {
488 case *Request:
489 c.acceptRequest(ctx, msg, preempter)
490
491 case *Response:
492 c.updateInFlight(func(s *inFlightState) {
493 if ac, ok := s.outgoingCalls[msg.ID]; ok {
494 delete(s.outgoingCalls, msg.ID)
495 ac.retire(msg)
496 } else {
497 // TODO: How should we report unexpected responses?
498 }
499 })
500
501 default:
502 c.internalErrorf("Read returned an unexpected message of type %T", msg)
503 }
504 }
505
506 c.updateInFlight(func(s *inFlightState) {
507 s.reading = false
508 s.readErr = err
509
510 // Retire any outgoing requests that were still in flight: with the Reader no
511 // longer being processed, they necessarily cannot receive a response.
512 for id, ac := range s.outgoingCalls {
513 ac.retire(&Response{ID: id, Error: err})
514 }
515 s.outgoingCalls = nil
516 })
517 }
518
519 // acceptRequest either handles msg synchronously or enqueues it to be handled
520 // asynchronously.
521 func (c *Connection) acceptRequest(ctx context.Context, msg *Request, preempter Preempter) {
522 // In theory notifications cannot be cancelled, but we build them a cancel
523 // context anyway.
524 reqCtx, cancel := context.WithCancel(ctx)
525 req := &incomingRequest{
526 Request: msg,
527 ctx: reqCtx,
528 cancel: cancel,
529 }
530
531 // If the request is a call, add it to the incoming map so it can be
532 // cancelled (or responded) by ID.
533 var err error
534 c.updateInFlight(func(s *inFlightState) {
535 s.incoming++
536
537 if req.IsCall() {
538 if s.incomingByID[req.ID] != nil {
539 err = fmt.Errorf("%w: request ID %v already in use", ErrInvalidRequest, req.ID)
540 req.ID = ID{} // Don't misattribute this error to the existing request.
541 return
542 }
543
544 if s.incomingByID == nil {
545 s.incomingByID = make(map[ID]*incomingRequest)
546 }
547 s.incomingByID[req.ID] = req
548
549 // When shutting down, reject all new Call requests, even if they could
550 // theoretically be handled by the preempter. The preempter could return
551 // ErrAsyncResponse, which would increase the amount of work in flight
552 // when we're trying to ensure that it strictly decreases.
553 err = s.shuttingDown(ErrServerClosing)
554 }
555 })
556 if err != nil {
557 c.processResult("acceptRequest", req, nil, err)
558 return
559 }
560
561 if preempter != nil {
562 result, err := preempter.Preempt(req.ctx, req.Request)
563
564 if !errors.Is(err, ErrNotHandled) {
565 c.processResult("Preempt", req, result, err)
566 return
567 }
568 }
569
570 c.updateInFlight(func(s *inFlightState) {
571 // If the connection is shutting down, don't enqueue anything to the
572 // handler — not even notifications. That ensures that if the handler
573 // continues to make progress, it will eventually become idle and
574 // close the connection.
575 err = s.shuttingDown(ErrServerClosing)
576 if err != nil {
577 return
578 }
579
580 // We enqueue requests that have not been preempted to an unbounded slice.
581 // Unfortunately, we cannot in general limit the size of the handler
582 // queue: we have to read every response that comes in on the wire
583 // (because it may be responding to a request issued by, say, an
584 // asynchronous handler), and in order to get to that response we have
585 // to read all of the requests that came in ahead of it.
586 s.handlerQueue = append(s.handlerQueue, req)
587 if !s.handlerRunning {
588 // We start the handleAsync goroutine when it has work to do, and let it
589 // exit when the queue empties.
590 //
591 // Otherwise, in order to synchronize the handler we would need some other
592 // goroutine (probably readIncoming?) to explicitly wait for handleAsync
593 // to finish, and that would complicate error reporting: either the error
594 // report from the goroutine would be blocked on the handler emptying its
595 // queue (which was tried, and introduced a deadlock detected by
596 // TestCloseCallRace), or the error would need to be reported separately
597 // from synchronizing completion. Allowing the handler goroutine to exit
598 // when idle seems simpler than trying to implement either of those
599 // alternatives correctly.
600 s.handlerRunning = true
601 go c.handleAsync()
602 }
603 })
604 if err != nil {
605 c.processResult("acceptRequest", req, nil, err)
606 }
607 }
608
609 // handleAsync invokes the handler on the requests in the handler queue
610 // sequentially until the queue is empty.
611 func (c *Connection) handleAsync() {
612 for {
613 var req *incomingRequest
614 c.updateInFlight(func(s *inFlightState) {
615 if len(s.handlerQueue) > 0 {
616 req, s.handlerQueue = s.handlerQueue[0], s.handlerQueue[1:]
617 } else {
618 s.handlerRunning = false
619 }
620 })
621 if req == nil {
622 return
623 }
624
625 // Only deliver to the Handler if not already canceled.
626 if err := req.ctx.Err(); err != nil {
627 c.updateInFlight(func(s *inFlightState) {
628 if s.writeErr != nil {
629 // Assume that req.ctx was canceled due to s.writeErr.
630 // TODO(#51365): use a Context API to plumb this through req.ctx.
631 err = fmt.Errorf("%w: %v", ErrServerClosing, s.writeErr)
632 }
633 })
634 c.processResult("handleAsync", req, nil, err)
635 continue
636 }
637
638 releaser := &releaser{ch: make(chan struct{})}
639 ctx := context.WithValue(req.ctx, asyncKey, releaser)
640 go func() {
641 defer releaser.release(true)
642 result, err := c.handler.Handle(ctx, req.Request)
643 c.processResult(c.handler, req, result, err)
644 }()
645 <-releaser.ch
646 }
647 }
648
649 // processResult processes the result of a request and, if appropriate, sends a response.
650 func (c *Connection) processResult(from any, req *incomingRequest, result any, err error) error {
651 switch err {
652 case ErrNotHandled, ErrMethodNotFound:
653 // Add detail describing the unhandled method.
654 err = fmt.Errorf("%w: %q", ErrMethodNotFound, req.Method)
655 }
656
657 if result != nil && err != nil {
658 c.internalErrorf("%#v returned a non-nil result with a non-nil error for %s:\n%v\n%#v", from, req.Method, err, result)
659 result = nil // Discard the spurious result and respond with err.
660 }
661
662 if req.IsCall() {
663 if result == nil && err == nil {
664 err = c.internalErrorf("%#v returned a nil result and nil error for a %q Request that requires a Response", from, req.Method)
665 }
666
667 response, respErr := NewResponse(req.ID, result, err)
668
669 // The caller could theoretically reuse the request's ID as soon as we've
670 // sent the response, so ensure that it is removed from the incoming map
671 // before sending.
672 c.updateInFlight(func(s *inFlightState) {
673 delete(s.incomingByID, req.ID)
674 })
675 if respErr == nil {
676 writeErr := c.write(notDone{req.ctx}, response)
677 if err == nil {
678 err = writeErr
679 }
680 } else {
681 err = c.internalErrorf("%#v returned a malformed result for %q: %w", from, req.Method, respErr)
682 }
683 } else { // req is a notification
684 if result != nil {
685 err = c.internalErrorf("%#v returned a non-nil result for a %q Request without an ID", from, req.Method)
686 } else if err != nil {
687 err = fmt.Errorf("%w: %q notification failed: %v", ErrInternal, req.Method, err)
688 }
689 }
690 if err != nil {
691 // TODO: can/should we do anything with this error beyond writing it to the event log?
692 // (Is this the right label to attach to the log?)
693 }
694
695 // Cancel the request to free any associated resources.
696 req.cancel()
697 c.updateInFlight(func(s *inFlightState) {
698 if s.incoming == 0 {
699 panic("jsonrpc2: processResult called when incoming count is already zero")
700 }
701 s.incoming--
702 })
703 return nil
704 }
705
706 // write is used by all things that write outgoing messages, including replies.
707 // it makes sure that writes are atomic
708 func (c *Connection) write(ctx context.Context, msg Message) error {
709 var err error
710 // Fail writes immediately if the connection is shutting down.
711 //
712 // TODO(rfindley): should we allow cancellation notifications through? It
713 // could be the case that writes can still succeed.
714 c.updateInFlight(func(s *inFlightState) {
715 err = s.shuttingDown(ErrServerClosing)
716 })
717 if err == nil {
718 err = c.writer.Write(ctx, msg)
719 }
720
721 // For cancelled or rejected requests, we don't set the writeErr (which would
722 // break the connection). They can just be returned to the caller.
723 if err != nil && ctx.Err() == nil && !errors.Is(err, ErrRejected) {
724 // The call to Write failed, and since ctx.Err() is nil we can't attribute
725 // the failure (even indirectly) to Context cancellation. The writer appears
726 // to be broken, and future writes are likely to also fail.
727 //
728 // If the read side of the connection is also broken, we might not even be
729 // able to receive cancellation notifications. Since we can't reliably write
730 // the results of incoming calls and can't receive explicit cancellations,
731 // cancel the calls now.
732 c.updateInFlight(func(s *inFlightState) {
733 if s.writeErr == nil {
734 s.writeErr = err
735 for _, r := range s.incomingByID {
736 r.cancel()
737 }
738 }
739 })
740 }
741
742 return err
743 }
744
745 // internalErrorf reports an internal error. By default it panics, but if
746 // c.onInternalError is non-nil it instead calls that and returns an error
747 // wrapping ErrInternal.
748 func (c *Connection) internalErrorf(format string, args ...any) error {
749 err := fmt.Errorf(format, args...)
750 if c.onInternalError == nil {
751 panic("jsonrpc2: " + err.Error())
752 }
753 c.onInternalError(err)
754
755 return fmt.Errorf("%w: %v", ErrInternal, err)
756 }
757
758 // notDone is a context.Context wrapper that returns a nil Done channel.
759 type notDone struct{ ctx context.Context }
760
761 func (ic notDone) Value(key any) any {
762 return ic.ctx.Value(key)
763 }
764
765 func (notDone) Done() <-chan struct{} { return nil }
766 func (notDone) Err() error { return nil }
767 func (notDone) Deadline() (time.Time, bool) { return time.Time{}, false }