-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathws_test.go
More file actions
1254 lines (1087 loc) · 34.6 KB
/
ws_test.go
File metadata and controls
1254 lines (1087 loc) · 34.6 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
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
package shiftapi_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"github.com/fcjr/shiftapi"
)
type wsServerMsg struct {
Text string `json:"text"`
}
type wsClientMsg struct {
Text string `json:"text"`
}
func noSetup(r *http.Request, sender *shiftapi.WSSender, _ struct{}) (struct{}, error) {
return struct{}{}, nil
}
// wsErrorFrame represents the wire format for error frames:
// {"error": true, "code": 4xxx, "data": ...}
type wsErrorFrame struct {
Error bool `json:"error"`
Code int `json:"code"`
Data json.RawMessage `json:"data"`
}
// readWSError reads an error frame envelope and decodes its data field into v.
func readWSError(t *testing.T, ctx context.Context, conn *websocket.Conn, v any) wsErrorFrame {
t.Helper()
var frame wsErrorFrame
if err := wsjson.Read(ctx, conn, &frame); err != nil {
t.Fatalf("read error frame: %v", err)
}
if !frame.Error {
t.Fatal("expected error frame (error: true)")
}
if v != nil {
if err := json.Unmarshal(frame.Data, v); err != nil {
t.Fatalf("unmarshal error data: %v", err)
}
}
return frame
}
type wsNoJsonTags struct {
Text string
}
func TestHandleWS_OpenAPISchemaNoJsonTags(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("echo", func(sender *shiftapi.WSSender, _ struct{}, msg wsNoJsonTags) error {
return nil
}),
),
)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/openapi.json", nil)
api.ServeHTTP(w, r)
var spec map[string]any
if err := json.NewDecoder(w.Body).Decode(&spec); err != nil {
t.Fatalf("decode spec: %v", err)
}
oaComponents := spec["components"].(map[string]any)
oaSchemas := oaComponents["schemas"].(map[string]any)
// Even without json tags, the schema should be registered in OpenAPI
// so the generated TypeScript type doesn't resolve to any.
if _, ok := oaSchemas["wsNoJsonTags"]; !ok {
t.Error("missing wsNoJsonTags schema in OpenAPI components — would resolve to any in generated client")
}
}
func TestHandleWS_AsyncAPISpec(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("echo", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return sender.Send(wsServerMsg(msg))
}),
),
shiftapi.WithRouteInfo(shiftapi.RouteInfo{
Summary: "Echo WS",
Tags: []string{"websocket"},
}),
)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/asyncapi.json", nil)
api.ServeHTTP(w, r)
var spec map[string]any
if err := json.NewDecoder(w.Body).Decode(&spec); err != nil {
t.Fatalf("decode spec: %v", err)
}
// Verify asyncapi version.
if spec["asyncapi"] != "2.4.0" {
t.Errorf("asyncapi = %v, want 2.4.0", spec["asyncapi"])
}
channels, ok := spec["channels"].(map[string]any)
if !ok {
t.Fatal("no channels in async spec")
}
ch, ok := channels["/ws"].(map[string]any)
if !ok {
t.Fatal("no /ws channel in async spec")
}
// subscribe = server→client = Send type
sub, ok := ch["subscribe"].(map[string]any)
if !ok {
t.Fatal("no subscribe operation on /ws channel")
}
if sub["operationId"] == nil {
t.Error("subscribe missing operationId")
}
if sub["message"] == nil {
t.Error("subscribe missing message")
}
if sub["summary"] != "Echo WS" {
t.Errorf("subscribe summary = %v, want Echo WS", sub["summary"])
}
// publish = client→server = Recv type
pub, ok := ch["publish"].(map[string]any)
if !ok {
t.Fatal("no publish operation on /ws channel")
}
if pub["message"] == nil {
t.Error("publish missing message")
}
if pub["summary"] != "Echo WS" {
t.Errorf("publish summary = %v, want Echo WS", pub["summary"])
}
// Both operations should have tags.
for _, opName := range []string{"subscribe", "publish"} {
op := ch[opName].(map[string]any)
tags, ok := op["tags"].([]any)
if !ok || len(tags) == 0 {
t.Errorf("%s missing tags", opName)
} else {
tag := tags[0].(map[string]any)
if tag["name"] != "websocket" {
t.Errorf("%s tag = %v, want websocket", opName, tag["name"])
}
}
}
// Verify schemas are in AsyncAPI components.
components, ok := spec["components"].(map[string]any)
if !ok {
t.Fatal("no components in async spec")
}
schemas, ok := components["schemas"].(map[string]any)
if !ok {
t.Fatal("no schemas in async spec components")
}
if _, ok := schemas["wsServerMsg"]; !ok {
t.Error("missing wsServerMsg schema in async spec")
}
if _, ok := schemas["wsClientMsg"]; !ok {
t.Error("missing wsClientMsg schema in async spec")
}
// Verify WS path is NOT in OpenAPI spec.
w2 := httptest.NewRecorder()
r2 := httptest.NewRequest("GET", "/openapi.json", nil)
api.ServeHTTP(w2, r2)
var oaSpec map[string]any
if err := json.NewDecoder(w2.Body).Decode(&oaSpec); err != nil {
t.Fatalf("decode openapi spec: %v", err)
}
if paths, ok := oaSpec["paths"].(map[string]any); ok {
if _, ok := paths["/ws"]; ok {
t.Error("WS path /ws should not be in OpenAPI spec")
}
}
// Verify schemas are in OpenAPI components (for openapi-typescript).
oaComponents, ok := oaSpec["components"].(map[string]any)
if !ok {
t.Fatal("no components in OpenAPI spec")
}
oaSchemas, ok := oaComponents["schemas"].(map[string]any)
if !ok {
t.Fatal("no schemas in OpenAPI components")
}
if _, ok := oaSchemas["wsServerMsg"]; !ok {
t.Error("missing wsServerMsg schema in OpenAPI components")
}
if _, ok := oaSchemas["wsClientMsg"]; !ok {
t.Error("missing wsClientMsg schema in OpenAPI components")
}
}
func TestHandleWS_OpenAPISchemaProperties(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("echo", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return sender.Send(wsServerMsg(msg))
}),
),
)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/openapi.json", nil)
api.ServeHTTP(w, r)
var spec map[string]any
if err := json.NewDecoder(w.Body).Decode(&spec); err != nil {
t.Fatalf("decode spec: %v", err)
}
oaComponents := spec["components"].(map[string]any)
oaSchemas := oaComponents["schemas"].(map[string]any)
// Verify WS schemas have actual properties, not just empty entries.
// This ensures openapi-typescript generates real types (not any).
for _, name := range []string{"wsServerMsg", "wsClientMsg"} {
schema, ok := oaSchemas[name].(map[string]any)
if !ok {
t.Fatalf("missing %s schema in OpenAPI components", name)
}
props, ok := schema["properties"].(map[string]any)
if !ok || len(props) == 0 {
t.Errorf("schema %s has no properties; would resolve to any in generated client", name)
}
if _, ok := props["text"]; !ok {
t.Errorf("schema %s missing 'text' property", name)
}
}
}
func TestHandleWS_AsyncAPISpec_XErrors(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
func(r *http.Request, sender *shiftapi.WSSender, _ struct{}) (struct{}, error) {
return struct{}{}, nil
},
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return nil
}),
),
shiftapi.WithError[*wsAuthError](http.StatusUnauthorized),
)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/asyncapi.json", nil)
api.ServeHTTP(w, r)
var spec map[string]any
if err := json.NewDecoder(w.Body).Decode(&spec); err != nil {
t.Fatalf("decode spec: %v", err)
}
channels := spec["channels"].(map[string]any)
ch := channels["/ws"].(map[string]any)
xErrors, ok := ch["x-errors"].(map[string]any)
if !ok {
t.Fatal("no x-errors on /ws channel")
}
// Should have 4401 for wsAuthError and 4422 for ValidationError.
if _, ok := xErrors["4401"]; !ok {
t.Error("missing 4401 in x-errors")
}
if _, ok := xErrors["4422"]; !ok {
t.Error("missing 4422 in x-errors")
}
// Verify the 4401 entry references wsAuthError schema.
entry := xErrors["4401"].(map[string]any)
ref, _ := entry["$ref"].(string)
if ref != "#/components/schemas/wsAuthError" {
t.Errorf("4401 $ref = %q, want #/components/schemas/wsAuthError", ref)
}
// Verify the schema is registered in both specs.
components := spec["components"].(map[string]any)
schemas := components["schemas"].(map[string]any)
if _, ok := schemas["wsAuthError"]; !ok {
t.Error("missing wsAuthError schema in AsyncAPI components")
}
}
func TestHandleWS_InputParsing(t *testing.T) {
api := shiftapi.New()
type Input struct {
Channel string `query:"channel" validate:"required"`
}
type inputState struct {
Channel string
}
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
func(r *http.Request, sender *shiftapi.WSSender, in Input) (*inputState, error) {
return &inputState{Channel: in.Channel}, nil
},
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, state *inputState, msg wsClientMsg) error {
return sender.Send(wsServerMsg{Text: "channel=" + state.Channel})
}),
),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/ws?channel=general", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// Send a message to trigger the handler.
if err := wsjson.Write(ctx, conn, map[string]any{"type": "msg", "data": map[string]any{"text": "hi"}}); err != nil {
t.Fatalf("write: %v", err)
}
var envelope struct {
Type string `json:"type"`
Data wsServerMsg `json:"data"`
}
if err := wsjson.Read(ctx, conn, &envelope); err != nil {
t.Fatalf("read: %v", err)
}
if envelope.Data.Text != "channel=general" {
t.Errorf("got %q, want %q", envelope.Data.Text, "channel=general")
}
conn.Close(websocket.StatusNormalClosure, "") //nolint:errcheck
}
func TestHandleWS_OnDispatch(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /echo",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("echo", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return sender.Send(wsServerMsg{Text: "echo: " + msg.Text})
}),
),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/echo", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// Send and receive multiple messages.
for _, text := range []string{"hello", "world"} {
envelope := map[string]any{"type": "echo", "data": map[string]any{"text": text}}
if err := wsjson.Write(ctx, conn, envelope); err != nil {
t.Fatalf("write %q: %v", text, err)
}
var resp struct {
Type string `json:"type"`
Data wsServerMsg `json:"data"`
}
if err := wsjson.Read(ctx, conn, &resp); err != nil {
t.Fatalf("read: %v", err)
}
want := "echo: " + text
if resp.Data.Text != want {
t.Errorf("got %q, want %q", resp.Data.Text, want)
}
}
conn.Close(websocket.StatusNormalClosure, "") //nolint:errcheck
}
func TestHandleWS_AutoWrapSend(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("ping", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return sender.Send(wsServerMsg{Text: "pong"})
}),
),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/ws", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// Send a message
if err := wsjson.Write(ctx, conn, map[string]any{"type": "ping", "data": map[string]any{"text": "hi"}}); err != nil {
t.Fatalf("write: %v", err)
}
// Read — should be wrapped in envelope {"type":"server","data":{...}}
var envelope struct {
Type string `json:"type"`
Data wsServerMsg `json:"data"`
}
if err := wsjson.Read(ctx, conn, &envelope); err != nil {
t.Fatalf("read: %v", err)
}
if envelope.Type != "server" {
t.Errorf("envelope.Type = %q, want %q", envelope.Type, "server")
}
if envelope.Data.Text != "pong" {
t.Errorf("envelope.Data.Text = %q, want %q", envelope.Data.Text, "pong")
}
conn.Close(websocket.StatusNormalClosure, "") //nolint:errcheck
}
func TestHandleWS_ErrorBeforeUpgrade(t *testing.T) {
api := shiftapi.New()
type Input struct {
Token string `query:"token" validate:"required"`
}
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
func(r *http.Request, sender *shiftapi.WSSender, in Input) (struct{}, error) {
return struct{}{}, nil
},
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return nil
}),
),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
// Missing required query param → connection opens, error sent as first frame.
conn, _, err := websocket.Dial(ctx, srv.URL+"/ws", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// First frame should be a structured error envelope.
var errResp shiftapi.ValidationError
frame := readWSError(t, ctx, conn, &errResp)
if frame.Code != 4422 {
t.Errorf("error frame code = %d, want 4422", frame.Code)
}
if errResp.Message != "validation failed" {
t.Errorf("message = %q, want %q", errResp.Message, "validation failed")
}
// Connection should close with 4422.
_, _, err = conn.Read(ctx)
if websocket.CloseStatus(err) != 4422 {
t.Errorf("close code = %d, want 4422", websocket.CloseStatus(err))
}
}
func TestHandleWS_ErrorAfterUpgrade(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return fmt.Errorf("something went wrong")
}),
),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/ws", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// Send a message to trigger the handler error.
if err := wsjson.Write(ctx, conn, map[string]any{"type": "msg", "data": map[string]any{"text": "hi"}}); err != nil {
t.Fatalf("write: %v", err)
}
// The server should close the connection with StatusInternalError.
_, _, err = conn.Read(ctx)
if err == nil {
t.Fatal("expected error from read")
}
status := websocket.CloseStatus(err)
if status != websocket.StatusInternalError {
t.Errorf("close status = %d, want %d", status, websocket.StatusInternalError)
}
}
func TestHandleWS_ErrorAfterUpgrade_Registered(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return &wsAuthError{Message: "token expired", Realm: "api"}
}),
),
shiftapi.WithError[*wsAuthError](http.StatusUnauthorized),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/ws", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// Send a message to trigger the handler error.
if err := wsjson.Write(ctx, conn, map[string]any{"type": "msg", "data": map[string]any{"text": "hi"}}); err != nil {
t.Fatalf("write: %v", err)
}
// Should receive a structured error envelope, not a data frame.
var errResp wsAuthError
frame := readWSError(t, ctx, conn, &errResp)
if frame.Code != 4401 {
t.Errorf("error frame code = %d, want 4401", frame.Code)
}
if errResp.Message != "token expired" {
t.Errorf("message = %q, want %q", errResp.Message, "token expired")
}
if errResp.Realm != "api" {
t.Errorf("realm = %q, want %q", errResp.Realm, "api")
}
// Connection should close with 4401.
_, _, err = conn.Read(ctx)
if websocket.CloseStatus(err) != 4401 {
t.Errorf("close code = %d, want 4401", websocket.CloseStatus(err))
}
}
// wsAuthError is an error type registered via WithError for setup error tests.
type wsAuthError struct {
Message string `json:"message"`
Realm string `json:"realm"`
}
func (e *wsAuthError) Error() string { return e.Message }
func TestHandleWS_SetupErrorRegistered(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
func(r *http.Request, sender *shiftapi.WSSender, _ struct{}) (struct{}, error) {
return struct{}{}, &wsAuthError{Message: "bad token", Realm: "api"}
},
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return nil
}),
),
shiftapi.WithError[*wsAuthError](http.StatusUnauthorized),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/ws", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// First frame should be a structured error envelope.
var errResp wsAuthError
frame := readWSError(t, ctx, conn, &errResp)
if frame.Code != 4401 {
t.Errorf("error frame code = %d, want 4401", frame.Code)
}
if errResp.Message != "bad token" {
t.Errorf("message = %q, want %q", errResp.Message, "bad token")
}
if errResp.Realm != "api" {
t.Errorf("realm = %q, want %q", errResp.Realm, "api")
}
// Connection should close with 4401.
_, _, err = conn.Read(ctx)
if websocket.CloseStatus(err) != 4401 {
t.Errorf("close code = %d, want 4401", websocket.CloseStatus(err))
}
}
func TestHandleWS_SetupErrorUnregistered(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
func(r *http.Request, sender *shiftapi.WSSender, _ struct{}) (struct{}, error) {
return struct{}{}, fmt.Errorf("unexpected failure")
},
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return nil
}),
),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/ws", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// Unregistered error → no error frame, just StatusInternalError close.
_, _, err = conn.Read(ctx)
if err == nil {
t.Fatal("expected error from read")
}
if websocket.CloseStatus(err) != websocket.StatusInternalError {
t.Errorf("close status = %d, want %d", websocket.CloseStatus(err), websocket.StatusInternalError)
}
}
func TestHandleWS_SetupValidationError(t *testing.T) {
api := shiftapi.New()
type SetupInput struct {
Code string `query:"code"`
}
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
func(r *http.Request, sender *shiftapi.WSSender, in SetupInput) (struct{}, error) {
if in.Code != "secret" {
return struct{}{}, &shiftapi.ValidationError{
Message: "validation failed",
Errors: []shiftapi.FieldError{{Field: "code", Message: "invalid code"}},
}
}
return struct{}{}, nil
},
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return nil
}),
),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/ws?code=wrong", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// ValidationError is always matched → sent as error envelope with 4422.
var errResp shiftapi.ValidationError
frame := readWSError(t, ctx, conn, &errResp)
if frame.Code != 4422 {
t.Errorf("error frame code = %d, want 4422", frame.Code)
}
if errResp.Message != "validation failed" {
t.Errorf("message = %q, want %q", errResp.Message, "validation failed")
}
if len(errResp.Errors) != 1 || errResp.Errors[0].Field != "code" {
t.Errorf("field errors = %v, want [{code invalid code}]", errResp.Errors)
}
_, _, err = conn.Read(ctx)
if websocket.CloseStatus(err) != 4422 {
t.Errorf("close code = %d, want 4422", websocket.CloseStatus(err))
}
}
func TestHandleWS_WSOnUnknownMessage(t *testing.T) {
api := shiftapi.New()
var gotType string
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return sender.Send(wsServerMsg{Text: "ok"})
}),
shiftapi.WSOnUnknownMessage(func(sender *shiftapi.WSSender, _ struct{}, msgType string, data json.RawMessage) {
gotType = msgType
sender.Send(wsServerMsg{Text: "unknown: " + msgType}) //nolint:errcheck
}),
),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/ws", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// Send an unknown message type.
if err := wsjson.Write(ctx, conn, map[string]any{"type": "bogus", "data": map[string]any{"text": "hi"}}); err != nil {
t.Fatalf("write: %v", err)
}
// The callback should have sent a response.
var envelope struct {
Type string `json:"type"`
Data wsServerMsg `json:"data"`
}
if err := wsjson.Read(ctx, conn, &envelope); err != nil {
t.Fatalf("read: %v", err)
}
if envelope.Data.Text != "unknown: bogus" {
t.Errorf("got %q, want %q", envelope.Data.Text, "unknown: bogus")
}
if gotType != "bogus" {
t.Errorf("gotType = %q, want %q", gotType, "bogus")
}
conn.Close(websocket.StatusNormalClosure, "") //nolint:errcheck
}
func TestHandleWS_WithWSAcceptOptions(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, _ struct{}, msg wsClientMsg) error {
return sender.Send(wsServerMsg{Text: "ok"})
}),
),
shiftapi.WithWSAcceptOptions(shiftapi.WSAcceptOptions{
Subprotocols: []string{"test-proto"},
}),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, resp, err := websocket.Dial(ctx, srv.URL+"/ws", &websocket.DialOptions{
Subprotocols: []string{"test-proto"},
})
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// Verify the subprotocol was negotiated.
if got := resp.Header.Get("Sec-WebSocket-Protocol"); got != "test-proto" {
t.Errorf("subprotocol = %q, want %q", got, "test-proto")
}
// Send a message to trigger the handler.
if err := wsjson.Write(ctx, conn, map[string]any{"type": "msg", "data": map[string]any{"text": "hi"}}); err != nil {
t.Fatalf("write: %v", err)
}
var envelope struct {
Type string `json:"type"`
Data wsServerMsg `json:"data"`
}
if err := wsjson.Read(ctx, conn, &envelope); err != nil {
t.Fatalf("read: %v", err)
}
if envelope.Data.Text != "ok" {
t.Errorf("got %q, want %q", envelope.Data.Text, "ok")
}
conn.Close(websocket.StatusNormalClosure, "") //nolint:errcheck
}
func TestHandleWS_PathParams(t *testing.T) {
api := shiftapi.New()
type Input struct {
ID string `path:"id"`
}
type pathState struct {
ID string
}
shiftapi.HandleWS(api, "GET /rooms/{id}",
shiftapi.Websocket(
func(r *http.Request, sender *shiftapi.WSSender, in Input) (*pathState, error) {
return &pathState{ID: in.ID}, nil
},
shiftapi.WSSends(shiftapi.WSMessageType[wsServerMsg]("server")),
shiftapi.WSOn("msg", func(sender *shiftapi.WSSender, state *pathState, msg wsClientMsg) error {
return sender.Send(wsServerMsg{Text: "room=" + state.ID})
}),
),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/rooms/abc", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// Send a message to trigger the handler.
if err := wsjson.Write(ctx, conn, map[string]any{"type": "msg", "data": map[string]any{"text": "hi"}}); err != nil {
t.Fatalf("write: %v", err)
}
var envelope struct {
Type string `json:"type"`
Data wsServerMsg `json:"data"`
}
if err := wsjson.Read(ctx, conn, &envelope); err != nil {
t.Fatalf("read: %v", err)
}
if envelope.Data.Text != "room=abc" {
t.Errorf("got %q, want %q", envelope.Data.Text, "room=abc")
}
conn.Close(websocket.StatusNormalClosure, "") //nolint:errcheck
}
// --- Multi-message (WSSends) tests ---
type wsChatMsg struct {
User string `json:"user"`
Text string `json:"text"`
}
type wsSystemMsg struct {
Info string `json:"info"`
}
type wsUserMsg struct {
Text string `json:"text"`
}
type wsUserCmd struct {
Command string `json:"command"`
}
func TestHandleWS_MultiTypeDispatch(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(
shiftapi.WSMessageType[wsChatMsg]("chat"),
shiftapi.WSMessageType[wsSystemMsg]("system"),
),
shiftapi.WSOn("message", func(sender *shiftapi.WSSender, _ struct{}, m wsUserMsg) error {
return sender.Send(wsChatMsg{User: "server", Text: "got: " + m.Text})
}),
shiftapi.WSOn("command", func(sender *shiftapi.WSSender, _ struct{}, cmd wsUserCmd) error {
return sender.Send(wsSystemMsg{Info: "executed: " + cmd.Command})
}),
),
)
srv := httptest.NewServer(api)
defer srv.Close()
ctx := context.Background()
conn, _, err := websocket.Dial(ctx, srv.URL+"/ws", nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow() //nolint:errcheck
// Send a "message" type
if err := wsjson.Write(ctx, conn, map[string]any{"type": "message", "data": map[string]any{"text": "hello"}}); err != nil {
t.Fatalf("write: %v", err)
}
var msg1 struct {
Type string `json:"type"`
Data wsChatMsg `json:"data"`
}
if err := wsjson.Read(ctx, conn, &msg1); err != nil {
t.Fatalf("read 1: %v", err)
}
if msg1.Type != "chat" {
t.Errorf("msg1.Type = %q, want %q", msg1.Type, "chat")
}
if msg1.Data.Text != "got: hello" {
t.Errorf("msg1.Data.Text = %q, want %q", msg1.Data.Text, "got: hello")
}
// Send a "command" type
if err := wsjson.Write(ctx, conn, map[string]any{"type": "command", "data": map[string]any{"command": "quit"}}); err != nil {
t.Fatalf("write: %v", err)
}
var msg2 struct {
Type string `json:"type"`
Data wsSystemMsg `json:"data"`
}
if err := wsjson.Read(ctx, conn, &msg2); err != nil {
t.Fatalf("read 2: %v", err)
}
if msg2.Type != "system" {
t.Errorf("msg2.Type = %q, want %q", msg2.Type, "system")
}
if msg2.Data.Info != "executed: quit" {
t.Errorf("msg2.Data.Info = %q, want %q", msg2.Data.Info, "executed: quit")
}
conn.Close(websocket.StatusNormalClosure, "") //nolint:errcheck
}
func TestHandleWS_WithMessages_AsyncAPISpec(t *testing.T) {
api := shiftapi.New()
shiftapi.HandleWS(api, "GET /ws",
shiftapi.Websocket(
noSetup,
shiftapi.WSSends(
shiftapi.WSMessageType[wsChatMsg]("chat"),
shiftapi.WSMessageType[wsSystemMsg]("system"),
),
shiftapi.WSOn("message", func(sender *shiftapi.WSSender, _ struct{}, m wsUserMsg) error {
return nil
}),
shiftapi.WSOn("command", func(sender *shiftapi.WSSender, _ struct{}, cmd wsUserCmd) error {
return nil
}),
),
)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/asyncapi.json", nil)
api.ServeHTTP(w, r)