-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathconnection_cancel_test.go
More file actions
658 lines (572 loc) · 16.8 KB
/
connection_cancel_test.go
File metadata and controls
658 lines (572 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
package acp
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"testing"
"time"
)
func TestConnectionInboundCancelRequest_CancelsHandler(t *testing.T) {
inR, inW := io.Pipe()
outR, outW := io.Pipe()
defer func() {
_ = inW.Close()
_ = outW.Close()
_ = inR.Close()
_ = outR.Close()
}()
started := make(chan struct{})
c := NewConnection(func(ctx context.Context, method string, params json.RawMessage) (any, *RequestError) {
close(started)
<-ctx.Done()
return nil, toReqErr(ctx.Err())
}, outW, inR)
_ = c
lines := make(chan []byte, 10)
go func() {
scanner := bufio.NewScanner(outR)
for scanner.Scan() {
b := append([]byte(nil), scanner.Bytes()...)
lines <- b
}
close(lines)
}()
// Send a request that will block until cancelled.
_, err := inW.Write([]byte(`{"jsonrpc":"2.0","id":1,"method":"test","params":{}}` + "\n"))
if err != nil {
t.Fatalf("write request: %v", err)
}
select {
case <-started:
case <-time.After(2 * time.Second):
t.Fatal("handler did not start")
}
// Cancel the in-flight request.
_, err = inW.Write([]byte(`{"jsonrpc":"2.0","method":"$/cancel_request","params":{"requestId":1}}` + "\n"))
if err != nil {
t.Fatalf("write cancel notification: %v", err)
}
var raw []byte
select {
case raw = <-lines:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for response")
}
var msg anyMessage
if err := json.Unmarshal(raw, &msg); err != nil {
t.Fatalf("unmarshal response: %v", err)
}
if msg.ID == nil {
t.Fatalf("response missing id: %s", string(raw))
}
if got := string(*msg.ID); got != "1" {
t.Fatalf("unexpected response id: %q", got)
}
if msg.Error == nil {
t.Fatalf("expected error response, got: %s", string(raw))
}
if msg.Error.Code != -32800 {
t.Fatalf("expected error code -32800, got %d (%s)", msg.Error.Code, msg.Error.Message)
}
}
func TestConnectionInboundCancelRequest_CanonicalizesEquivalentIDs(t *testing.T) {
inR, inW := io.Pipe()
outR, outW := io.Pipe()
defer func() {
_ = inW.Close()
_ = outW.Close()
_ = inR.Close()
_ = outR.Close()
}()
started := make(chan struct{})
c := NewConnection(func(ctx context.Context, method string, params json.RawMessage) (any, *RequestError) {
close(started)
<-ctx.Done()
return nil, toReqErr(ctx.Err())
}, outW, inR)
_ = c
lines := make(chan []byte, 10)
go func() {
scanner := bufio.NewScanner(outR)
for scanner.Scan() {
b := append([]byte(nil), scanner.Bytes()...)
lines <- b
}
close(lines)
}()
// Request id is encoded as a unicode escape sequence; cancel uses the canonical form.
_, err := inW.Write([]byte(`{"jsonrpc":"2.0","id":"\u0061","method":"test","params":{}}` + "\n"))
if err != nil {
t.Fatalf("write request: %v", err)
}
select {
case <-started:
case <-time.After(2 * time.Second):
t.Fatal("handler did not start")
}
_, err = inW.Write([]byte(`{"jsonrpc":"2.0","method":"$/cancel_request","params":{"requestId":"a"}}` + "\n"))
if err != nil {
t.Fatalf("write cancel notification: %v", err)
}
var raw []byte
select {
case raw = <-lines:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for response")
}
var msg anyMessage
if err := json.Unmarshal(raw, &msg); err != nil {
t.Fatalf("unmarshal response: %v", err)
}
if msg.Error == nil {
t.Fatalf("expected error response, got: %s", string(raw))
}
if msg.Error.Code != -32800 {
t.Fatalf("expected error code -32800, got %d (%s)", msg.Error.Code, msg.Error.Message)
}
}
func TestConnectionInboundCancelRequest_CanonicalizesEquivalentNumericIDs(t *testing.T) {
inR, inW := io.Pipe()
outR, outW := io.Pipe()
defer func() {
_ = inW.Close()
_ = outW.Close()
_ = inR.Close()
_ = outR.Close()
}()
started := make(chan struct{})
c := NewConnection(func(ctx context.Context, method string, params json.RawMessage) (any, *RequestError) {
close(started)
<-ctx.Done()
return nil, toReqErr(ctx.Err())
}, outW, inR)
_ = c
lines := make(chan []byte, 10)
go func() {
scanner := bufio.NewScanner(outR)
for scanner.Scan() {
b := append([]byte(nil), scanner.Bytes()...)
lines <- b
}
close(lines)
}()
// Request id uses exponent notation; cancel uses normalized integer notation.
_, err := inW.Write([]byte(`{"jsonrpc":"2.0","id":1e0,"method":"test","params":{}}` + "\n"))
if err != nil {
t.Fatalf("write request: %v", err)
}
select {
case <-started:
case <-time.After(2 * time.Second):
t.Fatal("handler did not start")
}
_, err = inW.Write([]byte(`{"jsonrpc":"2.0","method":"$/cancel_request","params":{"requestId":1}}` + "\n"))
if err != nil {
t.Fatalf("write cancel notification: %v", err)
}
var raw []byte
select {
case raw = <-lines:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for response")
}
var msg anyMessage
if err := json.Unmarshal(raw, &msg); err != nil {
t.Fatalf("unmarshal response: %v", err)
}
if msg.Error == nil {
t.Fatalf("expected error response, got: %s", string(raw))
}
if msg.Error.Code != -32800 {
t.Fatalf("expected error code -32800, got %d (%s)", msg.Error.Code, msg.Error.Message)
}
}
func TestCanonicalJSONRPCIDKey_LargeNumericIDsDoNotCollide(t *testing.T) {
id1 := json.RawMessage(`9007199254740992`)
id2 := json.RawMessage(`9007199254740993`)
key1, err := canonicalJSONRPCIDKey(id1)
if err != nil {
t.Fatalf("canonicalize id1: %v", err)
}
key2, err := canonicalJSONRPCIDKey(id2)
if err != nil {
t.Fatalf("canonicalize id2: %v", err)
}
if key1 != string(id1) {
t.Fatalf("unexpected canonical id1: got %q want %q", key1, string(id1))
}
if key2 != string(id2) {
t.Fatalf("unexpected canonical id2: got %q want %q", key2, string(id2))
}
if key1 == key2 {
t.Fatalf("canonical keys collided: id1=%q id2=%q key=%q", id1, id2, key1)
}
}
func TestCanonicalJSONRPCIDKey_NumericRepresentationsMatch(t *testing.T) {
t.Parallel()
tests := []struct {
name string
a json.RawMessage
b json.RawMessage
}{
{name: "integer exponent", a: json.RawMessage(`1`), b: json.RawMessage(`1e0`)},
{name: "integer decimal", a: json.RawMessage(`1`), b: json.RawMessage(`1.0`)},
{name: "fraction exponent", a: json.RawMessage(`0.1`), b: json.RawMessage(`1e-1`)},
{name: "negative zero", a: json.RawMessage(`-0`), b: json.RawMessage(`0`)},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
keyA, err := canonicalJSONRPCIDKey(tc.a)
if err != nil {
t.Fatalf("canonicalize a: %v", err)
}
keyB, err := canonicalJSONRPCIDKey(tc.b)
if err != nil {
t.Fatalf("canonicalize b: %v", err)
}
if keyA != keyB {
t.Fatalf("expected equivalent numeric ids to match: a=%q b=%q keyA=%q keyB=%q", tc.a, tc.b, keyA, keyB)
}
})
}
}
func TestCanonicalJSONRPCIDKey_RejectsOversizedExponent(t *testing.T) {
t.Parallel()
tests := []json.RawMessage{
json.RawMessage(`1e4097`),
json.RawMessage(`1e-4097`),
}
for _, raw := range tests {
raw := raw
t.Run(string(raw), func(t *testing.T) {
_, err := canonicalJSONRPCIDKey(raw)
if !errors.Is(err, errJSONRPCNumericIDTooLarge) {
t.Fatalf("expected oversized numeric id error for %q, got %v", raw, err)
}
})
}
}
func TestConnectionResponseID_CanonicalizesEquivalentNumericRepresentations(t *testing.T) {
inR, inW := io.Pipe()
outR, outW := io.Pipe()
defer func() {
_ = inW.Close()
_ = outW.Close()
_ = inR.Close()
_ = outR.Close()
}()
c := NewConnection(nil, outW, inR)
responderErr := make(chan error, 1)
go func() {
br := bufio.NewReader(outR)
if _, err := br.ReadBytes('\n'); err != nil {
responderErr <- fmt.Errorf("read outbound request: %w", err)
return
}
if _, err := inW.Write([]byte(`{"jsonrpc":"2.0","id":1e0,"result":{"ok":true}}` + "\n")); err != nil {
responderErr <- fmt.Errorf("write response: %w", err)
return
}
responderErr <- nil
}()
result, err := SendRequest[map[string]bool](c, context.Background(), "test/method", map[string]any{"x": 1})
if err != nil {
t.Fatalf("SendRequest returned error: %v", err)
}
if !result["ok"] {
t.Fatalf("unexpected response payload: %#v", result)
}
if err := <-responderErr; err != nil {
t.Fatal(err)
}
}
func TestConnectionInboundCancelRequest_ImmediateCancelNoRace(t *testing.T) {
inR, inW := io.Pipe()
outR, outW := io.Pipe()
defer func() {
_ = inW.Close()
_ = outW.Close()
_ = inR.Close()
_ = outR.Close()
}()
c := NewConnection(func(ctx context.Context, method string, params json.RawMessage) (any, *RequestError) {
<-ctx.Done()
return nil, toReqErr(ctx.Err())
}, outW, inR)
_ = c
lines := make(chan []byte, 10)
go func() {
scanner := bufio.NewScanner(outR)
for scanner.Scan() {
b := append([]byte(nil), scanner.Bytes()...)
lines <- b
}
close(lines)
}()
for i := 1; i <= 25; i++ {
payload := fmt.Sprintf(
`{"jsonrpc":"2.0","id":%d,"method":"test","params":{}}`+"\n"+
`{"jsonrpc":"2.0","method":"$/cancel_request","params":{"requestId":%d}}`+"\n",
i, i,
)
if _, err := inW.Write([]byte(payload)); err != nil {
t.Fatalf("write request/cancel pair %d: %v", i, err)
}
var raw []byte
select {
case raw = <-lines:
case <-time.After(2 * time.Second):
t.Fatalf("timed out waiting for response on iteration %d", i)
}
var msg anyMessage
if err := json.Unmarshal(raw, &msg); err != nil {
t.Fatalf("unmarshal response on iteration %d: %v", i, err)
}
if msg.ID == nil {
t.Fatalf("response missing id on iteration %d: %s", i, string(raw))
}
if got := string(*msg.ID); got != fmt.Sprintf("%d", i) {
t.Fatalf("unexpected response id on iteration %d: got %q", i, got)
}
if msg.Error == nil {
t.Fatalf("expected error response on iteration %d, got: %s", i, string(raw))
}
if msg.Error.Code != -32800 {
t.Fatalf("expected error code -32800 on iteration %d, got %d (%s)", i, msg.Error.Code, msg.Error.Message)
}
}
}
func TestConnectionOutboundCancelRequest_SendsNotification(t *testing.T) {
inR, inW := io.Pipe()
outR, outW := io.Pipe()
defer func() {
_ = inW.Close()
_ = outW.Close()
_ = inR.Close()
_ = outR.Close()
}()
c := NewConnection(nil, outW, inR)
lines := make(chan []byte, 10)
go func() {
scanner := bufio.NewScanner(outR)
for scanner.Scan() {
b := append([]byte(nil), scanner.Bytes()...)
lines <- b
}
close(lines)
}()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
errCh := make(chan error, 1)
go func() {
_, err := SendRequest[json.RawMessage](c, ctx, "test/method", map[string]any{"x": 1})
errCh <- err
}()
// First message should be the outbound request.
var reqRaw []byte
select {
case reqRaw = <-lines:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for request")
}
var req anyMessage
if err := json.Unmarshal(reqRaw, &req); err != nil {
t.Fatalf("unmarshal request: %v", err)
}
if req.ID == nil {
t.Fatalf("request missing id: %s", string(reqRaw))
}
if req.Method != "test/method" {
t.Fatalf("unexpected request method: %q", req.Method)
}
idKey := string(*req.ID)
// Cancel the outbound request context; this should trigger a best-effort $/cancel_request.
cancel()
var cancelRaw []byte
select {
case cancelRaw = <-lines:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for cancel notification")
}
var cancelMsg anyMessage
if err := json.Unmarshal(cancelRaw, &cancelMsg); err != nil {
t.Fatalf("unmarshal cancel notification: %v", err)
}
if cancelMsg.ID != nil {
t.Fatalf("cancel notification unexpectedly had id: %s", string(cancelRaw))
}
if cancelMsg.Method != "$/cancel_request" {
t.Fatalf("unexpected cancel method: %q", cancelMsg.Method)
}
var p cancelRequestParams
if err := json.Unmarshal(cancelMsg.Params, &p); err != nil {
t.Fatalf("unmarshal cancel params: %v", err)
}
if got := string(p.RequestID); got != idKey {
t.Fatalf("unexpected cancel requestId: got %q want %q", got, idKey)
}
select {
case err := <-errCh:
if err == nil {
t.Fatal("expected request error")
}
re, ok := err.(*RequestError)
if !ok {
t.Fatalf("expected *RequestError, got %T: %v", err, err)
}
if re.Code != -32800 {
t.Fatalf("expected error code -32800, got %d", re.Code)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for SendRequest to return")
}
}
func TestConnectionOutboundRequestTimeout_ReturnsInternalError(t *testing.T) {
inR, inW := io.Pipe()
defer func() {
_ = inW.Close()
_ = inR.Close()
}()
c := NewConnection(nil, io.Discard, inR)
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
_, err := SendRequest[json.RawMessage](c, ctx, "test/method", map[string]any{"x": 1})
if err == nil {
t.Fatal("expected request error")
}
re, ok := err.(*RequestError)
if !ok {
t.Fatalf("expected *RequestError, got %T: %v", err, err)
}
if re.Code != -32603 {
t.Fatalf("expected timeout to map to internal error code -32603, got %d (%s)", re.Code, re.Message)
}
c.mu.Lock()
pendingCount := len(c.pending)
c.mu.Unlock()
if pendingCount != 0 {
t.Fatalf("expected pending map to be cleaned up after timeout, got %d entries", pendingCount)
}
}
func TestConnectionOutboundCancelRequest_DoesNotBlockWhenPeerStopsReading(t *testing.T) {
inR, inW := io.Pipe()
outR, outW := io.Pipe()
defer func() {
_ = inW.Close()
_ = outW.Close()
_ = inR.Close()
_ = outR.Close()
}()
c := NewConnection(nil, outW, inR)
firstReq := make(chan []byte, 1)
go func() {
br := bufio.NewReader(outR)
line, err := br.ReadBytes('\n')
if err == nil {
firstReq <- append([]byte(nil), line...)
}
close(firstReq)
// Intentionally stop reading after the first request line.
}()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
errCh := make(chan error, 1)
go func() {
_, err := SendRequest[json.RawMessage](c, ctx, "test/method", map[string]any{"x": 1})
errCh <- err
}()
var reqRaw []byte
select {
case reqRaw = <-firstReq:
if len(reqRaw) == 0 {
t.Fatal("failed to read first outbound request")
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for first request")
}
var req anyMessage
if err := json.Unmarshal(reqRaw, &req); err != nil {
t.Fatalf("unmarshal request: %v", err)
}
if req.ID == nil {
t.Fatalf("request missing id: %s", string(reqRaw))
}
// Peer is no longer reading. The best-effort cancel write may block in the background,
// but SendRequest should still return promptly on context cancellation.
cancel()
select {
case err := <-errCh:
if err == nil {
t.Fatal("expected request error")
}
re, ok := err.(*RequestError)
if !ok {
t.Fatalf("expected *RequestError, got %T: %v", err, err)
}
if re.Code != -32800 {
t.Fatalf("expected error code -32800, got %d", re.Code)
}
case <-time.After(1 * time.Second):
t.Fatal("SendRequest blocked on cancel notification write")
}
}
func TestConnectionSendCancelRequest_BoundsPendingQueue(t *testing.T) {
baseCtx, baseCancel := context.WithCancelCause(context.Background())
defer baseCancel(nil)
c := &Connection{
pending: make(map[string]*pendingResponse),
inflight: make(map[string]context.CancelCauseFunc),
cancelRequestSignal: make(chan struct{}, 1),
ctx: baseCtx,
cancel: baseCancel,
}
for i := 0; i < maxPendingCancelRequests+128; i++ {
c.sendCancelRequest(fmt.Sprintf("%d", i))
}
c.mu.Lock()
defer c.mu.Unlock()
if len(c.pendingCancelRequest) != maxPendingCancelRequests {
t.Fatalf("expected pending cancel queue length %d, got %d", maxPendingCancelRequests, len(c.pendingCancelRequest))
}
if got := c.pendingCancelRequest[0]; got != "0" {
t.Fatalf("expected queue to retain earliest id when full, got first id %q", got)
}
expectedLast := fmt.Sprintf("%d", maxPendingCancelRequests-1)
if got := c.pendingCancelRequest[len(c.pendingCancelRequest)-1]; got != expectedLast {
t.Fatalf("expected queue to drop ids beyond capacity, got last id %q want %q", got, expectedLast)
}
}
func TestConnectionWaitForResponse_PeerDisconnectWinsOverDerivedContextCancel(t *testing.T) {
const iterations = 64
for i := 0; i < iterations; i++ {
baseCtx, baseCancel := context.WithCancelCause(context.Background())
c := &Connection{
pending: make(map[string]*pendingResponse),
ctx: baseCtx,
cancel: baseCancel,
}
idKey := fmt.Sprintf("id-%d", i)
pr := &pendingResponse{ch: make(chan anyMessage)}
c.pending[idKey] = pr
requestCtx, requestCancel := context.WithCancel(baseCtx)
baseCancel(errors.New("peer closed"))
_, err := c.waitForResponse(requestCtx, pr, idKey)
requestCancel()
if err == nil {
t.Fatalf("iteration %d: expected error", i)
}
re, ok := err.(*RequestError)
if !ok {
t.Fatalf("iteration %d: expected *RequestError, got %T (%v)", i, err, err)
}
if re.Code != -32603 {
t.Fatalf("iteration %d: expected disconnect error code -32603, got %d (%s)", i, re.Code, re.Message)
}
if _, ok := c.pending[idKey]; ok {
t.Fatalf("iteration %d: pending request %q was not cleaned up", i, idKey)
}
}
}