-
Notifications
You must be signed in to change notification settings - Fork 10
/
jrpc2_test.go
1381 lines (1221 loc) · 42.2 KB
/
jrpc2_test.go
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2017 Michael J. Fromberger. All Rights Reserved.
package jrpc2_test
import (
"context"
"encoding/json"
"errors"
"expvar"
"fmt"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/creachadair/jrpc2"
"github.com/creachadair/jrpc2/channel"
"github.com/creachadair/jrpc2/handler"
"github.com/creachadair/jrpc2/server"
"github.com/fortytw2/leaktest"
"github.com/google/go-cmp/cmp"
)
// Static type assertions.
var (
_ jrpc2.ErrCoder = (*jrpc2.Error)(nil)
)
var testOK = handler.New(func(ctx context.Context) (string, error) {
return "OK", nil
})
var testService = handler.Map{
// Verify that we can bind methods of a value.
"Add": handler.New((dummy{}).Add),
"Mul": handler.New((dummy{}).Mul),
"Max": handler.New((dummy{}).Max),
// Verify that we can bind free functions.
"Nil": handler.New(methodNil),
"Ctx": handler.New(methodCtx),
"Ping": handler.New(methodPing),
"Echo": handler.New(methodStruct),
}
type dummy struct{}
// Add is a request-based method.
func (dummy) Add(_ context.Context, req *jrpc2.Request) (any, error) {
if req.IsNotification() {
return nil, errors.New("ignoring notification")
}
var vals []int
if err := req.UnmarshalParams(&vals); err != nil {
return nil, err
}
var sum int
for _, v := range vals {
sum += v
}
return sum, nil
}
// Mul uses its own explicit parameter type.
func (dummy) Mul(_ context.Context, req struct{ X, Y int }) (int, error) {
return req.X * req.Y, nil
}
// Max takes a slice of arguments.
func (dummy) Max(_ context.Context, vs []int) (int, error) {
if len(vs) == 0 {
return 0, jrpc2.Errorf(jrpc2.InvalidParams, "cannot compute max of no elements")
}
max := vs[0]
for _, v := range vs[1:] {
if v > max {
max = v
}
}
return max, nil
}
// methodNil does not require any parameters.
func methodNil(_ context.Context) (int, error) { return 42, nil }
// methodCtx validates that its context includes the request.
func methodCtx(ctx context.Context, req *jrpc2.Request) (int, error) {
if creq := jrpc2.InboundRequest(ctx); creq != req {
return 0, fmt.Errorf("wrong req in context %p ≠ %p", creq, req)
}
return 1, nil
}
// methodPing responds only to notifications.
func methodPing(ctx context.Context, req *jrpc2.Request) error {
if !req.IsNotification() {
return errors.New("called Ping expecting a response")
}
return nil
}
type Anon struct{ OK string }
// structArgs has 4 valid fields.
type structArgs struct {
A string `json:"alpha"` // explicitly named
B bool `json:"-"` // explicitly skipped
//lint:ignore U1000 Verify that unexported fields are skipped.
skip bool
Anon // unnamed anonymous, skipped for positional
C int // default name "c"
D int `json:"delta"` // assigned name "delta"
}
// methodStruct has a struct argument that can be called with either an object
// or an array. It returns the value of arg.D.
func methodStruct(ctx context.Context, arg *structArgs) int {
return arg.D
}
var callTests = []struct {
method string
params any
want int
}{
{"Test.Add", []int{}, 0},
{"Test.Add", []int{1, 2, 3}, 6},
{"Test.Mul", struct{ X, Y int }{7, 9}, 63},
{"Test.Mul", struct{ X, Y int }{}, 0},
{"Test.Max", []int{3, 1, 8, 4, 2, 0, -5}, 8},
{"Test.Ctx", nil, 1},
{"Test.Nil", nil, 42},
{"Test.Nil", json.RawMessage("null"), 42},
{"Test.Echo", []any{"foo", 4, 17}, 17},
{"Test.Echo", map[string]any{"delta": 144, "ok": "yes"}, 144},
}
func TestServerInfo_methodNames(t *testing.T) {
defer leaktest.Check(t)()
loc := server.NewLocal(handler.ServiceMap{
"Test": testService,
}, nil)
defer loc.Close()
s := loc.Server
// Verify that the assigner got the names it was supposed to.
got, want := s.ServerInfo().Methods, []string{
"Test.Add", "Test.Ctx", "Test.Echo", "Test.Max", "Test.Mul", "Test.Nil", "Test.Ping",
}
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("Wrong method names: (-want, +got)\n%s", diff)
}
}
func TestClient_Call(t *testing.T) {
defer leaktest.Check(t)()
loc := server.NewLocal(handler.ServiceMap{
"Test": testService,
}, &server.LocalOptions{
Server: &jrpc2.ServerOptions{Concurrency: 16},
})
defer loc.Close()
c := loc.Client
ctx := context.Background()
// Verify that individual sequential requests work.
for _, test := range callTests {
rsp, err := c.Call(ctx, test.method, test.params)
if err != nil {
t.Errorf("Call %q %v: unexpected error: %v", test.method, test.params, err)
continue
}
var got int
if err := rsp.UnmarshalResult(&got); err != nil {
t.Errorf("Unmarshaling result: %v", err)
continue
}
if got != test.want {
t.Errorf("Call %q %v: got %v, want %v", test.method, test.params, got, test.want)
}
if err := c.Notify(ctx, test.method, test.params); err != nil {
t.Errorf("Notify %q %v: unexpected error: %v", test.method, test.params, err)
}
}
}
func TestClient_CallResult(t *testing.T) {
defer leaktest.Check(t)()
loc := server.NewLocal(handler.ServiceMap{
"Test": testService,
}, &server.LocalOptions{
Server: &jrpc2.ServerOptions{Concurrency: 16},
})
defer loc.Close()
c := loc.Client
ctx := context.Background()
// Verify also that the CallResult wrapper works.
for _, test := range callTests {
var got int
if err := c.CallResult(ctx, test.method, test.params, &got); err != nil {
t.Errorf("CallResult %q %v: unexpected error: %v", test.method, test.params, err)
continue
}
if got != test.want {
t.Errorf("CallResult %q %v: got %v, want %v", test.method, test.params, got, test.want)
}
}
}
func TestClient_Batch(t *testing.T) {
defer leaktest.Check(t)()
loc := server.NewLocal(handler.ServiceMap{
"Test": testService,
}, &server.LocalOptions{
Server: &jrpc2.ServerOptions{Concurrency: 16},
})
defer loc.Close()
c := loc.Client
ctx := context.Background()
// Verify that a batch request works.
specs := make([]jrpc2.Spec, len(callTests)+1)
specs[0] = jrpc2.Spec{
Method: "Test.Ping",
Params: []string{"hey"},
Notify: true,
}
for i, test := range callTests {
specs[i+1] = jrpc2.Spec{
Method: test.method,
Params: test.params,
Notify: false,
}
}
batch, err := c.Batch(ctx, specs)
if err != nil {
t.Fatalf("Batch failed: %v", err)
}
if len(batch) != len(callTests) {
t.Errorf("Wrong number of responses: got %d, want %d", len(batch), len(callTests))
}
for i, rsp := range batch {
if err := rsp.Error(); err != nil {
t.Errorf("Response %d failed: %v", i+1, err)
continue
}
var got int
if err := rsp.UnmarshalResult(&got); err != nil {
t.Errorf("Umarshaling result %d: %v", i+1, err)
continue
}
if got != callTests[i].want {
t.Errorf("Response %d (%q): got %v, want %v", i+1, rsp.ID(), got, callTests[i].want)
}
}
}
// Verify that notifications respect order of arrival.
func TestServer_notificationOrder(t *testing.T) {
defer leaktest.Check(t)()
var last int32
loc := server.NewLocal(handler.Map{
"Test": handler.New(func(_ context.Context, req *jrpc2.Request) error {
var seq int32
if err := req.UnmarshalParams(&handler.Args{&seq}); err != nil {
t.Errorf("Invalid test parameters: %v", err)
return err
}
if old := atomic.SwapInt32(&last, seq); old != seq-1 {
t.Errorf("Request out of sequence at #%d: got %d, want %d", seq, old, seq-1)
}
return nil
}),
}, &server.LocalOptions{
Server: &jrpc2.ServerOptions{Concurrency: 16},
})
for i := 1; i < 10; i++ {
if err := loc.Client.Notify(context.Background(), "Test", []int{i}); err != nil {
t.Errorf("Test notification failed: %v", err)
}
}
if err := loc.Close(); err != nil {
t.Logf("Warning: error at server exit: %v", err)
}
}
// Verify that a method that returns only an error (no result payload) is set
// up and handled correctly.
func TestHandler_errorOnly(t *testing.T) {
defer leaktest.Check(t)()
const errMessage = "not enough strings"
loc := server.NewLocal(handler.Map{
"ErrorOnly": handler.New(func(_ context.Context, ss []string) error {
if len(ss) == 0 {
return jrpc2.Errorf(1, errMessage)
}
t.Logf("ErrorOnly succeeds on input %q", ss)
return nil
}),
}, nil)
defer loc.Close()
c := loc.Client
ctx := context.Background()
t.Run("CallExpectingError", func(t *testing.T) {
rsp, err := c.Call(ctx, "ErrorOnly", []string{})
if err == nil {
t.Errorf("ErrorOnly: got %+v, want error", rsp)
} else if e, ok := err.(*jrpc2.Error); !ok {
t.Errorf("ErrorOnly: got %v, want *Error", err)
} else if e.Code != 1 || e.Message != errMessage {
t.Errorf("ErrorOnly: got (%s, %s), want (1, %s)", e.Code, e.Message, errMessage)
}
})
t.Run("CallExpectingOK", func(t *testing.T) {
rsp, err := c.Call(ctx, "ErrorOnly", []string{"aiutami!"})
if err != nil {
t.Errorf("ErrorOnly: unexpected error: %v", err)
}
// Per https://www.jsonrpc.org/specification#response_object, a "result"
// field is required on success, so verify that it is set null.
var got json.RawMessage
if err := rsp.UnmarshalResult(&got); err != nil {
t.Fatalf("Failed to unmarshal result data: %v", err)
} else if r := string(got); r != "null" {
t.Errorf("ErrorOnly response: got %q, want null", r)
}
})
}
// Verify that a timeout set on the client context is respected and reports
// back to the caller as an error.
func TestClient_contextTimeout(t *testing.T) {
defer leaktest.Check(t)()
loc := server.NewLocal(handler.Map{
"Stall": handler.New(func(ctx context.Context) (bool, error) {
t.Log("Stalling...")
select {
case <-ctx.Done():
t.Logf("Stall context done: err=%v", ctx.Err())
return true, nil
case <-time.After(5 * time.Second):
return false, errors.New("stall timed out")
}
}),
}, nil)
defer loc.Close()
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
start := time.Now()
got, err := loc.Client.Call(ctx, "Stall", nil)
if err == nil {
t.Errorf("Stall: got %+v, wanted error", got)
} else if err != context.DeadlineExceeded {
t.Errorf("Stall: got error %v, want %v", err, context.DeadlineExceeded)
} else {
t.Logf("Successfully cancelled after %v", time.Since(start))
}
}
// Verify that stopping the server terminates in-flight requests.
func TestServer_stopCancelsHandlers(t *testing.T) {
defer leaktest.Check(t)()
started := make(chan struct{})
stopped := make(chan error, 1)
loc := server.NewLocal(handler.Map{
"Hang": handler.New(func(ctx context.Context) (bool, error) {
close(started) // signal that the method handler is running
<-ctx.Done()
return true, ctx.Err()
}),
}, nil)
defer loc.Close()
s, c := loc.Server, loc.Client
// Call the server. The method will hang until its context is cancelled,
// which should happen when the server stops.
go func() {
defer close(stopped)
_, err := c.Call(context.Background(), "Hang", nil)
stopped <- err
}()
// Wait until the client method is running so we know we are testing at the
// right time, i.e., with a request in flight.
<-started
s.Stop()
select {
case <-time.After(30 * time.Second):
t.Error("Timed out waiting for service handler to fail")
case err := <-stopped:
if ec := jrpc2.ErrorCode(err); ec != jrpc2.Cancelled {
t.Errorf("Client error: got %v (%v), wanted code %v", err, ec, jrpc2.Cancelled)
}
}
}
// Test that a handler can cancel an in-flight request.
func TestServer_CancelRequest(t *testing.T) {
defer leaktest.Check(t)()
ready := make(chan struct{})
loc := server.NewLocal(handler.Map{
"Stall": handler.New(func(ctx context.Context) error {
close(ready)
t.Log("Stall handler: waiting for context cancellation")
<-ctx.Done()
return ctx.Err()
}),
"Test": handler.New(func(ctx context.Context, req *jrpc2.Request) error {
var id string
if err := req.UnmarshalParams(&handler.Args{&id}); err != nil {
return err
}
t.Logf("Test handler: cancelling %q...", id)
jrpc2.ServerFromContext(ctx).CancelRequest(id)
return nil
}),
}, nil)
defer loc.Close()
ctx := context.Background()
// Start a call in the background that will stall until cancelled.
errc := make(chan error, 1)
go func() {
_, err := loc.Client.Call(ctx, "Stall", nil)
errc <- err
close(errc)
}()
// Wait until the handler is in progress.
<-ready
// Call the test method to cancel the stalled method, and verify that we got
// back the expected error.
if _, err := loc.Client.Call(ctx, "Test", []string{"1"}); err != nil {
t.Errorf("Test call failed: %v", err)
}
err := <-errc
got := jrpc2.ErrorCode(err)
if got != jrpc2.Cancelled {
t.Errorf("Stall: got %v (%v), want %v", err, got, jrpc2.Cancelled)
} else {
t.Logf("Cancellation succeeded, got expected error: %v", err)
}
}
// Test that an error with data attached to it is correctly propagated back
// from the server to the client, in a value of concrete type *Error.
func TestError_withData(t *testing.T) {
defer leaktest.Check(t)()
const errCode = -32000
const errData = `{"caroline":452}`
const errMessage = "error thingy"
loc := server.NewLocal(handler.Map{
"Err": handler.New(func(_ context.Context) (int, error) {
return 17, jrpc2.Errorf(errCode, errMessage).WithData(json.RawMessage(errData))
}),
"Push": handler.New(func(ctx context.Context) (bool, error) {
return false, jrpc2.ServerFromContext(ctx).Notify(ctx, "PushBack", nil)
}),
"Code": handler.New(func(ctx context.Context) error {
return jrpc2.Code(12345).Err()
}),
}, &server.LocalOptions{
Client: &jrpc2.ClientOptions{
OnNotify: func(req *jrpc2.Request) {
t.Errorf("Client received unexpected push: %#v", req)
},
},
})
defer loc.Close()
c := loc.Client
if got, err := c.Call(context.Background(), "Err", nil); err == nil {
t.Errorf("Call(Push): got %#v, wanted error", got)
} else if e, ok := err.(*jrpc2.Error); ok {
if e.Code != errCode {
t.Errorf("Error code: got %d, want %d", e.Code, errCode)
}
if e.Message != errMessage {
t.Errorf("Error message: got %q, want %q", e.Message, errMessage)
}
if s := string(e.Data); s != errData {
t.Errorf("Error data: got %q, want %q", s, errData)
}
} else {
t.Fatalf("Call(Err): unexpected error: %v", err)
}
if got, err := c.Call(context.Background(), "Push", nil); err == nil {
t.Errorf("Call(Push): got %#v, wanted error", got)
}
if got, err := c.Call(context.Background(), "Code", nil); err == nil {
t.Errorf("Call(Code): got %#v, wanted error", got)
} else if s, exp := err.Error(), "[12345] error code 12345"; s != exp {
t.Errorf("Call(Code): got error %q, want %q", s, exp)
}
}
// Test that a client correctly reports bad parameters.
func TestClient_badCallParams(t *testing.T) {
defer leaktest.Check(t)()
loc := server.NewLocal(handler.Map{
"Test": handler.New(func(_ context.Context, v any) error {
return jrpc2.Errorf(129, "this should not be reached")
}),
}, nil)
defer loc.Close()
rsp, err := loc.Client.Call(context.Background(), "Test", "bogus")
if err == nil {
t.Errorf("Call(Test): got %+v, wanted error", rsp)
} else if got, want := jrpc2.ErrorCode(err), jrpc2.InvalidRequest; got != want {
t.Errorf("Call(Test): got code %v, want %v", got, want)
}
}
// Verify that metrics are correctly propagated to server info.
func TestServer_serverInfoMetrics(t *testing.T) {
defer leaktest.Check(t)()
const metricValue = "if red were green, green would be my favourite colour"
customMetric := new(expvar.String)
customMetric.Set(metricValue)
loc := server.NewLocal(handler.Map{
"Metricize": handler.New(func(ctx context.Context) (bool, error) {
jrpc2.ServerMetrics().Set("custom-metric", customMetric)
return true, nil
}),
}, nil)
s, c := loc.Server, loc.Client
ctx := context.Background()
if _, err := c.Call(ctx, "Metricize", nil); err != nil {
t.Fatalf("Call(Metricize) failed: %v", err)
}
active, ok := jrpc2.ServerMetrics().Get("servers_active").(*expvar.Int)
if !ok {
t.Fatal("Metric servers_active not defined")
} else if active.Value() != 2 { // 1 for this test, 1 for the examples
t.Errorf("Metric servers_active: got %d, want 1", active.Value())
}
loc.Close()
// When populated into a ServerInfo value, metrics should be converted to
// JSON values in a sensible way.
metric := s.ServerInfo().Metrics["custom-metric"]
if metric == nil {
t.Fatal("Custom metric not found")
} else if got, ok := metric.(json.RawMessage); !ok {
t.Fatalf("Wrong metric type: got %T, want json.RawMessage", metric)
} else if s := string(got); s != `"`+metricValue+`"` {
t.Fatalf("Wrong metric value: got %q, want %q", s, metricValue)
}
}
// Ensure that a correct request not sent via the *Client type will still
// elicit a correct response from the server. Here we simulate a "different"
// client by writing requests directly into the channel.
func TestServer_nonLibraryClient(t *testing.T) {
defer leaktest.Check(t)()
srv, cli := channel.Direct()
s := jrpc2.NewServer(handler.Map{
"X": testOK,
"Y": handler.New(func(context.Context) (any, error) {
return nil, nil
}),
}, nil).Start(srv)
defer func() {
cli.Close()
if err := s.Wait(); err != nil {
t.Errorf("Server wait: unexpected error %v", err)
}
}()
const invalidIDMessage = `{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"invalid request ID"}}`
tests := []struct {
input, want string
}{
// Missing version marker (and therefore wrong).
{`{"id":0}`,
`{"jsonrpc":"2.0","id":0,"error":{"code":-32600,"message":"invalid version marker"}}`},
// Version marker is present, but wrong.
{`{"jsonrpc":"1.5","id":1}`,
`{"jsonrpc":"2.0","id":1,"error":{"code":-32600,"message":"invalid version marker"}}`},
// No method was specified.
{`{"jsonrpc":"2.0","id":2}`,
`{"jsonrpc":"2.0","id":2,"error":{"code":-32600,"message":"empty method name"}}`},
// The method specified doesn't exist.
{`{"jsonrpc":"2.0", "id": 3, "method": "NoneSuch"}`,
`{"jsonrpc":"2.0","id":3,"error":{"code":-32601,"message":"method not found","data":"NoneSuch"}}`},
// The parameters are of the wrong form.
{`{"jsonrpc":"2.0", "id": 4, "method": "X", "params": "bogus"}`,
`{"jsonrpc":"2.0","id":4,"error":{"code":-32600,"message":"parameters must be array or object"}}`},
// The parameters are absent, but as null.
{`{"jsonrpc": "2.0", "id": 6, "method": "X", "params": null}`,
`{"jsonrpc":"2.0","id":6,"result":"OK"}`},
// Correct requests.
{`{"jsonrpc":"2.0","id": 5, "method": "X"}`, `{"jsonrpc":"2.0","id":5,"result":"OK"}`},
{`{"jsonrpc":"2.0","id":21,"method":"Y"}`, `{"jsonrpc":"2.0","id":21,"result":null}`},
{`{"jsonrpc":"2.0","id":0,"method":"X"}`, `{"jsonrpc":"2.0","id":0,"result":"OK"}`},
{`{"jsonrpc":"2.0","id":-0,"method":"X"}`, `{"jsonrpc":"2.0","id":-0,"result":"OK"}`},
{`{"jsonrpc":"2.0","id":-1,"method":"X"}`, `{"jsonrpc":"2.0","id":-1,"result":"OK"}`},
{`{"jsonrpc":"2.0","id":-600,"method":"Y"}`, `{"jsonrpc":"2.0","id":-600,"result":null}`},
// A batch of correct requests.
{`[{"jsonrpc":"2.0", "id":"a1", "method":"X"}, {"jsonrpc":"2.0", "id":"a2", "method": "X"}]`,
`[{"jsonrpc":"2.0","id":"a1","result":"OK"},{"jsonrpc":"2.0","id":"a2","result":"OK"}]`},
{`{"jsonrpc":"2.0", "id":-25, "method":"X"}`, `{"jsonrpc":"2.0","id":-25,"result":"OK"}`},
// Extra fields on an otherwise-correct request.
{`{"jsonrpc":"2.0","id": 7, "method": "Z", "params":[], "bogus":true}`,
`{"jsonrpc":"2.0","id":7,"error":{"code":-32600,"message":"extra fields in request","data":["bogus"]}}`},
// An empty batch request should report a single error object.
{`[]`, `{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"empty request batch"}}`},
// An invalid batch request should report a single error object.
{`[1]`, `[{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"request is not a JSON object"}}]`},
// A batch of invalid requests returns a batch of errors.
{`[{"jsonrpc": "2.0", "id": 6, "method":"bogus"}]`,
`[{"jsonrpc":"2.0","id":6,"error":{"code":-32601,"message":"method not found","data":"bogus"}}]`},
// Batch requests return batch responses, even for a singleton.
{`[{"jsonrpc": "2.0", "id": 7, "method": "X"}]`, `[{"jsonrpc":"2.0","id":7,"result":"OK"}]`},
// Notifications are not reflected in a batch response.
{`[{"jsonrpc": "2.0", "method": "note"}, {"jsonrpc": "2.0", "id": 8, "method": "X"}]`,
`[{"jsonrpc":"2.0","id":8,"result":"OK"}]`},
// Invalid structure for a version is reported, with and without ID.
{`{"jsonrpc": false}`,
`{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"invalid version key"}}`},
{`{"jsonrpc": false, "id": 747}`,
`{"jsonrpc":"2.0","id":747,"error":{"code":-32700,"message":"invalid version key"}}`},
// Invalid structure for a method name is reported, with and without ID.
{`{"jsonrpc":"2.0", "method": [false]}`,
`{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"invalid method name"}}`},
{`{"jsonrpc":"2.0", "method": [false], "id": 252}`,
`{"jsonrpc":"2.0","id":252,"error":{"code":-32700,"message":"invalid method name"}}`},
// A broken batch request should report a single top-level error.
{`[{"jsonrpc":"2.0", "method":"A", "id": 1}, {"jsonrpc":"2.0"]`, // N.B. syntax error
`{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"invalid request value"}}`},
// A broken single request should report a top-level error.
{`{"bogus"][++`,
`{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"invalid request value"}}`},
// Various invalid ID checks.
{`{"jsonrpc":"2.0", "id":[], "method":"X"}`, invalidIDMessage}, // invalid ID: array
{`{"jsonrpc":"2.0", "id":["q"], "method":"X"}`, invalidIDMessage}, // "
{`{"jsonrpc":"2.0", "id":{}, "method":"X"}`, invalidIDMessage}, // invalid ID: object
{`{"jsonrpc":"2.0", "id":true, "method":"X"}`, invalidIDMessage}, // invalid ID: Boolean
{`{"jsonrpc":"2.0", "id":false, "method":"X"}`, invalidIDMessage}, // "
}
for _, test := range tests {
if err := cli.Send([]byte(test.input)); err != nil {
t.Fatalf("Send %#q failed: %v", test.input, err)
}
raw, err := cli.Recv()
if err != nil {
t.Fatalf("Recv failed: %v", err)
}
if got := string(raw); got != test.want {
t.Errorf("Simulated call %#q: got %#q, want %#q", test.input, got, test.want)
}
}
}
// Verify that server-side push notifications work.
func TestServer_Notify(t *testing.T) {
defer leaktest.Check(t)()
// Set up a server and client with server-side notification support. Here
// we're just capturing the name of the notification method, as a sign we
// got the right thing.
var notes []string
loc := server.NewLocal(handler.Map{
"NoteMe": handler.New(func(ctx context.Context) (bool, error) {
// When this method is called, it posts a notification back to the
// client before returning.
if err := jrpc2.ServerFromContext(ctx).Notify(ctx, "method", nil); err != nil {
t.Errorf("Push Notify unexpectedly failed: %v", err)
return false, err
}
return true, nil
}),
}, &server.LocalOptions{
Server: &jrpc2.ServerOptions{
AllowPush: true,
},
Client: &jrpc2.ClientOptions{
OnNotify: func(req *jrpc2.Request) {
notes = append(notes, req.Method())
t.Logf("OnNotify handler saw method %q", req.Method())
},
},
})
s, c := loc.Server, loc.Client
ctx := context.Background()
// Post an explicit notification.
if err := s.Notify(ctx, "explicit", nil); err != nil {
t.Errorf("Notify explicit: unexpected error: %v", err)
}
// Call the method that posts a notification.
if _, err := c.Call(ctx, "NoteMe", nil); err != nil {
t.Errorf("Call NoteMe: unexpected error: %v", err)
}
// Shut everything down to be sure the callbacks have settled.
// Sort the results since the order of arrival may vary.
loc.Close()
sort.Strings(notes)
want := []string{"explicit", "method"}
if diff := cmp.Diff(want, notes); diff != "" {
t.Errorf("Server notifications: (-want, +got)\n%s", diff)
}
}
// Verify that server-side callbacks can time out.
func TestServer_callbackTimeout(t *testing.T) {
defer leaktest.Check(t)()
loc := server.NewLocal(handler.Map{
"Test": handler.New(func(ctx context.Context) error {
tctx, cancel := context.WithTimeout(ctx, 5*time.Millisecond)
defer cancel()
rsp, err := jrpc2.ServerFromContext(ctx).Callback(tctx, "hey", nil)
if err == context.DeadlineExceeded {
t.Logf("Callback correctly failed: %v", err)
return nil
} else if err != nil {
return fmt.Errorf("unexpected error: %v", err)
}
return fmt.Errorf("got rsp=%+v, want error", rsp)
}),
}, &server.LocalOptions{
Server: &jrpc2.ServerOptions{AllowPush: true},
// N.B. Client does not have a callback handler, so calls will be ignored
// and no response will be generated.
})
defer loc.Close()
ctx := context.Background()
if _, err := loc.Client.Call(ctx, "Test", nil); err != nil {
t.Errorf("Call failed: %v", err)
}
}
// Verify that server-side callbacks work.
func TestServer_Callback(t *testing.T) {
defer leaktest.Check(t)()
loc := server.NewLocal(handler.Map{
"CallMeMaybe": handler.New(func(ctx context.Context) error {
if _, err := jrpc2.ServerFromContext(ctx).Callback(ctx, "succeed", nil); err != nil {
t.Errorf("Callback failed: %v", err)
}
if rsp, err := jrpc2.ServerFromContext(ctx).Callback(ctx, "fail", nil); err == nil {
t.Errorf("Callback did not fail: got %v, want error", rsp)
}
return nil
}),
}, &server.LocalOptions{
Server: &jrpc2.ServerOptions{AllowPush: true},
Client: &jrpc2.ClientOptions{
OnCallback: func(ctx context.Context, req *jrpc2.Request) (any, error) {
t.Logf("OnCallback invoked for method %q", req.Method())
switch req.Method() {
case "succeed":
return true, nil
case "fail":
return false, errors.New("here is your requested error")
}
panic("broken test: you should not see this")
},
},
})
defer loc.Close()
ctx := context.Background()
// Call the method that posts a callback.
if _, err := loc.Client.Call(ctx, "CallMeMaybe", nil); err != nil {
t.Fatalf("Call CallMeMaybe: unexpected error: %v", err)
}
// Post an explicit callback.
if _, err := loc.Server.Callback(ctx, "succeed", nil); err != nil {
t.Errorf("Callback explicit: unexpected error: %v", err)
}
}
// Verify that a server push after the client closes does not trigger a panic.
func TestServer_pushAfterClose(t *testing.T) {
defer leaktest.Check(t)()
loc := server.NewLocal(make(handler.Map), &server.LocalOptions{
Server: &jrpc2.ServerOptions{AllowPush: true},
})
loc.Client.Close()
ctx := context.Background()
if err := loc.Server.Notify(ctx, "whatever", nil); err != jrpc2.ErrConnClosed {
t.Errorf("Notify(whatever): got %v, want %v", err, jrpc2.ErrConnClosed)
}
if rsp, err := loc.Server.Callback(ctx, "whatever", nil); err != jrpc2.ErrConnClosed {
t.Errorf("Callback(whatever): got %v, %v; want %v", rsp, err, jrpc2.ErrConnClosed)
}
}
// Verify that an OnCancel hook is called when expected.
func TestClient_onCancelHook(t *testing.T) {
defer leaktest.Check(t)()
hooked := make(chan struct{}) // closed when hook notification is finished
loc := server.NewLocal(handler.Map{
// Block until explicitly cancelled or a long timeout expires.
"Stall": handler.New(func(ctx context.Context) error {
select {
case <-ctx.Done():
t.Logf("Method unblocked; returning err=%v", ctx.Err())
return ctx.Err()
case <-time.After(10 * time.Second): // shouldn't happen
t.Error("Timeout waiting for server cancellation")
}
return nil
}),
// Cancel the specified request (notification only).
"computerSaysNo": handler.New(func(ctx context.Context, ids []string) error {
defer close(hooked)
if req := jrpc2.InboundRequest(ctx); !req.IsNotification() {
return jrpc2.Errorf(jrpc2.MethodNotFound, "no such method %q", req.Method())
}
srv := jrpc2.ServerFromContext(ctx)
for _, id := range ids {
srv.CancelRequest(id)
t.Logf("In cancellation handler, cancelled request id=%v", id)
}
return nil
}),
}, &server.LocalOptions{
Client: &jrpc2.ClientOptions{
OnCancel: func(cli *jrpc2.Client, rsp *jrpc2.Response) {
t.Logf("OnCancel hook called with id=%q, err=%v", rsp.ID(), rsp.Error())
cli.Notify(context.Background(), "computerSaysNo", []string{rsp.ID()})
},
},
})
// Call a method on the server that will stall until its context terminates.
// On the client side, set a deadline to expire the caller's context.
// The cancellation hook will notify the server to unblock the method.
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
got, err := loc.Client.Call(ctx, "Stall", nil)
if err == nil {
t.Errorf("Stall: got %+v, wanted error", got)
} else if err != context.DeadlineExceeded {
t.Errorf("Stall: got error %v, want %v", err, context.Canceled)
}
<-hooked
loc.Client.Close()
if err := loc.Server.Wait(); err != nil {
t.Errorf("Server exit status: %v", err)
}
}
// Verify that client callback handlers are cancelled when the client stops.
func TestClient_closeEndsCallbacks(t *testing.T) {
defer leaktest.Check(t)()
ready := make(chan struct{})
loc := server.NewLocal(handler.Map{
"Test": handler.New(func(ctx context.Context) error {
// Call back to the client and block indefinitely until it returns.
srv := jrpc2.ServerFromContext(ctx)
_, err := srv.Callback(ctx, "whatever", nil)
return err
}),
}, &server.LocalOptions{
Server: &jrpc2.ServerOptions{AllowPush: true},
Client: &jrpc2.ClientOptions{
OnCallback: handler.New(func(ctx context.Context) error {
// Signal the test that the callback handler is running. When the
// client is closed, it should terminate ctx and allow this to
// return. If that doesn't happen, time out and fail.
close(ready)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(10 * time.Second):
return errors.New("context not cancelled before timeout")
}
}),
},
})
go func() {
rsp, err := loc.Client.Call(context.Background(), "Test", nil)
if err == nil {
t.Errorf("Client call: got %+v, wanted error", rsp)
}
}()
<-ready
loc.Client.Close()
loc.Server.Wait()
}
// Verify that it is possible for multiple callback handlers to execute
// concurrently.
func TestClient_concurrentCallbacks(t *testing.T) {
defer leaktest.Check(t)()
ready1 := make(chan struct{})
ready2 := make(chan struct{})
release := make(chan struct{})
loc := server.NewLocal(handler.Map{
"Test": handler.New(func(ctx context.Context) []string {
srv := jrpc2.ServerFromContext(ctx)
// Call two callbacks concurrently, wait until they are both running,
// then ungate them and wait for them both to reply. Return their
// responses back to the test for validation.
ss := make([]string, 2)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
rsp, err := srv.Callback(ctx, "C1", nil)
if err != nil {
t.Errorf("Callback C1 failed: %v", err)
} else {
rsp.UnmarshalResult(&ss[0])
}
}()
go func() {
defer wg.Done()
rsp, err := srv.Callback(ctx, "C2", nil)
if err != nil {
t.Errorf("Callback C2 failed: %v", err)
} else {
rsp.UnmarshalResult(&ss[1])
}
}()
<-ready1 // C1 is ready
<-ready2 // C2 is ready
close(release) // allow all callbacks to proceed
wg.Wait() // wait for all callbacks to be done
return ss
}),
}, &server.LocalOptions{
Server: &jrpc2.ServerOptions{AllowPush: true},
Client: &jrpc2.ClientOptions{
OnCallback: func(ctx context.Context, req *jrpc2.Request) (any, error) {
// A trivial callback that reports its method name.
// The name is used to select which invocation we are serving.
switch req.Method() {
case "C1":
close(ready1)
case "C2":