Debian Codegraph @

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