| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package jsonrpc2 |
| 6 |
|
| 7 |
import ( |
| 8 |
"context" |
| 9 |
"encoding/json" |
| 10 |
"fmt" |
| 11 |
"io" |
| 12 |
"sync/atomic" |
| 13 |
|
| 14 |
"golang.org/x/exp/event" |
| 15 |
errors "golang.org/x/xerrors" |
| 16 |
) |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
type Binder interface { |
| 23 |
|
| 24 |
|
| 25 |
Bind(context.Context, *Connection) (ConnectionOptions, error) |
| 26 |
} |
| 27 |
|
| 28 |
|
| 29 |
type ConnectionOptions struct { |
| 30 |
|
| 31 |
|
| 32 |
Framer Framer |
| 33 |
|
| 34 |
|
| 35 |
Preempter Preempter |
| 36 |
|
| 37 |
|
| 38 |
Handler Handler |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
type Connection struct { |
| 46 |
seq int64 |
| 47 |
closer io.Closer |
| 48 |
writerBox chan Writer |
| 49 |
outgoingBox chan map[ID]chan<- *Response |
| 50 |
incomingBox chan map[ID]*incoming |
| 51 |
async async |
| 52 |
} |
| 53 |
|
| 54 |
type AsyncCall struct { |
| 55 |
id ID |
| 56 |
response chan *Response |
| 57 |
resultBox chan asyncResult |
| 58 |
ctx context.Context |
| 59 |
} |
| 60 |
|
| 61 |
type asyncResult struct { |
| 62 |
result []byte |
| 63 |
err error |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
type incoming struct { |
| 68 |
request *Request |
| 69 |
baseCtx context.Context |
| 70 |
handleCtx context.Context |
| 71 |
cancel func() |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
func (o ConnectionOptions) Bind(context.Context, *Connection) (ConnectionOptions, error) { |
| 76 |
return o, nil |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
func newConnection(ctx context.Context, rwc io.ReadWriteCloser, binder Binder) (*Connection, error) { |
| 82 |
c := &Connection{ |
| 83 |
closer: rwc, |
| 84 |
writerBox: make(chan Writer, 1), |
| 85 |
outgoingBox: make(chan map[ID]chan<- *Response, 1), |
| 86 |
incomingBox: make(chan map[ID]*incoming, 1), |
| 87 |
} |
| 88 |
c.async.init() |
| 89 |
|
| 90 |
options, err := binder.Bind(ctx, c) |
| 91 |
if err != nil { |
| 92 |
return nil, err |
| 93 |
} |
| 94 |
if options.Framer == nil { |
| 95 |
options.Framer = HeaderFramer() |
| 96 |
} |
| 97 |
if options.Preempter == nil { |
| 98 |
options.Preempter = defaultHandler{} |
| 99 |
} |
| 100 |
if options.Handler == nil { |
| 101 |
options.Handler = defaultHandler{} |
| 102 |
} |
| 103 |
c.outgoingBox <- make(map[ID]chan<- *Response) |
| 104 |
c.incomingBox <- make(map[ID]*incoming) |
| 105 |
|
| 106 |
reader := options.Framer.Reader(rwc) |
| 107 |
readToQueue := make(chan *incoming) |
| 108 |
queueToDeliver := make(chan *incoming) |
| 109 |
go c.readIncoming(ctx, reader, readToQueue) |
| 110 |
go c.manageQueue(ctx, options.Preempter, readToQueue, queueToDeliver) |
| 111 |
go c.deliverMessages(ctx, options.Handler, queueToDeliver) |
| 112 |
|
| 113 |
|
| 114 |
c.writerBox <- options.Framer.Writer(rwc) |
| 115 |
return c, nil |
| 116 |
} |
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
func (c *Connection) Notify(ctx context.Context, method string, params interface{}) error { |
| 122 |
notify, err := NewNotification(method, params) |
| 123 |
if err != nil { |
| 124 |
return errors.Errorf("marshaling notify parameters: %v", err) |
| 125 |
} |
| 126 |
ctx = event.Start(ctx, method, RPCDirection(Outbound)) |
| 127 |
Started.Record(ctx, 1, Method(method)) |
| 128 |
var errLabel event.Label |
| 129 |
if err = c.write(ctx, notify); err != nil { |
| 130 |
errLabel = event.Value("error", err) |
| 131 |
} |
| 132 |
Finished.Record(ctx, 1, errLabel) |
| 133 |
event.End(ctx) |
| 134 |
return err |
| 135 |
} |
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
func (c *Connection) Call(ctx context.Context, method string, params interface{}) *AsyncCall { |
| 143 |
result := &AsyncCall{ |
| 144 |
id: Int64ID(atomic.AddInt64(&c.seq, 1)), |
| 145 |
resultBox: make(chan asyncResult, 1), |
| 146 |
} |
| 147 |
|
| 148 |
ctx = event.Start(ctx, method, |
| 149 |
Method(method), RPCDirection(Outbound), RPCID(fmt.Sprintf("%q", result.id))) |
| 150 |
Started.Record(ctx, 1, Method(method)) |
| 151 |
result.ctx = ctx |
| 152 |
|
| 153 |
call, err := NewCall(result.id, method, params) |
| 154 |
if err != nil { |
| 155 |
|
| 156 |
result.resultBox <- asyncResult{err: errors.Errorf("marshaling call parameters: %w", err)} |
| 157 |
return result |
| 158 |
} |
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
result.response = make(chan *Response, 1) |
| 163 |
pending := <-c.outgoingBox |
| 164 |
pending[result.id] = result.response |
| 165 |
c.outgoingBox <- pending |
| 166 |
|
| 167 |
if err := c.write(ctx, call); err != nil { |
| 168 |
|
| 169 |
r, _ := NewResponse(result.id, nil, err) |
| 170 |
c.incomingResponse(r) |
| 171 |
} |
| 172 |
return result |
| 173 |
} |
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
func (a *AsyncCall) ID() ID { return a.id } |
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
|
| 182 |
func (a *AsyncCall) IsReady() bool { |
| 183 |
select { |
| 184 |
case r := <-a.resultBox: |
| 185 |
a.resultBox <- r |
| 186 |
return true |
| 187 |
default: |
| 188 |
return false |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
func (a *AsyncCall) Await(ctx context.Context, result interface{}) error { |
| 195 |
status := "NONE" |
| 196 |
defer event.End(a.ctx, StatusCode(status)) |
| 197 |
var r asyncResult |
| 198 |
select { |
| 199 |
case response := <-a.response: |
| 200 |
|
| 201 |
switch { |
| 202 |
case response.Error != nil: |
| 203 |
r.err = response.Error |
| 204 |
status = "ERROR" |
| 205 |
default: |
| 206 |
r.result = response.Result |
| 207 |
status = "OK" |
| 208 |
} |
| 209 |
case r = <-a.resultBox: |
| 210 |
|
| 211 |
case <-ctx.Done(): |
| 212 |
status = "CANCELLED" |
| 213 |
return ctx.Err() |
| 214 |
} |
| 215 |
|
| 216 |
a.resultBox <- r |
| 217 |
|
| 218 |
if r.err != nil { |
| 219 |
return r.err |
| 220 |
} |
| 221 |
if result == nil || len(r.result) == 0 { |
| 222 |
return nil |
| 223 |
} |
| 224 |
return json.Unmarshal(r.result, result) |
| 225 |
} |
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
func (c *Connection) Respond(id ID, result interface{}, rerr error) error { |
| 232 |
pending := <-c.incomingBox |
| 233 |
defer func() { c.incomingBox <- pending }() |
| 234 |
entry, found := pending[id] |
| 235 |
if !found { |
| 236 |
return nil |
| 237 |
} |
| 238 |
delete(pending, id) |
| 239 |
return c.respond(entry, result, rerr) |
| 240 |
} |
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
func (c *Connection) Cancel(id ID) { |
| 250 |
pending := <-c.incomingBox |
| 251 |
defer func() { c.incomingBox <- pending }() |
| 252 |
if entry, found := pending[id]; found && entry.cancel != nil { |
| 253 |
entry.cancel() |
| 254 |
entry.cancel = nil |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
|
| 259 |
func (c *Connection) Wait() error { |
| 260 |
return c.async.wait() |
| 261 |
} |
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
func (c *Connection) Close() error { |
| 267 |
|
| 268 |
if err := c.closer.Close(); err != nil && !isClosingError(err) { |
| 269 |
return err |
| 270 |
} |
| 271 |
|
| 272 |
if err := c.Wait(); err != nil && !isClosingError(err) { |
| 273 |
return err |
| 274 |
} |
| 275 |
return nil |
| 276 |
} |
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
func (c *Connection) readIncoming(ctx context.Context, reader Reader, toQueue chan<- *incoming) { |
| 281 |
defer close(toQueue) |
| 282 |
for { |
| 283 |
|
| 284 |
|
| 285 |
msg, n, err := reader.Read(ctx) |
| 286 |
if err != nil { |
| 287 |
|
| 288 |
c.async.setError(err) |
| 289 |
return |
| 290 |
} |
| 291 |
switch msg := msg.(type) { |
| 292 |
case *Request: |
| 293 |
entry := &incoming{ |
| 294 |
request: msg, |
| 295 |
} |
| 296 |
|
| 297 |
var idLabel event.Label |
| 298 |
if msg.IsCall() { |
| 299 |
idLabel = RPCID(fmt.Sprintf("%q", msg.ID)) |
| 300 |
} |
| 301 |
entry.baseCtx = event.Start(ctx, msg.Method, |
| 302 |
Method(msg.Method), RPCDirection(Inbound), idLabel) |
| 303 |
Started.Record(entry.baseCtx, 1, Method(msg.Method)) |
| 304 |
ReceivedBytes.Record(entry.baseCtx, n, Method(msg.Method)) |
| 305 |
|
| 306 |
entry.handleCtx, entry.cancel = context.WithCancel(entry.baseCtx) |
| 307 |
|
| 308 |
|
| 309 |
if msg.IsCall() { |
| 310 |
pending := <-c.incomingBox |
| 311 |
pending[msg.ID] = entry |
| 312 |
c.incomingBox <- pending |
| 313 |
} |
| 314 |
|
| 315 |
toQueue <- entry |
| 316 |
case *Response: |
| 317 |
|
| 318 |
|
| 319 |
c.incomingResponse(msg) |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
func (c *Connection) incomingResponse(msg *Response) { |
| 325 |
pending := <-c.outgoingBox |
| 326 |
response, ok := pending[msg.ID] |
| 327 |
if ok { |
| 328 |
delete(pending, msg.ID) |
| 329 |
} |
| 330 |
c.outgoingBox <- pending |
| 331 |
if response != nil { |
| 332 |
response <- msg |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
func (c *Connection) manageQueue(ctx context.Context, preempter Preempter, fromRead <-chan *incoming, toDeliver chan<- *incoming) { |
| 339 |
defer close(toDeliver) |
| 340 |
q := []*incoming{} |
| 341 |
ok := true |
| 342 |
for { |
| 343 |
var nextReq *incoming |
| 344 |
if len(q) == 0 { |
| 345 |
|
| 346 |
|
| 347 |
if !ok { |
| 348 |
return |
| 349 |
} |
| 350 |
|
| 351 |
nextReq, ok = <-fromRead |
| 352 |
} else { |
| 353 |
|
| 354 |
|
| 355 |
select { |
| 356 |
case nextReq, ok = <-fromRead: |
| 357 |
case toDeliver <- q[0]: |
| 358 |
|
| 359 |
q = q[1:] |
| 360 |
} |
| 361 |
} |
| 362 |
if nextReq != nil { |
| 363 |
|
| 364 |
var result interface{} |
| 365 |
rerr := nextReq.handleCtx.Err() |
| 366 |
if rerr == nil { |
| 367 |
|
| 368 |
result, rerr = preempter.Preempt(nextReq.handleCtx, nextReq.request) |
| 369 |
} |
| 370 |
switch { |
| 371 |
case rerr == ErrNotHandled: |
| 372 |
|
| 373 |
q = append(q, nextReq) |
| 374 |
case rerr == ErrAsyncResponse: |
| 375 |
|
| 376 |
default: |
| 377 |
|
| 378 |
c.reply(nextReq, result, rerr) |
| 379 |
} |
| 380 |
} |
| 381 |
} |
| 382 |
} |
| 383 |
|
| 384 |
func (c *Connection) deliverMessages(ctx context.Context, handler Handler, fromQueue <-chan *incoming) { |
| 385 |
defer c.async.done() |
| 386 |
for entry := range fromQueue { |
| 387 |
|
| 388 |
var result interface{} |
| 389 |
rerr := entry.handleCtx.Err() |
| 390 |
if rerr == nil { |
| 391 |
|
| 392 |
result, rerr = handler.Handle(entry.handleCtx, entry.request) |
| 393 |
} |
| 394 |
switch { |
| 395 |
case rerr == ErrNotHandled: |
| 396 |
|
| 397 |
c.reply(entry, nil, errors.Errorf("%w: %q", ErrMethodNotFound, entry.request.Method)) |
| 398 |
case rerr == ErrAsyncResponse: |
| 399 |
|
| 400 |
default: |
| 401 |
c.reply(entry, result, rerr) |
| 402 |
} |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
|
| 407 |
func (c *Connection) reply(entry *incoming, result interface{}, rerr error) { |
| 408 |
if entry.request.IsCall() { |
| 409 |
|
| 410 |
pending := <-c.incomingBox |
| 411 |
defer func() { c.incomingBox <- pending }() |
| 412 |
delete(pending, entry.request.ID) |
| 413 |
} |
| 414 |
if err := c.respond(entry, result, rerr); err != nil { |
| 415 |
|
| 416 |
|
| 417 |
event.Error(entry.baseCtx, "jsonrpc2 message delivery failed", err) |
| 418 |
} |
| 419 |
} |
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
func (c *Connection) respond(entry *incoming, result interface{}, rerr error) error { |
| 424 |
var err error |
| 425 |
if entry.request.IsCall() { |
| 426 |
|
| 427 |
if result == nil && rerr == nil { |
| 428 |
|
| 429 |
rerr = errors.Errorf("%w: %q produced no response", ErrInternal, entry.request.Method) |
| 430 |
} |
| 431 |
var response *Response |
| 432 |
response, err = NewResponse(entry.request.ID, result, rerr) |
| 433 |
if err == nil { |
| 434 |
|
| 435 |
err = c.write(entry.baseCtx, response) |
| 436 |
} |
| 437 |
} else { |
| 438 |
switch { |
| 439 |
case rerr != nil: |
| 440 |
|
| 441 |
err = errors.Errorf("%w: %q notification failed: %v", ErrInternal, entry.request.Method, rerr) |
| 442 |
rerr = nil |
| 443 |
case result != nil: |
| 444 |
|
| 445 |
err = errors.Errorf("%w: %q produced unwanted response", ErrInternal, entry.request.Method) |
| 446 |
default: |
| 447 |
|
| 448 |
} |
| 449 |
} |
| 450 |
var status string |
| 451 |
switch { |
| 452 |
case rerr != nil || err != nil: |
| 453 |
status = "ERROR" |
| 454 |
default: |
| 455 |
status = "OK" |
| 456 |
} |
| 457 |
|
| 458 |
if entry.cancel != nil { |
| 459 |
entry.cancel() |
| 460 |
entry.cancel = nil |
| 461 |
} |
| 462 |
|
| 463 |
event.End(entry.baseCtx, StatusCode(status)) |
| 464 |
return err |
| 465 |
} |
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
func (c *Connection) write(ctx context.Context, msg Message) error { |
| 470 |
writer := <-c.writerBox |
| 471 |
defer func() { c.writerBox <- writer }() |
| 472 |
n, err := writer.Write(ctx, msg) |
| 473 |
|
| 474 |
SentBytes.Record(ctx, n) |
| 475 |
return err |
| 476 |
} |