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